'use client'

import { useState } from 'react'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Button } from '@/components/ui/button'
import { AnimatedCard } from '@/components/shared/animated-container'
import { CountryDisplay } from '@/components/shared/country-display'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Filter, ChevronDown, ChevronUp, ChevronLeft, ChevronRight } from 'lucide-react'
import { cn, formatCategory } from '@/lib/utils'

type AIScreeningData = {
  meetsCriteria?: boolean
  confidence?: number
  reasoning?: string
  qualityScore?: number
  spamRisk?: boolean
}

function parseAIData(json: unknown): AIScreeningData | null {
  if (!json || typeof json !== 'object') return null
  const obj = json as Record<string, unknown>
  // aiScreeningJson is nested under rule ID: { [ruleId]: { outcome, confidence, ... } }
  if (!('outcome' in obj) && !('reasoning' in obj)) {
    const keys = Object.keys(obj)
    if (keys.length > 0) {
      const inner = obj[keys[0]]
      if (inner && typeof inner === 'object') return inner as AIScreeningData
    }
    return null
  }
  return obj as unknown as AIScreeningData
}

export function FilteringPanel({ roundId }: { roundId: string }) {
  const [outcomeFilter, setOutcomeFilter] = useState<string>('ALL')
  const [page, setPage] = useState(1)
  const [expandedId, setExpandedId] = useState<string | null>(null)

  const { data: roundStats, isLoading: statsLoading } = trpc.analytics.getRoundTypeStats.useQuery(
    { roundId },
    { refetchInterval: 30_000 },
  )

  const { data: resultStats } = trpc.analytics.getFilteringResultStats.useQuery(
    { roundId },
    { refetchInterval: 30_000 },
  )

  const { data: results, isLoading: resultsLoading } = trpc.analytics.getFilteringResults.useQuery(
    {
      roundId,
      outcome: outcomeFilter === 'ALL' ? undefined : outcomeFilter as 'PASSED' | 'FILTERED_OUT' | 'FLAGGED',
      page,
      perPage: 15,
    },
    { refetchInterval: 30_000 },
  )

  const stats = roundStats?.stats as {
    totalScreened: number
    passed: number
    filteredOut: number
    flagged: number
    passRate: number
  } | undefined

  const total = stats?.totalScreened ?? 0

  const outcomeColor: Record<string, string> = {
    PASSED: 'bg-emerald-500',
    FILTERED_OUT: 'bg-rose-500',
    FLAGGED: 'bg-amber-500',
  }

  return (
    <div className="space-y-4">
      {/* Screening Stats Bar */}
      {statsLoading ? (
        <Skeleton className="h-24 rounded-lg" />
      ) : stats ? (
        <Card className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Filter className="h-4 w-4 text-brand-teal" />
            <span className="text-sm font-semibold">Screening Results</span>
            <Badge variant="secondary" className="ml-auto tabular-nums">{total} screened</Badge>
          </div>
          {/* Segmented bar */}
          {total > 0 && (
            <div className="flex h-3 rounded-full overflow-hidden bg-muted">
              <div
                className="bg-emerald-500 transition-all"
                style={{ width: `${(stats.passed / total) * 100}%` }}
                title={`Passed: ${stats.passed}`}
              />
              <div
                className="bg-rose-500 transition-all"
                style={{ width: `${(stats.filteredOut / total) * 100}%` }}
                title={`Filtered: ${stats.filteredOut}`}
              />
              <div
                className="bg-amber-500 transition-all"
                style={{ width: `${(stats.flagged / total) * 100}%` }}
                title={`Flagged: ${stats.flagged}`}
              />
            </div>
          )}
          <div className="flex justify-between mt-2 text-xs text-muted-foreground">
            <span className="flex items-center gap-1">
              <span className="h-2 w-2 rounded-full bg-emerald-500 inline-block" />
              Passed {stats.passed}
            </span>
            <span className="flex items-center gap-1">
              <span className="h-2 w-2 rounded-full bg-rose-500 inline-block" />
              Filtered {stats.filteredOut}
            </span>
            <span className="flex items-center gap-1">
              <span className="h-2 w-2 rounded-full bg-amber-500 inline-block" />
              Flagged {stats.flagged}
            </span>
          </div>
        </Card>
      ) : null}

      {/* Detailed Stats */}
      {resultStats && (
        <div className="grid grid-cols-3 gap-3">
          <Card className="p-3 text-center">
            <p className="text-xl font-semibold tabular-nums text-emerald-600">
              {resultStats.passed}
            </p>
            <p className="text-xs text-muted-foreground">Passed</p>
          </Card>
          <Card className="p-3 text-center">
            <p className="text-xl font-semibold tabular-nums text-amber-600">
              {resultStats.overridden}
            </p>
            <p className="text-xs text-muted-foreground">Overridden</p>
          </Card>
          <Card className="p-3 text-center">
            <p className="text-xl font-semibold tabular-nums">
              {resultStats.total > 0 ? Math.round((resultStats.passed / resultStats.total) * 100) : 0}%
            </p>
            <p className="text-xs text-muted-foreground">Pass Rate</p>
          </Card>
        </div>
      )}

      {/* AI Results Table */}
      <AnimatedCard index={1}>
        <Card>
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm">AI Screening Results</CardTitle>
              <Select value={outcomeFilter} onValueChange={(v) => { setOutcomeFilter(v); setPage(1) }}>
                <SelectTrigger className="w-32 h-8 text-xs">
                  <SelectValue placeholder="All" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="ALL">All</SelectItem>
                  <SelectItem value="PASSED">Passed</SelectItem>
                  <SelectItem value="FILTERED_OUT">Filtered</SelectItem>
                  <SelectItem value="FLAGGED">Flagged</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            {resultsLoading ? (
              <div className="p-4 space-y-2">
                {[...Array(5)].map((_, i) => <Skeleton key={i} className="h-10 w-full" />)}
              </div>
            ) : results && results.results.length > 0 ? (
              <>
                <div className="divide-y">
                  {results.results.map((r: any) => (
                    <div key={r.id}>
                      <button
                        type="button"
                        className="w-full text-left px-4 py-2.5 hover:bg-muted/50 transition-colors"
                        onClick={() => setExpandedId(expandedId === r.id ? null : r.id)}
                      >
                        <div className="flex items-center justify-between gap-2">
                          <div className="min-w-0 flex-1">
                            <Link
                              href={`/observer/projects/${r.project?.id}` as Route}
                              className="text-sm font-medium truncate hover:underline"
                              onClick={(e) => e.stopPropagation()}
                            >
                              {r.project?.title ?? 'Unknown'}
                            </Link>
                            <p className="text-xs text-muted-foreground truncate">
                              {formatCategory(r.project?.competitionCategory)} · {r.project?.country ? <CountryDisplay country={r.project.country} /> : ''}
                            </p>
                          </div>
                          <div className="flex items-center gap-2 shrink-0">
                            {(() => {
                              const effectiveOutcome = r.finalOutcome ?? r.outcome
                              return (
                                <>
                                  <span className={cn(
                                    'h-2 w-2 rounded-full',
                                    outcomeColor[effectiveOutcome] ?? 'bg-muted',
                                  )} />
                                  <span className="text-xs">{effectiveOutcome?.replace(/_/g, ' ')}</span>
                                </>
                              )
                            })()}
                            {expandedId === r.id
                              ? <ChevronUp className="h-3 w-3 text-muted-foreground" />
                              : <ChevronDown className="h-3 w-3 text-muted-foreground" />}
                          </div>
                        </div>
                      </button>
                      {expandedId === r.id && (() => {
                        const ai = parseAIData(r.aiScreeningJson)
                        return (
                          <div className="px-4 pb-3 pt-0 space-y-2">
                            {ai?.confidence != null && (
                              <div className="flex items-center gap-3 text-xs">
                                {ai.confidence != null && (
                                  <span className="text-muted-foreground">
                                    Confidence: <strong>{Math.round(ai.confidence * 100)}%</strong>
                                  </span>
                                )}
                                {ai.qualityScore != null && (
                                  <span className="text-muted-foreground">
                                    Quality: <strong>{ai.qualityScore}/10</strong>
                                  </span>
                                )}
                                {ai.spamRisk && (
                                  <Badge variant="destructive" className="text-[10px] px-1.5 py-0">Spam Risk</Badge>
                                )}
                              </div>
                            )}
                            <div className="rounded bg-muted/50 border p-3 text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap">
                              {ai?.reasoning || 'No AI reasoning available'}
                            </div>
                            {r.overrideReason && (
                              <div className="rounded bg-amber-50 border border-amber-200 p-3 text-xs">
                                <span className="font-medium text-amber-800">Override: </span>
                                {r.overrideReason}
                              </div>
                            )}
                          </div>
                        )
                      })()}
                    </div>
                  ))}
                </div>
                {/* Pagination */}
                {results.totalPages > 1 && (
                  <div className="flex items-center justify-between border-t px-4 py-2">
                    <span className="text-xs text-muted-foreground">
                      Page {results.page} of {results.totalPages}
                    </span>
                    <div className="flex gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        disabled={page <= 1}
                        onClick={() => setPage(page - 1)}
                      >
                        <ChevronLeft className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        disabled={page >= results.totalPages}
                        onClick={() => setPage(page + 1)}
                      >
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                )}
              </>
            ) : (
              <div className="p-4 text-sm text-muted-foreground">No screening results yet.</div>
            )}
          </CardContent>
        </Card>
      </AnimatedCard>
    </div>
  )
}
