import React, { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Loader2 } from 'lucide-react';
import { useVotes } from '@/hooks/useVotes';

export default function BoardVoteResponseDialog({ open, onOpenChange, vote, targetUser, onSuccess }) {
  const { recordVote, loading } = useVotes();
  const [selectedOption, setSelectedOption] = useState('');

  const handleSubmit = async () => {
    if (!selectedOption) return;
    
    const success = await recordVote(vote.id, targetUser.id, selectedOption);
    if (success) {
        onSuccess();
        onOpenChange(false);
        setSelectedOption('');
    }
  };

  if (!vote || !targetUser) return null;

  return (
    <Dialog open={open} onOpenChange={(val) => !loading && onOpenChange(val)}>
      <DialogContent className="sm:max-w-[400px]">
        <DialogHeader>
          <DialogTitle>Record Vote</DialogTitle>
          <DialogDescription>
             Recording vote on behalf of <span className="font-semibold">{targetUser.full_name || targetUser.email}</span>
          </DialogDescription>
        </DialogHeader>

        <div className="py-4 space-y-4">
            <div>
                <h4 className="font-medium text-sm mb-1">{vote.title}</h4>
                <p className="text-xs text-muted-foreground">{vote.description}</p>
            </div>
            
            <RadioGroup value={selectedOption} onValueChange={setSelectedOption} className="gap-3">
                {(vote.vote_options || []).map((option) => (
                    <div key={option} className="flex items-center space-x-2 border rounded p-3 hover:bg-muted/50 cursor-pointer">
                        <RadioGroupItem value={option} id={`opt-${option}`} />
                        <Label htmlFor={`opt-${option}`} className="flex-1 cursor-pointer">{option}</Label>
                    </div>
                ))}
            </RadioGroup>
        </div>

        <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button onClick={handleSubmit} disabled={loading || !selectedOption}>
                {loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />} Submit Vote
            </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
