'use client';

import { useState } from 'react';
import { trpc } from '@/lib/trpc/client';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { AlertTriangle, CheckCircle2 } from 'lucide-react';
import { toast } from 'sonner';
import { AdminOverrideDialog } from './admin-override-dialog';

interface ResultsPanelProps {
  sessionId: string;
}

export function ResultsPanel({ sessionId }: ResultsPanelProps) {
  const utils = trpc.useUtils();
  const [overrideDialogOpen, setOverrideDialogOpen] = useState(false);

  const { data: session } = trpc.deliberation.getSession.useQuery(
    { sessionId },
    { refetchInterval: 10_000 }
  );
  const { data: aggregatedResults } = trpc.deliberation.aggregate.useQuery(
    { sessionId },
    {
      refetchInterval: 10_000,
      enabled: session?.status === 'TALLYING' || session?.status === 'RUNOFF' || session?.status === 'DELIB_LOCKED',
    }
  );

  const initRunoffMutation = trpc.deliberation.initRunoff.useMutation({
    onSuccess: () => {
      utils.deliberation.getSession.invalidate();
      utils.deliberation.aggregate.invalidate();
      toast.success('Runoff voting initiated');
    },
    onError: (err) => {
      toast.error(err.message);
    }
  });

  const finalizeMutation = trpc.deliberation.finalize.useMutation({
    onSuccess: () => {
      utils.deliberation.getSession.invalidate();
      toast.success('Results finalized successfully');
    },
    onError: (err) => {
      toast.error(err.message);
    }
  });

  if (!aggregatedResults) {
    return (
      <Card>
        <CardContent className="p-12 text-center">
          <p className="text-muted-foreground">
            {session?.status === 'DELIB_OPEN' || session?.status === 'VOTING'
              ? 'Voting has not been tallied yet'
              : 'No voting results yet'}
          </p>
        </CardContent>
      </Card>
    );
  }

  // Detect ties using the backend-computed flag, with client-side fallback
  const hasTie = aggregatedResults.hasTies ?? (() => {
    const rankings = aggregatedResults.rankings as Array<{ score?: number; projectId: string }> | undefined;
    if (!rankings || rankings.length < 2) return false;
    const scoreGroups = new Map<number, string[]>();
    for (const r of rankings) {
      const score = r.score ?? 0;
      const group = scoreGroups.get(score) || [];
      group.push(r.projectId);
      scoreGroups.set(score, group);
    }
    const topScore = Math.max(...scoreGroups.keys());
    const topGroup = scoreGroups.get(topScore);
    return (topGroup?.length ?? 0) >= 2;
  })();
  const tiedProjectIds = aggregatedResults.tiedProjectIds ?? [];
  const canFinalize = session?.status === 'TALLYING' && !hasTie;

  return (
    <div className="space-y-4">
      {/* Results Table */}
      <Card>
        <CardHeader>
          <CardTitle>Voting Results</CardTitle>
          <CardDescription>
            Aggregated voting results
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {aggregatedResults.rankings?.map((result: any, index: number) => (
              <div
                key={result.projectId}
                className="flex items-center justify-between rounded-lg border p-4"
              >
                <div className="flex items-center gap-4">
                  <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 font-bold">
                    #{result.rank ?? index + 1}
                  </div>
                  <div>
                    <p className="font-medium">{result.projectTitle ?? result.projectId}</p>
                    <p className="text-sm text-muted-foreground">
                      {result.voteCount} votes
                    </p>
                  </div>
                </div>
                <Badge variant="outline" className="text-lg">
                  {result.score?.toFixed?.(1) ?? 0}
                </Badge>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Tie Warning */}
      {hasTie && (
        <Alert variant="destructive">
          <AlertTriangle className="h-4 w-4" />
          <AlertTitle>Tie Detected</AlertTitle>
          <AlertDescription className="space-y-3">
            <p>
              Multiple projects have the same score. You must resolve this before finalizing
              results.
            </p>
            <div className="flex flex-col gap-2 sm:flex-row">
              <Button
                variant="outline"
                size="sm"
                onClick={() => initRunoffMutation.mutate({ sessionId, tiedProjectIds })}
                disabled={initRunoffMutation.isPending}
              >
                Initiate Runoff Vote
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setOverrideDialogOpen(true)}
              >
                Admin Override
              </Button>
            </div>
          </AlertDescription>
        </Alert>
      )}

      {/* Finalize Button */}
      {canFinalize && (
        <Card>
          <CardContent className="flex items-center justify-between p-6">
            <div className="flex items-center gap-3">
              <CheckCircle2 className="h-5 w-5 text-green-600" />
              <div>
                <p className="font-medium">Ready to Finalize</p>
                <p className="text-sm text-muted-foreground">
                  All votes counted, no ties detected
                </p>
              </div>
            </div>
            <Button
              onClick={() => finalizeMutation.mutate({ sessionId })}
              disabled={finalizeMutation.isPending}
            >
              {finalizeMutation.isPending ? 'Finalizing...' : 'Finalize Results'}
            </Button>
          </CardContent>
        </Card>
      )}

      {/* Admin Override Dialog */}
      <AdminOverrideDialog
        sessionId={sessionId}
        open={overrideDialogOpen}
        onOpenChange={setOverrideDialogOpen}
        projectIds={aggregatedResults.rankings?.map((r: any) => r.projectId) || []}
      />
    </div>
  );
}
