import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Loader2 } from 'lucide-react';
import { useElections } from '@/hooks/useElections';
import { supabase } from '@/integrations/supabase/client';

export default function ElectionSetupDialog({ open, onOpenChange, onSuccess }) {
  const { createElection, loading } = useElections();
  const [associations, setAssociations] = useState([]);
  const [selectedAssociation, setSelectedAssociation] = useState('');

  const { register, handleSubmit, reset, formState: { errors } } = useForm({
    defaultValues: {
      title: '',
      description: '',
      election_type: 'board_election',
      voting_start: '',
      voting_end: '',
      quorum_required: 0,
    }
  });

  useEffect(() => {
    if (open) {
      supabase.from('associations').select('id, name').eq('status', 'active').order('name')
        .then(({ data }) => setAssociations(data || []));
    } else {
      reset();
      setSelectedAssociation('');
    }
  }, [open, reset]);

  const onSubmit = async (data) => {
    if (!selectedAssociation) return;
    const payload = {
      ...data,
      association_id: selectedAssociation,
      quorum_required: parseInt(data.quorum_required) || 0,
      voting_start: data.voting_start ? new Date(data.voting_start).toISOString() : null,
      voting_end: data.voting_end ? new Date(data.voting_end).toISOString() : null,
      status: 'draft'
    };
    const result = await createElection(payload);
    if (result) {
      onSuccess();
      onOpenChange(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={(v) => !loading && onOpenChange(v)}>
      <DialogContent className="sm:max-w-[520px]">
        <DialogHeader>
          <DialogTitle>Create New Election</DialogTitle>
          <DialogDescription>Set up an election compliant with Florida Statutes §718/§720.</DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-2">
          <div className="space-y-2">
            <Label>Association <span className="text-destructive">*</span></Label>
            <Select value={selectedAssociation} onValueChange={setSelectedAssociation} required>
              <SelectTrigger><SelectValue placeholder="Select Association" /></SelectTrigger>
              <SelectContent>
                {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label>Election Title <span className="text-destructive">*</span></Label>
            <Input {...register('title', { required: true })} placeholder="e.g. 2026 Board of Directors Election" />
            {errors.title && <span className="text-xs text-destructive">Required</span>}
          </div>

          <div className="space-y-2">
            <Label>Description</Label>
            <Textarea {...register('description')} placeholder="Details about this election..." rows={2} />
          </div>

          <div className="space-y-2">
            <Label>Election Type</Label>
            <Select defaultValue="board_election" onValueChange={(v) => reset(prev => ({ ...prev, election_type: v }))}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="board_election">Board of Directors</SelectItem>
                <SelectItem value="amendment">Amendment Vote</SelectItem>
                <SelectItem value="special">Special Election</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-2">
              <Label>Voting Opens</Label>
              <Input type="datetime-local" {...register('voting_start')} />
            </div>
            <div className="space-y-2">
              <Label>Voting Closes</Label>
              <Input type="datetime-local" {...register('voting_end')} />
            </div>
          </div>

          <div className="space-y-2">
            <Label>Quorum Required (# of voters)</Label>
            <Input type="number" {...register('quorum_required')} placeholder="0" min="0" />
          </div>

          <DialogFooter className="pt-3">
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button type="submit" disabled={loading || !selectedAssociation}>
              {loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />} Create Election
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
