
import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { Loader2, Save } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
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 { usePaymentPlans } from '@/hooks/usePaymentPlans';
import { useAuth } from '@/contexts/AuthContext';
import { supabase } from '@/integrations/supabase/client';

export function PaymentPlanDialog({ open, onOpenChange, onSuccess }) {
  const { register, handleSubmit, reset, setValue, formState: { errors } } = useForm();
  const { createPaymentPlan, loading } = usePaymentPlans();
  const { user } = useAuth();
  const [clients, setClients] = useState([]);
  const [loadingClients, setLoadingClients] = useState(false);

  useEffect(() => {
    if (open) {
      const fetchClients = async () => {
        setLoadingClients(true);
        const { data } = await supabase.from('associations').select('id, name').eq('status', 'active').order('name');
        setClients(data || []);
        setLoadingClients(false);
      };
      fetchClients();
    }
  }, [open]);

  const onSubmit = async (data) => {
    const associationId = data.association_id;
    if (!associationId) return;

    const result = await createPaymentPlan({
      title: data.title, description: data.description,
      association_id: associationId, created_by: user?.id, status: 'active'
    });

    if (result) { reset(); onOpenChange(false); if (onSuccess) onSuccess(); }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader><DialogTitle>Create New Payment Plan</DialogTitle></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) => setValue('association_id', val)}>
              <SelectTrigger><SelectValue placeholder={loadingClients ? "Loading..." : "Select Association"} /></SelectTrigger>
              <SelectContent>{clients.map(client => <SelectItem key={client.id} value={client.id}>{client.name}</SelectItem>)}</SelectContent>
            </Select>
            <input type="hidden" {...register('association_id', { required: 'Association is required' })} />
            {errors.association_id && <p className="text-xs text-destructive">{errors.association_id.message}</p>}
          </div>
          <div className="space-y-2">
            <Label htmlFor="title">Plan Title <span className="text-destructive">*</span></Label>
            <Input id="title" placeholder="e.g. 2024 Assessment Plan" {...register('title', { required: 'Title is required' })} />
            {errors.title && <p className="text-xs text-destructive">{errors.title.message}</p>}
          </div>
          <div className="space-y-2">
            <Label htmlFor="description">Description</Label>
            <Textarea id="description" placeholder="Details about this payment plan..." {...register('description')} />
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button type="submit" disabled={loading}>
              {loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Save className="mr-2 h-4 w-4" />}
              Create Plan
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
