'use client'

import { use, useState } from 'react'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible'
import { Pagination } from '@/components/shared/pagination'
import { toast } from 'sonner'
import {
  ArrowLeft,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  ChevronDown,
  RotateCcw,
  Loader2,
  ShieldCheck,
} from 'lucide-react'
import { cn } from '@/lib/utils'

const OUTCOME_BADGES: Record<
  string,
  { variant: 'default' | 'destructive' | 'secondary' | 'outline'; icon: React.ReactNode; label: string }
> = {
  PASSED: {
    variant: 'default',
    icon: <CheckCircle2 className="mr-1 h-3 w-3" />,
    label: 'Passed',
  },
  FILTERED_OUT: {
    variant: 'destructive',
    icon: <XCircle className="mr-1 h-3 w-3" />,
    label: 'Filtered Out',
  },
  FLAGGED: {
    variant: 'secondary',
    icon: <AlertTriangle className="mr-1 h-3 w-3" />,
    label: 'Flagged',
  },
}

export default function FilteringResultsPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id: roundId } = use(params)

  const [outcomeFilter, setOutcomeFilter] = useState<string>('')
  const [page, setPage] = useState(1)
  const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set())
  const [overrideDialog, setOverrideDialog] = useState<{
    id: string
    currentOutcome: string
  } | null>(null)
  const [overrideOutcome, setOverrideOutcome] = useState<string>('PASSED')
  const [overrideReason, setOverrideReason] = useState('')

  const perPage = 20

  const { data, isLoading, refetch } = trpc.filtering.getResults.useQuery({
    roundId,
    outcome: outcomeFilter
      ? (outcomeFilter as 'PASSED' | 'FILTERED_OUT' | 'FLAGGED')
      : undefined,
    page,
    perPage,
  })

  const utils = trpc.useUtils()
  const overrideResult = trpc.filtering.overrideResult.useMutation()
  const reinstateProject = trpc.filtering.reinstateProject.useMutation()

  const toggleRow = (id: string) => {
    const next = new Set(expandedRows)
    if (next.has(id)) next.delete(id)
    else next.add(id)
    setExpandedRows(next)
  }

  const handleOverride = async () => {
    if (!overrideDialog || !overrideReason.trim()) return
    try {
      await overrideResult.mutateAsync({
        id: overrideDialog.id,
        finalOutcome: overrideOutcome as 'PASSED' | 'FILTERED_OUT' | 'FLAGGED',
        reason: overrideReason.trim(),
      })
      toast.success('Result overridden')
      setOverrideDialog(null)
      setOverrideReason('')
      refetch()
      utils.project.list.invalidate()
    } catch {
      toast.error('Failed to override result')
    }
  }

  const handleReinstate = async (projectId: string) => {
    try {
      await reinstateProject.mutateAsync({ roundId, projectId })
      toast.success('Project reinstated')
      refetch()
      utils.project.list.invalidate()
    } catch {
      toast.error('Failed to reinstate project')
    }
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-9 w-48" />
        <Skeleton className="h-96 w-full" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" asChild className="-ml-4">
          <Link href={`/admin/rounds/${roundId}`}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Round
          </Link>
        </Button>
      </div>

      <div>
        <h1 className="text-2xl font-semibold tracking-tight">
          Filtering Results
        </h1>
        <p className="text-muted-foreground">
          Review and override filtering outcomes
        </p>
      </div>

      {/* Outcome Filter Tabs */}
      <div className="flex gap-2">
        {['', 'PASSED', 'FILTERED_OUT', 'FLAGGED'].map((outcome) => (
          <Button
            key={outcome || 'all'}
            variant={outcomeFilter === outcome ? 'default' : 'outline'}
            size="sm"
            onClick={() => {
              setOutcomeFilter(outcome)
              setPage(1)
            }}
          >
            {outcome ? (
              <>
                {OUTCOME_BADGES[outcome].icon}
                {OUTCOME_BADGES[outcome].label}
              </>
            ) : (
              'All'
            )}
          </Button>
        ))}
      </div>

      {/* Results Table */}
      {data && data.results.length > 0 ? (
        <>
          <Card>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Project</TableHead>
                  <TableHead>Category</TableHead>
                  <TableHead>Outcome</TableHead>
                  <TableHead className="w-[300px]">AI Reason</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data.results.map((result) => {
                  const isExpanded = expandedRows.has(result.id)
                  const effectiveOutcome =
                    result.finalOutcome || result.outcome
                  const badge = OUTCOME_BADGES[effectiveOutcome]

                  // Extract AI reasoning from aiScreeningJson
                  const aiScreening = result.aiScreeningJson as Record<string, {
                    meetsCriteria?: boolean
                    confidence?: number
                    reasoning?: string
                    qualityScore?: number
                    spamRisk?: boolean
                  }> | null
                  const firstAiResult = aiScreening ? Object.values(aiScreening)[0] : null
                  const aiReasoning = firstAiResult?.reasoning

                  return (
                    <>
                      <TableRow
                        key={result.id}
                        className="cursor-pointer hover:bg-muted/50"
                        onClick={() => toggleRow(result.id)}
                      >
                        <TableCell>
                          <div>
                            <p className="font-medium">
                              {result.project.title}
                            </p>
                            <p className="text-sm text-muted-foreground">
                              {result.project.teamName}
                              {result.project.country && ` · ${result.project.country}`}
                            </p>
                          </div>
                        </TableCell>
                        <TableCell>
                          {result.project.competitionCategory ? (
                            <Badge variant="outline">
                              {result.project.competitionCategory.replace(
                                '_',
                                ' '
                              )}
                            </Badge>
                          ) : (
                            '-'
                          )}
                        </TableCell>
                        <TableCell>
                          <div className="space-y-1">
                            <Badge variant={badge?.variant || 'secondary'}>
                              {badge?.icon}
                              {badge?.label || effectiveOutcome}
                            </Badge>
                            {result.overriddenByUser && (
                              <p className="text-xs text-muted-foreground">
                                Overridden by {result.overriddenByUser.name || result.overriddenByUser.email}
                              </p>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          {aiReasoning ? (
                            <div className="space-y-1">
                              <p className="text-sm line-clamp-2">
                                {aiReasoning}
                              </p>
                              {firstAiResult && (
                                <div className="flex gap-2 text-xs text-muted-foreground">
                                  {firstAiResult.confidence !== undefined && (
                                    <span>Confidence: {Math.round(firstAiResult.confidence * 100)}%</span>
                                  )}
                                  {firstAiResult.qualityScore !== undefined && (
                                    <span>Quality: {firstAiResult.qualityScore}/10</span>
                                  )}
                                  {firstAiResult.spamRisk && (
                                    <Badge variant="destructive" className="text-xs">Spam Risk</Badge>
                                  )}
                                </div>
                              )}
                            </div>
                          ) : (
                            <span className="text-sm text-muted-foreground italic">
                              No AI screening
                            </span>
                          )}
                        </TableCell>
                        <TableCell className="text-right">
                          <div
                            className="flex justify-end gap-1"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                setOverrideOutcome('PASSED')
                                setOverrideDialog({
                                  id: result.id,
                                  currentOutcome: effectiveOutcome,
                                })
                              }}
                            >
                              <ShieldCheck className="mr-1 h-3 w-3" />
                              Override
                            </Button>
                            {effectiveOutcome === 'FILTERED_OUT' && (
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() =>
                                  handleReinstate(result.projectId)
                                }
                                disabled={reinstateProject.isPending}
                              >
                                <RotateCcw className="mr-1 h-3 w-3" />
                                Reinstate
                              </Button>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                      {isExpanded && (
                        <TableRow key={`${result.id}-detail`}>
                          <TableCell colSpan={5} className="bg-muted/30">
                            <div className="p-4 space-y-4">
                              {/* Rule Results (non-AI rules only, AI shown separately) */}
                              <div>
                                <p className="text-sm font-medium mb-2">
                                  Rule Results
                                </p>
                                {result.ruleResultsJson &&
                                Array.isArray(result.ruleResultsJson) ? (
                                  <div className="space-y-2">
                                    {(
                                      result.ruleResultsJson as Array<{
                                        ruleName: string
                                        ruleType: string
                                        passed: boolean
                                        action: string
                                        reasoning?: string
                                      }>
                                    ).filter((rr) => rr.ruleType !== 'AI_SCREENING').map((rr, i) => (
                                      <div
                                        key={i}
                                        className="flex items-start gap-2 text-sm"
                                      >
                                        {rr.passed ? (
                                          <CheckCircle2 className="h-4 w-4 text-green-600 mt-0.5 flex-shrink-0" />
                                        ) : (
                                          <XCircle className="h-4 w-4 text-red-600 mt-0.5 flex-shrink-0" />
                                        )}
                                        <div>
                                          <div className="flex items-center gap-2">
                                            <span className="font-medium">
                                              {rr.ruleName}
                                            </span>
                                            <Badge variant="outline" className="text-xs">
                                              {rr.ruleType.replace('_', ' ')}
                                            </Badge>
                                          </div>
                                          {rr.reasoning && (
                                            <p className="text-muted-foreground mt-0.5">
                                              {rr.reasoning}
                                            </p>
                                          )}
                                        </div>
                                      </div>
                                    ))}
                                  </div>
                                ) : (
                                  <p className="text-sm text-muted-foreground">
                                    No detailed rule results available
                                  </p>
                                )}
                              </div>

                              {/* AI Screening Details */}
                              {aiScreening && Object.keys(aiScreening).length > 0 && (
                                <div>
                                  <p className="text-sm font-medium mb-2">
                                    AI Screening Analysis
                                  </p>
                                  <div className="space-y-3">
                                    {Object.entries(aiScreening).map(([ruleId, screening]) => (
                                      <div key={ruleId} className="p-3 bg-background rounded-lg border">
                                        <div className="flex items-center gap-2 mb-2">
                                          {screening.meetsCriteria ? (
                                            <CheckCircle2 className="h-4 w-4 text-green-600" />
                                          ) : (
                                            <XCircle className="h-4 w-4 text-red-600" />
                                          )}
                                          <span className="font-medium text-sm">
                                            {screening.meetsCriteria ? 'Meets Criteria' : 'Does Not Meet Criteria'}
                                          </span>
                                          {screening.spamRisk && (
                                            <Badge variant="destructive" className="text-xs">
                                              <AlertTriangle className="h-3 w-3 mr-1" />
                                              Spam Risk
                                            </Badge>
                                          )}
                                        </div>
                                        {screening.reasoning && (
                                          <p className="text-sm text-muted-foreground mb-2">
                                            {screening.reasoning}
                                          </p>
                                        )}
                                        <div className="flex gap-4 text-xs text-muted-foreground">
                                          {screening.confidence !== undefined && (
                                            <span>
                                              Confidence: <strong>{Math.round(screening.confidence * 100)}%</strong>
                                            </span>
                                          )}
                                          {screening.qualityScore !== undefined && (
                                            <span>
                                              Quality Score: <strong>{screening.qualityScore}/10</strong>
                                            </span>
                                          )}
                                        </div>
                                      </div>
                                    ))}
                                  </div>
                                </div>
                              )}

                              {/* Override Info */}
                              {result.overriddenByUser && (
                                <div className="pt-3 border-t">
                                  <p className="text-sm font-medium mb-1">Manual Override</p>
                                  <p className="text-sm text-muted-foreground">
                                    Overridden to <strong>{result.finalOutcome}</strong> by{' '}
                                    {result.overriddenByUser.name || result.overriddenByUser.email}
                                  </p>
                                  {result.overrideReason && (
                                    <p className="text-sm text-muted-foreground mt-1">
                                      Reason: {result.overrideReason}
                                    </p>
                                  )}
                                </div>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      )}
                    </>
                  )
                })}
              </TableBody>
            </Table>
          </Card>

          <Pagination
            page={data.page}
            totalPages={data.totalPages}
            total={data.total}
            perPage={perPage}
            onPageChange={setPage}
          />
        </>
      ) : (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <CheckCircle2 className="h-12 w-12 text-muted-foreground/50" />
            <p className="mt-2 font-medium">No results found</p>
            <p className="text-sm text-muted-foreground">
              {outcomeFilter
                ? 'No results match this filter'
                : 'Run filtering rules to generate results'}
            </p>
          </CardContent>
        </Card>
      )}

      {/* Override Dialog */}
      <Dialog
        open={!!overrideDialog}
        onOpenChange={(open) => {
          if (!open) {
            setOverrideDialog(null)
            setOverrideReason('')
          }
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Override Filtering Result</DialogTitle>
            <DialogDescription>
              Change the outcome for this project. This will be logged in the
              audit trail.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>New Outcome</Label>
              <Select
                value={overrideOutcome}
                onValueChange={setOverrideOutcome}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="PASSED">Passed</SelectItem>
                  <SelectItem value="FILTERED_OUT">Filtered Out</SelectItem>
                  <SelectItem value="FLAGGED">Flagged</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Reason</Label>
              <Input
                value={overrideReason}
                onChange={(e) => setOverrideReason(e.target.value)}
                placeholder="Explain why you're overriding..."
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setOverrideDialog(null)}
            >
              Cancel
            </Button>
            <Button
              onClick={handleOverride}
              disabled={
                overrideResult.isPending || !overrideReason.trim()
              }
            >
              {overrideResult.isPending && (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              )}
              Override
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
