'use client'

import { Fragment, useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import { cn, formatCategory } from '@/lib/utils'
import { Card, CardContent } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Badge } from '@/components/ui/badge'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Button } from '@/components/ui/button'
import { ChevronLeft, ChevronRight, ChevronDown, ChevronUp } from 'lucide-react'
import { RoundTypeStatsCards } from '@/components/observer/round-type-stats'
import { FilteringScreeningBar } from './filtering-screening-bar'
import { ProjectPreviewDialog } from './project-preview-dialog'
import { CountryDisplay } from '@/components/shared/country-display'

interface FilteringReportTabsProps {
  roundId: string
  programId: string
}

type OutcomeFilter = 'ALL' | 'PASSED' | 'FILTERED_OUT' | 'FLAGGED'

function outcomeTextColor(outcome: string): string {
  switch (outcome) {
    case 'PASSED': return 'text-emerald-700'
    case 'FILTERED_OUT': return 'text-rose-700'
    case 'FLAGGED': return 'text-amber-700'
    default: return 'text-primary'
  }
}

function outcomeBadge(outcome: string) {
  switch (outcome) {
    case 'PASSED':
      return <Badge className="bg-emerald-100 text-emerald-800 border-emerald-200">Passed</Badge>
    case 'FILTERED_OUT':
      return <Badge className="bg-rose-100 text-rose-800 border-rose-200">Filtered Out</Badge>
    case 'FLAGGED':
      return <Badge className="bg-amber-100 text-amber-800 border-amber-200">Flagged</Badge>
    default:
      return <Badge variant="outline">{outcome}</Badge>
  }
}

/** Extract reasoning text from aiScreeningJson */
function extractReasoning(aiScreeningJson: unknown): string | null {
  if (!aiScreeningJson || typeof aiScreeningJson !== 'object' || Array.isArray(aiScreeningJson)) {
    return null
  }
  const obj = aiScreeningJson as Record<string, unknown>
  // Direct reasoning field
  if (typeof obj.reasoning === 'string') return obj.reasoning
  // Nested under rule ID: { [ruleId]: { reasoning, confidence, ... } }
  for (const key of Object.keys(obj)) {
    const inner = obj[key]
    if (inner && typeof inner === 'object' && !Array.isArray(inner)) {
      const innerObj = inner as Record<string, unknown>
      if (typeof innerObj.reasoning === 'string') return innerObj.reasoning
    }
  }
  return null
}

