'use client';

import { use } from 'react';
import { useRouter } from 'next/navigation';
import { trpc } from '@/lib/trpc/client';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { ArrowLeft } from 'lucide-react';
import { toast } from 'sonner';
import { ResultsPanel } from '@/components/admin/deliberation/results-panel';
import type { Route } from 'next';

export default function DeliberationSessionPage({
  params: paramsPromise
}: {
  params: Promise<{ competitionId: string; sessionId: string }>;
}) {
  const params = use(paramsPromise);
  const router = useRouter();
  const utils = trpc.useUtils();

  const { data: session, isLoading } = trpc.deliberation.getSession.useQuery({
    sessionId: params.sessionId
  });

  const openVotingMutation = trpc.deliberation.openVoting.useMutation({
    onSuccess: () => {
      utils.deliberation.getSession.invalidate();
      toast.success('Voting opened');
    },
    onError: (err) => {
      toast.error(err.message);
    }
  });

  const closeVotingMutation = trpc.deliberation.closeVoting.useMutation({
    onSuccess: () => {
      utils.deliberation.getSession.invalidate();
      toast.success('Voting closed');
    },
    onError: (err) => {
      toast.error(err.message);
    }
  });

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" onClick={() => router.back()}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold">Loading...</h1>
          </div>
        </div>
      </div>
    );
  }

  if (!session) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" onClick={() => router.back()}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold">Session Not Found</h1>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button
          variant="ghost"
          size="icon"
          onClick={() =>
            router.push(`/admin/competitions/${params.competitionId}/deliberation` as Route)
          }
        >
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div className="flex-1">
          <div className="flex items-center gap-3">
            <h1 className="text-3xl font-bold">Deliberation Session</h1>
            <Badge>{session.status}</Badge>
          </div>
          <p className="text-muted-foreground">
            {session.round?.name} - {session.category}
          </p>
        </div>
      </div>

      <Tabs defaultValue="setup" className="w-full">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="setup">Setup</TabsTrigger>
          <TabsTrigger value="voting">Voting Control</TabsTrigger>
          <TabsTrigger value="results">Results</TabsTrigger>
        </TabsList>

        <TabsContent value="setup" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Session Configuration</CardTitle>
              <CardDescription>Deliberation settings and participants</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Mode</p>
                  <p className="mt-1">
                    {session.mode === 'SINGLE_WINNER_VOTE' ? 'Single Winner Vote' : 'Full Ranking'}
                  </p>
                </div>
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Tie Break Method</p>
                  <p className="mt-1">{session.tieBreakMethod}</p>
                </div>
                <div>
                  <p className="text-sm font-medium text-muted-foreground">
                    Show Collective Rankings
                  </p>
                  <p className="mt-1">{session.showCollectiveRankings ? 'Yes' : 'No'}</p>
                </div>
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Show Prior Jury Data</p>
                  <p className="mt-1">{session.showPriorJuryData ? 'Yes' : 'No'}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Participants ({session.participants?.length || 0})</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {session.participants?.map((participant: any) => (
                  <div
                    key={participant.id}
                    className="flex items-center justify-between rounded-lg border p-3"
                  >
                    <div>
                      <p className="font-medium">{participant.user?.name}</p>
                      <p className="text-sm text-muted-foreground">{participant.user?.email}</p>
                    </div>
                    <Badge variant={participant.hasVoted ? 'default' : 'outline'}>
                      {participant.hasVoted ? 'Voted' : 'Pending'}
                    </Badge>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="voting" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Voting Controls</CardTitle>
              <CardDescription>Manage the voting window for jury members</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex flex-col gap-3 sm:flex-row">
                <Button
                  onClick={() => openVotingMutation.mutate({ sessionId: params.sessionId })}
                  disabled={
                    openVotingMutation.isPending || session.status !== 'DELIB_OPEN'
                  }
                  className="flex-1"
                >
                  Open Voting
                </Button>
                <Button
                  variant="destructive"
                  onClick={() => closeVotingMutation.mutate({ sessionId: params.sessionId })}
                  disabled={
                    closeVotingMutation.isPending || session.status !== 'DELIB_VOTING'
                  }
                  className="flex-1"
                >
                  Close Voting
                </Button>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Voting Status</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {session.participants?.map((participant: any) => (
                  <div
                    key={participant.id}
                    className="flex items-center justify-between rounded-lg border p-3"
                  >
                    <span>{participant.user?.name}</span>
                    <Badge variant={participant.hasVoted ? 'default' : 'secondary'}>
                      {participant.hasVoted ? 'Submitted' : 'Not Voted'}
                    </Badge>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="results" className="space-y-4">
          <ResultsPanel sessionId={params.sessionId} />
        </TabsContent>
      </Tabs>
    </div>
  );
}
