import React, { useState, useEffect } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/contexts/AuthContext';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } 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 { Checkbox } from '@/components/ui/checkbox';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Loader2, CheckCircle2, DollarSign, AlertCircle, Users } from 'lucide-react';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';

const formSchema = z.object({
  association_id: z.string().min(1, "Association is required."),
  invoice_number: z.string().min(1, "Invoice number is required."),
  vendor_name: z.string().min(2, "Vendor name must be at least 2 characters."),
  invoice_date: z.string().min(1, "Invoice date is required."),
  due_date: z.string().min(1, "Due date is required."),
  amount: z.coerce.number().positive("Amount must be greater than 0."),
  description: z.string().optional(),
}).refine(data => {
  if (!data.invoice_date || !data.due_date) return true;
  return new Date(data.due_date) >= new Date(data.invoice_date);
}, {
  message: "Due date must be greater than or equal to invoice date.",
  path: ["due_date"]
});

export default function BillApprovalDialog({ open, onOpenChange, invoice, onSuccess }) {
  const { toast } = useToast();
  const { user } = useAuth();
  
  const [associations, setAssociations] = useState([]);
  const [boardMembers, setBoardMembers] = useState([]);
  const [selectedBoardMembers, setSelectedBoardMembers] = useState([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submittedData, setSubmittedData] = useState(null);

  const { register, handleSubmit, control, watch, reset, setValue, formState: { errors, isValid } } = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      association_id: '',
      invoice_number: '',
      vendor_name: '',
      invoice_date: '',
      due_date: '',
      amount: '',
      description: '',
    },
    mode: 'onChange'
  });

  const selectedAssociationId = watch('association_id');

  useEffect(() => {
    if (open && invoice) {
      reset({
        association_id: invoice.association_id || '',
        invoice_number: invoice.invoice_number || `INV-${Math.floor(Math.random()*10000)}`,
        vendor_name: invoice.vendor_name || '',
        invoice_date: invoice.issue_date || new Date().toISOString().split('T')[0],
        due_date: invoice.due_date || new Date().toISOString().split('T')[0],
        amount: invoice.amount || '',
        description: invoice.description || '',
      });
      setSubmittedData(null);
      setSelectedBoardMembers([]);
    }
  }, [open, invoice, reset]);

  useEffect(() => {
    async function fetchAssociations() {
      if (!open) return;
      try {
        const { data, error } = await supabase.from('associations').select('id, name').eq('status', 'active').order('name');
        if (error) throw error;
        setAssociations(data || []);
      } catch (err) {
        console.error("Failed to load associations", err);
      }
    }
    fetchAssociations();
  }, [open]);

  useEffect(() => {
    async function fetchBoardMembers() {
      if (!selectedAssociationId) {
        setBoardMembers([]);
        return;
      }
      try {
        const { data, error } = await supabase
          .from('board_members')
          .select('id, member_name, member_email')
          .eq('association_id', selectedAssociationId)
          .eq('approval_authority', true);
        if (error) throw error;
        setBoardMembers(data || []);
        setSelectedBoardMembers([]);
      } catch (err) {
        console.error("Failed to load board members", err);
      }
    }
    if (open) fetchBoardMembers();
  }, [selectedAssociationId, open]);

  const onSubmit = async (data) => {
    setIsSubmitting(true);
    try {
      const { data: newBill, error: billError } = await supabase
        .from('bills')
        .insert([{
          association_id: data.association_id,
          bill_date: data.invoice_date,
          due_date: data.due_date,
          amount: data.amount,
          description: data.description || `Invoice ${data.invoice_number}`,
          invoice_number: data.invoice_number,
          status: 'pending',
          created_by: user?.id,
        }])
        .select()
        .single();

      if (billError) throw billError;

      toast({ title: "Bill Created Successfully", description: "The bill has been saved." });
      setSubmittedData(data);
      if (onSuccess) onSuccess(newBill);

    } catch (err) {
      toast({ title: "Failed to create bill", description: err.message, variant: "destructive" });
    } finally {
      setIsSubmitting(false);
    }
  };

  const toggleBoardMember = (id) => {
    setSelectedBoardMembers(prev => 
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    );
  };

  const renderSuccessView = () => (
    <div className="py-6 flex flex-col items-center justify-center space-y-6">
      <div className="w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center">
        <CheckCircle2 className="w-10 h-10 text-emerald-600" />
      </div>
      <div className="text-center">
        <h3 className="text-xl font-semibold">Bill Created Successfully</h3>
        <p className="text-sm text-muted-foreground mt-1">Bill is now pending approval.</p>
      </div>
      <Button onClick={() => onOpenChange(false)} className="w-full">Close</Button>
    </div>
  );

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[650px] max-h-[90vh] overflow-y-auto">
        {!submittedData && (
          <DialogHeader>
            <DialogTitle className="text-xl">Create Bill & Request Approval</DialogTitle>
            <DialogDescription>Review invoice data and select board members for approval.</DialogDescription>
          </DialogHeader>
        )}

        {submittedData ? renderSuccessView() : (
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-5 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label className="font-semibold">Association <span className="text-destructive">*</span></Label>
                <Controller control={control} name="association_id" render={({ field }) => (
                  <Select onValueChange={field.onChange} value={field.value}>
                    <SelectTrigger className={errors.association_id ? 'border-destructive' : ''}><SelectValue placeholder="Select Association" /></SelectTrigger>
                    <SelectContent>{associations.map(c => <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>)}</SelectContent>
                  </Select>
                )}/>
              </div>
              <div className="space-y-2">
                <Label className="font-semibold">Invoice Number <span className="text-destructive">*</span></Label>
                <Input {...register('invoice_number')} className={errors.invoice_number ? 'border-destructive' : ''} />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label className="font-semibold">Vendor Name <span className="text-destructive">*</span></Label>
                <Input {...register('vendor_name')} className={errors.vendor_name ? 'border-destructive' : ''} />
              </div>
              <div className="space-y-2">
                <Label className="font-semibold">Amount <span className="text-destructive">*</span></Label>
                <div className="relative">
                  <DollarSign className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                  <Input type="number" step="0.01" className={`pl-9 ${errors.amount ? 'border-destructive' : ''}`} placeholder="0.00" {...register('amount')} />
                </div>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label className="font-semibold">Invoice Date <span className="text-destructive">*</span></Label>
                <Input type="date" {...register('invoice_date')} className={errors.invoice_date ? 'border-destructive' : ''} />
              </div>
              <div className="space-y-2">
                <Label className="font-semibold">Due Date <span className="text-destructive">*</span></Label>
                <Input type="date" {...register('due_date')} className={errors.due_date ? 'border-destructive' : ''} />
              </div>
            </div>

            <div className="space-y-2">
               <Label className="font-semibold flex items-center"><Users className="w-4 h-4 mr-2 text-primary"/> Required Approvers</Label>
               <div className="border rounded-md p-3 max-h-[150px] overflow-y-auto bg-muted/30 space-y-2">
                  {!selectedAssociationId ? (
                     <p className="text-sm text-muted-foreground italic">Select an association to view approvers.</p>
                  ) : boardMembers.length === 0 ? (
                     <p className="text-sm text-muted-foreground italic">No board members with approval authority found.</p>
                  ) : (
                     boardMembers.map(bm => (
                       <div key={bm.id} className="flex items-center space-x-2 bg-background p-2 rounded border">
                         <Checkbox 
                           id={`bm-${bm.id}`} 
                           checked={selectedBoardMembers.includes(bm.id)} 
                           onCheckedChange={() => toggleBoardMember(bm.id)} 
                         />
                         <Label htmlFor={`bm-${bm.id}`} className="cursor-pointer flex-1">
                           <span className="font-medium">{bm.member_name}</span>
                           <span className="text-xs text-muted-foreground block">{bm.member_email}</span>
                         </Label>
                       </div>
                     ))
                  )}
               </div>
            </div>

            <div className="space-y-2">
              <Label className="font-semibold">Notes</Label>
              <Textarea placeholder="Optional notes..." {...register('description')} className="min-h-[60px]" />
            </div>

            <div className="pt-4 border-t flex justify-end gap-3">
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>Cancel</Button>
              <Button type="submit" disabled={isSubmitting || !isValid}>
                {isSubmitting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : 'Create & Request'}
              </Button>
            </div>
          </form>
        )}
      </DialogContent>
    </Dialog>
  );
}