export function FilteringReportTabs({ roundId }: FilteringReportTabsProps) {
  const [outcomeFilter, setOutcomeFilter] = useState<OutcomeFilter>('ALL')
  const [page, setPage] = useState(1)
  const [expandedId, setExpandedId] = useState<string | null>(null)
  const [previewProjectId, setPreviewProjectId] = useState<string | null>(null)
  const perPage = 20

  const { data, isLoading } = trpc.analytics.getFilteringResults.useQuery({
    roundId,
    outcome: outcomeFilter === 'ALL' ? undefined : outcomeFilter,
    page,
    perPage,
  })

  function handleOutcomeChange(value: string) {
    setOutcomeFilter(value as OutcomeFilter)
    setPage(1)
  }

  function toggleExpand(id: string) {
    setExpandedId((prev) => (prev === id ? null : id))
  }

  function openPreview(projectId: string, e: React.MouseEvent) {
    e.stopPropagation()
    setPreviewProjectId(projectId)
  }

  return (
    <div className="space-y-6">
      <RoundTypeStatsCards roundId={roundId} />
      <FilteringScreeningBar roundId={roundId} />

      {/* Filter + count */}
      <div className="flex items-center gap-3">
        <Select value={outcomeFilter} onValueChange={handleOutcomeChange}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="All Outcomes" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="ALL">All Outcomes</SelectItem>
            <SelectItem value="PASSED">Passed</SelectItem>
            <SelectItem value="FILTERED_OUT">Filtered Out</SelectItem>
            <SelectItem value="FLAGGED">Flagged</SelectItem>
          </SelectContent>
        </Select>
        {data && (
          <p className="text-sm text-muted-foreground">
            {data.total} project{data.total !== 1 ? 's' : ''}
          </p>
        )}
      </div>

      {isLoading ? (
        <Skeleton className="h-[400px]" />
      ) : data?.results.length ? (
        <>
          {/* Desktop table */}
          <div className="hidden md:block rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-8" />
                  <TableHead>Project</TableHead>
                  <TableHead>Team</TableHead>
                  <TableHead>Category</TableHead>
                  <TableHead>Country</TableHead>
                  <TableHead>Outcome</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data.results.map((r) => {
                  const effectiveOutcome = r.finalOutcome ?? r.outcome
                  const reasoning = extractReasoning(r.aiScreeningJson)
                  const isExpanded = expandedId === r.id
                  return (
                    <Fragment key={r.id}>
                      <TableRow
                        className="cursor-pointer hover:bg-muted/50"
                        onClick={() => toggleExpand(r.id)}
                      >
                        <TableCell className="w-8 pr-0">
                          {isExpanded ? (
                            <ChevronUp className="h-4 w-4 text-muted-foreground" />
                          ) : (
                            <ChevronDown className="h-4 w-4 text-muted-foreground" />
                          )}
                        </TableCell>
                        <TableCell>
                          <button
                            className={cn('font-medium hover:underline text-left', outcomeTextColor(effectiveOutcome))}
                            onClick={(e) => openPreview(r.project.id, e)}
                          >
                            {r.project.title}
                          </button>
                        </TableCell>
                        <TableCell className="text-muted-foreground">{r.project.teamName}</TableCell>
                        <TableCell className="text-muted-foreground">
                          {formatCategory(r.project.competitionCategory) || '—'}
                        </TableCell>
                        <TableCell className="text-muted-foreground">
                          {r.project.country ? <CountryDisplay country={r.project.country} /> : '—'}
                        </TableCell>
                        <TableCell>{outcomeBadge(effectiveOutcome)}</TableCell>
                      </TableRow>
                      {isExpanded && (
                        <TableRow key={`${r.id}-detail`}>
                          <TableCell colSpan={6} className="bg-muted/30 p-0">
                            <div className="px-6 py-4 space-y-2">
                              {reasoning ? (
                                <div>
                                  <p className="text-xs font-medium text-muted-foreground mb-1">AI Reasoning</p>
                                  <p className="text-sm whitespace-pre-wrap leading-relaxed">{reasoning}</p>
                                </div>
                              ) : (
                                <p className="text-sm text-muted-foreground italic">No AI reasoning available</p>
                              )}
                              {r.overrideReason && (
                                <div className="mt-2">
                                  <p className="text-xs font-medium text-amber-700 mb-1">Override Reason</p>
                                  <p className="text-sm rounded-md bg-amber-50 border border-amber-200 p-2">
                                    {r.overrideReason}
                                  </p>
                                </div>
                              )}
                              {r.project.awardEligibilities.length > 0 && (
                                <div className="mt-2">
                                  <p className="text-xs font-medium text-muted-foreground mb-1">Award Routing</p>
                                  <div className="flex gap-1.5">
                                    {r.project.awardEligibilities.map((ae, i) => (
                                      <Badge key={i} variant="secondary">{ae.award.name}</Badge>
                                    ))}
                                  </div>
                                </div>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      )}
                    </Fragment>
                  )
                })}
              </TableBody>
            </Table>
          </div>

          {/* Mobile card stack */}
          <div className="space-y-3 md:hidden">
            {data.results.map((r) => {
              const effectiveOutcome = r.finalOutcome ?? r.outcome
              const reasoning = extractReasoning(r.aiScreeningJson)
              const isExpanded = expandedId === r.id
              return (
                <Card key={r.id}>
                  <CardContent className="p-4">
                    <div
                      className="w-full text-left cursor-pointer"
                      role="button"
                      tabIndex={0}
                      onClick={() => toggleExpand(r.id)}
                      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') toggleExpand(r.id) }}
                    >
                      <div className="flex items-start justify-between gap-2">
                        <div className="min-w-0">
                          <button
                            className={cn('font-medium text-sm hover:underline text-left truncate block max-w-full', outcomeTextColor(effectiveOutcome))}
                            onClick={(e) => openPreview(r.project.id, e)}
                          >
                            {r.project.title}
                          </button>
                          <p className="text-xs text-muted-foreground mt-0.5">{r.project.teamName}</p>
                        </div>
                        <div className="flex items-center gap-2 shrink-0">
                          {outcomeBadge(effectiveOutcome)}
                          {isExpanded ? (
                            <ChevronUp className="h-4 w-4 text-muted-foreground" />
                          ) : (
                            <ChevronDown className="h-4 w-4 text-muted-foreground" />
                          )}
                        </div>
                      </div>
                      <div className="flex gap-3 text-xs text-muted-foreground mt-1">
                        {r.project.competitionCategory && <span>{formatCategory(r.project.competitionCategory)}</span>}
                        {r.project.country && <span><CountryDisplay country={r.project.country} /></span>}
                      </div>
                    </div>

                    {isExpanded && (
                      <div className="mt-3 pt-3 border-t space-y-2">
                        {reasoning ? (
                          <div>
                            <p className="text-xs font-medium text-muted-foreground mb-1">AI Reasoning</p>
                            <p className="text-sm whitespace-pre-wrap leading-relaxed">{reasoning}</p>
                          </div>
                        ) : (
                          <p className="text-sm text-muted-foreground italic">No AI reasoning available</p>
                        )}
                        {r.overrideReason && (
                          <div>
                            <p className="text-xs font-medium text-amber-700 mb-1">Override Reason</p>
                            <p className="text-sm rounded-md bg-amber-50 border border-amber-200 p-2">
                              {r.overrideReason}
                            </p>
                          </div>
                        )}
                      </div>
                    )}
                  </CardContent>
                </Card>
              )
            })}
          </div>

          {/* Pagination */}
          {data.totalPages > 1 && (
            <div className="flex items-center justify-center gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page === 1}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              {Array.from({ length: Math.min(data.totalPages, 7) }, (_, i) => {
                const pageNum = i + 1
                return (
                  <Button
                    key={pageNum}
                    variant={page === pageNum ? 'default' : 'outline'}
                    size="sm"
                    onClick={() => setPage(pageNum)}
                  >
                    {pageNum}
                  </Button>
                )
              })}
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage((p) => Math.min(data.totalPages, p + 1))}
                disabled={page === data.totalPages}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          )}
        </>
      ) : (
        <Card>
          <CardContent className="flex items-center justify-center py-12">
            <p className="text-sm text-muted-foreground">No filtering results found</p>
          </CardContent>
        </Card>
      )}

      <ProjectPreviewDialog
        projectId={previewProjectId}
        roundId={roundId}
        open={!!previewProjectId}
        onOpenChange={(open) => { if (!open) setPreviewProjectId(null) }}
      />
    </div>
  )
}
