'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';

interface Project {
  id: string;
  title: string;
  category?: string;
  teamName?: string | null;
}

interface DeliberationRankingFormProps {
  projects: Project[];
  mode: 'SINGLE_WINNER_VOTE' | 'FULL_RANKING';
  onSubmit: (votes: Array<{ projectId: string; rank?: number; isWinnerPick?: boolean }>) => void;
  disabled?: boolean;
}

export function DeliberationRankingForm({
  projects,
  mode,
  onSubmit,
  disabled = false
}: DeliberationRankingFormProps) {
  const [selectedWinner, setSelectedWinner] = useState<string>('');
  const [rankings, setRankings] = useState<Record<string, number>>({});
  const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);

  const handleSubmit = () => {
    if (mode === 'SINGLE_WINNER_VOTE') {
      if (!selectedWinner) {
        return;
      }
    } else {
      // FULL_RANKING mode - check if all ranks are assigned
      const assignedRanks = Object.values(rankings);
      if (assignedRanks.length !== projects.length) {
        return;
      }
    }
    setConfirmDialogOpen(true);
  };

  const handleConfirm = () => {
    if (mode === 'SINGLE_WINNER_VOTE') {
      onSubmit([
        {
          projectId: selectedWinner,
          isWinnerPick: true
        }
      ]);
    } else {
      // FULL_RANKING mode
      const votes = Object.entries(rankings).map(([projectId, rank]) => ({
        projectId,
        rank
      }));
      onSubmit(votes);
    }
    setConfirmDialogOpen(false);
  };

  const isValid = mode === 'SINGLE_WINNER_VOTE'
    ? !!selectedWinner
    : Object.keys(rankings).length === projects.length;

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle>
            {mode === 'SINGLE_WINNER_VOTE' ? 'Select Winner' : 'Rank All Projects'}
          </CardTitle>
          <CardDescription>
            {mode === 'SINGLE_WINNER_VOTE'
              ? 'Choose your top pick for this category'
              : 'Assign a rank (1 = best) to each project'}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {mode === 'SINGLE_WINNER_VOTE' ? (
            <RadioGroup value={selectedWinner} onValueChange={setSelectedWinner}>
              <div className="space-y-3">
                {projects.map((project) => (
                  <div
                    key={project.id}
                    className="flex items-center space-x-3 rounded-lg border p-4"
                  >
                    <RadioGroupItem value={project.id} id={project.id} />
                    <Label htmlFor={project.id} className="flex-1 cursor-pointer">
                      <div>
                        <p className="font-medium">{project.title}</p>
                        <Badge variant="outline" className="mt-1">
                          {project.category}
                        </Badge>
                      </div>
                    </Label>
                  </div>
                ))}
              </div>
            </RadioGroup>
          ) : (
            <div className="space-y-3">
              {projects.map((project) => (
                <div
                  key={project.id}
                  className="flex items-center gap-3 rounded-lg border p-4"
                >
                  <Input
                    type="number"
                    min="1"
                    max={projects.length}
                    placeholder="Rank"
                    value={rankings[project.id] || ''}
                    onChange={(e) => {
                      const rank = parseInt(e.target.value) || 0;
                      if (rank > 0 && rank <= projects.length) {
                        setRankings({
                          ...rankings,
                          [project.id]: rank
                        });
                      } else if (e.target.value === '') {
                        const newRankings = { ...rankings };
                        delete newRankings[project.id];
                        setRankings(newRankings);
                      }
                    }}
                    className="w-20"
                  />
                  <div className="flex-1">
                    <p className="font-medium">{project.title}</p>
                    <Badge variant="outline" className="mt-1">
                      {project.category}
                    </Badge>
                  </div>
                </div>
              ))}
            </div>
          )}

          <Button onClick={handleSubmit} disabled={!isValid || disabled} className="w-full" size="lg">
            {disabled ? 'Submitting...' : 'Submit Vote'}
          </Button>
        </CardContent>
      </Card>

      {/* Confirmation Dialog */}
      <AlertDialog open={confirmDialogOpen} onOpenChange={setConfirmDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Confirm Your Vote</AlertDialogTitle>
            <AlertDialogDescription>
              {mode === 'SINGLE_WINNER_VOTE'
                ? 'You have selected your winner. This vote cannot be changed once submitted.'
                : 'You have ranked all projects. This ranking cannot be changed once submitted.'}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Review</AlertDialogCancel>
            <AlertDialogAction onClick={handleConfirm}>Confirm Vote</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
