'use client'

import { useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Users, Trophy } from 'lucide-react'
import { RoundTypeStatsCards } from '@/components/observer/round-type-stats'

interface DeliberationReportTabsProps {
  roundId: string
  programId: string
}

function sessionStatusBadge(status: string) {
  switch (status) {
    case 'DELIB_LOCKED':
      return <Badge variant="default">Locked</Badge>
    case 'VOTING':
      return <Badge variant="secondary">Voting</Badge>
    case 'TALLYING':
      return <Badge className="bg-amber-100 text-amber-800 border-amber-200">Tallying</Badge>
    case 'RUNOFF':
      return <Badge className="bg-rose-100 text-rose-800 border-rose-200">Runoff</Badge>
    case 'DELIB_OPEN':
      return <Badge variant="outline">Open</Badge>
    default:
      return <Badge variant="outline">{status}</Badge>
  }
}

function sessionModeBadge(mode: string) {
  return <Badge variant="outline">{mode.charAt(0) + mode.slice(1).toLowerCase()}</Badge>
}

function SessionsTab({ roundId }: { roundId: string }) {
  const { data: sessions, isLoading } =
    trpc.analytics.getDeliberationSessions.useQuery({ roundId })

  if (isLoading) return <Skeleton className="h-[350px]" />

  if (!sessions?.length) {
    return (
      <Card>
        <CardContent className="flex flex-col items-center justify-center py-12 text-center">
          <Users className="h-10 w-10 text-muted-foreground/40 mb-3" />
          <p className="text-sm font-medium text-muted-foreground">No deliberation sessions yet</p>
          <p className="text-xs text-muted-foreground mt-1">
            Sessions will appear here once created by administrators
          </p>
        </CardContent>
      </Card>
    )
  }

  return (
    <>
      {/* Desktop table */}
      <div className="hidden md:block rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Category</TableHead>
              <TableHead>Mode</TableHead>
              <TableHead>Status</TableHead>
              <TableHead className="text-right tabular-nums">Participants</TableHead>
              <TableHead className="text-right tabular-nums">Votes Cast</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {sessions.map((session) => (
              <TableRow key={session.id}>
                <TableCell className="font-medium">
                  {session.category ?? <span className="text-muted-foreground italic">General</span>}
                </TableCell>
                <TableCell>{sessionModeBadge(session.mode)}</TableCell>
                <TableCell>{sessionStatusBadge(session.status)}</TableCell>
                <TableCell className="text-right tabular-nums">{session._count.participants}</TableCell>
                <TableCell className="text-right tabular-nums">{session._count.votes}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      {/* Mobile card stack */}
      <div className="space-y-3 md:hidden">
        {sessions.map((session) => (
          <Card key={session.id}>
            <CardContent className="pt-4 space-y-3">
              <div className="flex items-start justify-between gap-2">
                <p className="font-medium text-sm">
                  {session.category ?? <span className="italic text-muted-foreground">General</span>}
                </p>
                {sessionStatusBadge(session.status)}
              </div>
              <div className="flex items-center gap-2">
                {sessionModeBadge(session.mode)}
              </div>
              <div className="grid grid-cols-2 gap-2 text-xs">
                <div>
                  <p className="text-muted-foreground">Participants</p>
                  <p className="font-medium tabular-nums">{session._count.participants}</p>
                </div>
                <div>
                  <p className="text-muted-foreground">Votes Cast</p>
                  <p className="font-medium tabular-nums">{session._count.votes}</p>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </>
  )
}

function ResultsTab({ roundId }: { roundId: string }) {
  const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null)

  const { data: sessions, isLoading: sessionsLoading } =
    trpc.analytics.getDeliberationSessions.useQuery({ roundId })

  const activeSessions = sessions?.filter((s) => s._count.votes > 0) ?? []
  const activeSessionId = selectedSessionId ?? activeSessions[0]?.id ?? null

  const { data: aggregate, isLoading: aggregateLoading } =
    trpc.analytics.getDeliberationAggregate.useQuery(
      { sessionId: activeSessionId! },
      { enabled: !!activeSessionId }
    )

  if (sessionsLoading) return <Skeleton className="h-[400px]" />

  if (!activeSessions.length) {
    return (
      <Card>
        <CardContent className="flex items-center justify-center py-12">
          <p className="text-sm text-muted-foreground">
            No votes have been cast yet. Results will appear once deliberation is underway.
          </p>
        </CardContent>
      </Card>
    )
  }

  const currentSessionId = selectedSessionId ?? activeSessions[0]?.id

  return (
    <div className="space-y-4">
      {/* Session selector if multiple */}
      {activeSessions.length > 1 && (
        <div className="flex items-center gap-3 flex-wrap">
          {activeSessions.map((s) => (
            <button
              key={s.id}
              onClick={() => setSelectedSessionId(s.id)}
              className={
                currentSessionId === s.id
                  ? 'rounded-full px-3 py-1 text-sm font-medium bg-primary text-primary-foreground'
                  : 'rounded-full px-3 py-1 text-sm font-medium bg-muted text-muted-foreground hover:bg-muted/80 transition-colors'
              }
            >
              {s.category ?? 'General'}
            </button>
          ))}
        </div>
      )}

      {aggregateLoading ? (
        <Skeleton className="h-[300px]" />
      ) : aggregate ? (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <Trophy className="h-4 w-4 text-amber-500" />
              Ranking Results
            </CardTitle>
            <CardDescription>
              {aggregate.rankings.length} project{aggregate.rankings.length !== 1 ? 's' : ''} ranked
              {aggregate.hasTies && (
                <span className="ml-1 text-amber-600 font-medium">· Ties detected</span>
              )}
            </CardDescription>
          </CardHeader>
          <CardContent>
            {/* Desktop table */}
            <div className="hidden md:block rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-12 text-center">Rank</TableHead>
                    <TableHead>Project</TableHead>
                    <TableHead>Team</TableHead>
                    <TableHead className="text-right tabular-nums">Score</TableHead>
                    <TableHead className="text-right tabular-nums">Votes</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {aggregate.rankings.map((r, idx) => {
                    const isTied = aggregate.tiedProjectIds.includes(r.projectId)
                    return (
                      <TableRow key={r.projectId} className={isTied ? 'bg-amber-50/50' : undefined}>
                        <TableCell className="text-center font-bold tabular-nums text-lg">
                          {idx + 1}
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <span className="font-medium">{r.projectTitle}</span>
                            {isTied && (
                              <Badge className="bg-amber-100 text-amber-800 border-amber-200 text-[10px]">
                                Tie
                              </Badge>
                            )}
                          </div>
                        </TableCell>
                        <TableCell className="text-muted-foreground text-sm">{r.teamName}</TableCell>
                        <TableCell className="text-right tabular-nums">
                          {typeof r.score === 'number' ? r.score : '—'}
                        </TableCell>
                        <TableCell className="text-right tabular-nums">{r.voteCount}</TableCell>
                      </TableRow>
                    )
                  })}
                </TableBody>
              </Table>
            </div>

            {/* Mobile list */}
            <div className="space-y-2 md:hidden">
              {aggregate.rankings.map((r, idx) => {
                const isTied = aggregate.tiedProjectIds.includes(r.projectId)
                return (
                  <div
                    key={r.projectId}
                    className={`flex items-center gap-3 rounded-md p-3 border${isTied ? ' bg-amber-50/50' : ''}`}
                  >
                    <span className="text-2xl font-bold tabular-nums w-8 text-center shrink-0">
                      {idx + 1}
                    </span>
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2 flex-wrap">
                        <p className="font-medium text-sm truncate">{r.projectTitle}</p>
                        {isTied && (
                          <Badge className="bg-amber-100 text-amber-800 border-amber-200 text-[10px]">
                            Tie
                          </Badge>
                        )}
                      </div>
                      <p className="text-xs text-muted-foreground">{r.teamName}</p>
                    </div>
                    <p className="text-xs text-muted-foreground tabular-nums shrink-0">
                      {r.voteCount} votes
                    </p>
                  </div>
                )
              })}
            </div>
          </CardContent>
        </Card>
      ) : null}
    </div>
  )
}

export function DeliberationReportTabs({ roundId }: DeliberationReportTabsProps) {
  return (
    <div className="space-y-6">
      <RoundTypeStatsCards roundId={roundId} />

      <Tabs defaultValue="sessions" className="space-y-6">
        <TabsList>
          <TabsTrigger value="sessions" className="gap-2">
            <Users className="h-4 w-4" />
            Sessions
          </TabsTrigger>
          <TabsTrigger value="results" className="gap-2">
            <Trophy className="h-4 w-4" />
            Results
          </TabsTrigger>
        </TabsList>

        <TabsContent value="sessions">
          <SessionsTab roundId={roundId} />
        </TabsContent>

        <TabsContent value="results">
          <ResultsTab roundId={roundId} />
        </TabsContent>
      </Tabs>
    </div>
  )
}
