
import React, { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/use-toast';
import { Loader2, AlertTriangle } from 'lucide-react';
import { format, parseISO, isValid } from 'date-fns';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';

export function PayableEditDialog({ open, onOpenChange, payable, onSave, clients }) {
  const { register, handleSubmit, reset, setValue, formState: { errors, isSubmitting } } = useForm();
  const { toast } = useToast();

  const isReadOnly = payable?.removal_eligible || payable?.deleted_at;

  useEffect(() => {
    if (payable) {
      setValue('bill_date', payable.bill_date);
      setValue('due_date', payable.due_date);
      setValue('payee', payable.payee);
      setValue('amount', payable.amount);
      setValue('expense_account', payable.expense_account || '');
      setValue('client_id', payable.client_id || 'none');
    } else {
      reset({ bill_date: new Date().toISOString().split('T')[0], due_date: new Date().toISOString().split('T')[0], client_id: 'none', expense_account: '' });
    }
  }, [payable, setValue, reset, open]);

  const onSubmit = async (data) => {
    if (isReadOnly) return;
    try {
      const payload = { ...data, client_id: data.client_id === 'none' ? null : data.client_id, amount: parseFloat(data.amount) };
      await onSave(payload);
      onOpenChange(false);
    } catch (error) {
      console.error(error);
    }
  };

  const formatDate = (dateString) => {
    if (!dateString) return '-';
    const date = parseISO(dateString);
    return isValid(date) ? format(date, 'MMM dd, yyyy h:mm a') : '-';
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{payable ? 'Edit Payable' : 'Add Payable'}</DialogTitle>
          {payable?.is_paid && (
             <DialogDescription className="text-emerald-600 font-medium text-xs">
                Marked Paid: {formatDate(payable.marked_paid_date)}
             </DialogDescription>
          )}
        </DialogHeader>
        
        {isReadOnly && (
           <Alert variant="destructive" className="py-2">
             <AlertTriangle className="h-4 w-4" />
             <AlertTitle>Read Only</AlertTitle>
             <AlertDescription>This payable has been archived/removed and cannot be edited.</AlertDescription>
           </Alert>
        )}

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-2">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="bill_date">Bill Date</Label>
              <Input id="bill_date" type="date" disabled={isReadOnly} {...register('bill_date')} />
            </div>
            <div className="space-y-2">
              <Label htmlFor="due_date">Due Date</Label>
              <Input id="due_date" type="date" disabled={isReadOnly} {...register('due_date', { required: true })} />
              {errors.due_date && <span className="text-xs text-destructive">Required</span>}
            </div>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="payee">Payee</Label>
            <Input id="payee" placeholder="e.g. Electric Company" disabled={isReadOnly} {...register('payee', { required: true })} />
            {errors.payee && <span className="text-xs text-destructive">Required</span>}
          </div>

          <div className="space-y-2">
            <Label htmlFor="expense_account">Expense Account</Label>
            <Input id="expense_account" placeholder="e.g. 5010 - Utilities" disabled={isReadOnly} {...register('expense_account')} />
          </div>

          <div className="space-y-2">
            <Label htmlFor="client">Association</Label>
            <Select disabled={isReadOnly} onValueChange={(val) => setValue('client_id', val)} defaultValue={payable?.client_id || 'none'}>
              <SelectTrigger><SelectValue placeholder="Select Association" /></SelectTrigger>
              <SelectContent className="max-h-[200px]">
                <SelectItem value="none">None / General</SelectItem>
                {clients?.map(client => (
                  <SelectItem key={client.id} value={client.id}>{client.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="amount">Amount ($)</Label>
            <Input id="amount" type="number" step="0.01" disabled={isReadOnly} placeholder="0.00" {...register('amount', { required: true, min: 0 })} />
            {errors.amount && <span className="text-xs text-destructive">Required</span>}
          </div>

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