import React, { useState, useEffect } from 'react';
import { useForm, useFieldArray } 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, Plus, Trash2 } from 'lucide-react';
import { useVotes } from '@/hooks/useVotes';
import { supabase } from '@/integrations/supabase/client';

export default function BoardVoteDialog({ open, onOpenChange, onSuccess }) {
  const { createBoardVote, loading } = useVotes();
  const [associations, setAssociations] = useState([]);
  
  const { register, control, handleSubmit, reset, formState: { errors } } = useForm({
    defaultValues: {
      title: '',
      description: '',
      association_id: '',
      vote_options: [{ value: 'Yes' }, { value: 'No' }]
    }
  });

  const { fields, append, remove } = useFieldArray({
    control,
    name: "vote_options"
  });

  useEffect(() => {
    if (open) {
        fetchAssociations();
    } else {
        reset({
            title: '',
            description: '',
            association_id: '',
            vote_options: [{ value: 'Yes' }, { value: 'No' }]
        });
    }
  }, [open, reset]);

  const fetchAssociations = async () => {
      const { data } = await supabase.from('associations').select('id, name').eq('status', 'active').order('name');
      setAssociations(data || []);
  };

  const onSubmit = async (data) => {
    const formattedOptions = data.vote_options.map(o => o.value).filter(Boolean);
    
    if (formattedOptions.length < 2) return; 

    const payload = {
        title: data.title,
        description: data.description,
        association_id: data.association_id,
        vote_options: formattedOptions,
        status: 'active'
    };

    const success = await createBoardVote(payload);
    if (success) {
        onSuccess();
        onOpenChange(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={(val) => !loading && onOpenChange(val)}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Create New Board Vote</DialogTitle>
          <DialogDescription>Setup a new voting item for board members.</DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-4">
            <div className="space-y-2">
                <Label>Association <span className="text-destructive">*</span></Label>
                <Select onValueChange={(val) => reset(prev => ({ ...prev, association_id: val }))} required>
                    <SelectTrigger>
                        <SelectValue placeholder="Select Association" />
                    </SelectTrigger>
                    <SelectContent>
                        {associations.map(assoc => (
                            <SelectItem key={assoc.id} value={assoc.id}>{assoc.name}</SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            </div>

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

            <div className="space-y-2">
                <Label>Description</Label>
                <Textarea {...register('description')} placeholder="Additional details..." rows={3} />
            </div>

            <div className="space-y-2">
                <div className="flex items-center justify-between">
                    <Label>Vote Options</Label>
                    <Button type="button" variant="ghost" size="sm" onClick={() => append({ value: '' })} className="h-6 text-xs">
                        <Plus className="w-3 h-3 mr-1" /> Add Option
                    </Button>
                </div>
                <div className="space-y-2 max-h-[150px] overflow-y-auto pr-1">
                    {fields.map((field, index) => (
                        <div key={field.id} className="flex gap-2">
                            <Input 
                                {...register(`vote_options.${index}.value`, { required: true })} 
                                placeholder={`Option ${index + 1}`}
                            />
                            {fields.length > 2 && (
                                <Button type="button" variant="ghost" size="icon" onClick={() => remove(index)}>
                                    <Trash2 className="w-4 h-4 text-muted-foreground hover:text-destructive" />
                                </Button>
                            )}
                        </div>
                    ))}
                </div>
            </div>

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