import React, { useState, useEffect } from 'react';
import { useForm, Controller } 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 { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Loader2, AlertCircle } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';

export default function BillApprovalEditDialog({ bill, isOpen, onClose, onSave }) {
  const { toast } = useToast();
  const [isSaving, setIsSaving] = useState(false);
  const isPaid = bill?.status?.toLowerCase() === 'paid';

  const { register, control, handleSubmit, reset, watch, formState: { errors } } = useForm({
    defaultValues: {
      amount: '',
      due_date: '',
      description: '',
      invoice_number: '',
      status: '',
    }
  });

  useEffect(() => {
    if (bill && isOpen) {
      reset({
        amount: bill.amount || '',
        due_date: bill.due_date ? new Date(bill.due_date).toISOString().split('T')[0] : '',
        description: bill.description || '',
        invoice_number: bill.invoice_number || '',
        status: bill.status || 'pending',
      });
    }
  }, [bill, isOpen, reset]);

  const onSubmit = async (data) => {
    if (isPaid) {
      toast({
        title: "Action Denied",
        description: "Paid bills cannot be edited.",
        variant: "destructive"
      });
      return;
    }

    setIsSaving(true);
    try {
      const { error } = await supabase
        .from('bills')
        .update({
          amount: parseFloat(data.amount),
          due_date: data.due_date,
          description: data.description,
          invoice_number: data.invoice_number,
          status: data.status,
          updated_at: new Date().toISOString()
        })
        .eq('id', bill.id);

      if (error) throw error;

      toast({
        title: "Bill Updated",
        description: "The bill has been successfully updated.",
      });
      
      if (onSave) onSave();
      onClose();
    } catch (err) {
      console.error('Error updating bill:', err);
      toast({
        title: "Update Failed",
        description: err.message || "Failed to update the bill.",
        variant: "destructive"
      });
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Edit Bill Details</DialogTitle>
          <DialogDescription>
            Modify the details of this bill. Paid bills cannot be altered.
          </DialogDescription>
        </DialogHeader>

        {isPaid && (
          <Alert className="bg-amber-50 border-amber-200 text-amber-800">
            <AlertCircle className="h-4 w-4" />
            <AlertTitle>Read Only</AlertTitle>
            <AlertDescription>
              This bill has been marked as paid and can no longer be edited.
            </AlertDescription>
          </Alert>
        )}

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Amount</Label>
              <Input 
                type="number" 
                step="0.01" 
                disabled={isPaid || isSaving}
                {...register('amount', { required: true, min: 0.01 })} 
              />
              {errors.amount && <span className="text-xs text-destructive">Valid amount required</span>}
            </div>
            <div className="space-y-2">
              <Label>Due Date</Label>
              <Input 
                type="date" 
                disabled={isPaid || isSaving}
                {...register('due_date', { required: true })} 
              />
              {errors.due_date && <span className="text-xs text-destructive">Date required</span>}
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Invoice Number</Label>
              <Input 
                disabled={isPaid || isSaving}
                {...register('invoice_number')} 
              />
            </div>
            <div className="space-y-2">
              <Label>Status</Label>
              <select 
                disabled={isPaid || isSaving}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                {...register('status', { required: true })}
              >
                <option value="pending">Pending</option>
                <option value="approved">Approved</option>
                <option value="denied">Denied</option>
                <option value="paid">Paid</option>
              </select>
            </div>
          </div>

          <div className="space-y-2">
            <Label>Description</Label>
            <Textarea 
              disabled={isPaid || isSaving}
              {...register('description')} 
            />
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose} disabled={isSaving}>
              Cancel
            </Button>
            <Button type="submit" disabled={isPaid || isSaving}>
              {isSaving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
              Save Changes
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
