import React, { useState, useEffect } from 'react';
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { Textarea } from '@/components/ui/textarea';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { Loader2, DollarSign } from 'lucide-react';
import { format } from 'date-fns';

export default function BankDepositDialog({ isOpen, onClose, onSuccess, bankAccount }) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  
  const [formData, setFormData] = useState({
    deposit_date: format(new Date(), 'yyyy-MM-dd'),
    amount: '',
    deposit_type: '',
    description: '',
    reference: '',
    notes: ''
  });

  const [errors, setErrors] = useState({});

  useEffect(() => {
    if (isOpen) {
      setFormData({
        deposit_date: format(new Date(), 'yyyy-MM-dd'),
        amount: '',
        deposit_type: '',
        description: '',
        reference: '',
        notes: ''
      });
      setErrors({});
    }
  }, [isOpen, bankAccount]);

  const validate = () => {
    const newErrors = {};
    if (!formData.deposit_date) newErrors.deposit_date = "Date is required";
    if (!formData.deposit_type) newErrors.deposit_type = "Deposit type is required";
    
    const amt = parseFloat(formData.amount);
    if (!formData.amount || isNaN(amt) || amt <= 0) {
      newErrors.amount = "Enter a valid positive amount";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validate()) return;
    if (!bankAccount?.id) {
      toast({ title: 'Error', description: 'No bank account selected.', variant: 'destructive' });
      return;
    }

    setLoading(true);
    try {
      const { error: txError } = await supabase
        .from('bank_transactions')
        .insert([{
          bank_account_id: bankAccount.id,
          association_id: bankAccount.association_id,
          date: formData.deposit_date,
          description: formData.description || `Deposit: ${formData.deposit_type}`,
          credit: parseFloat(formData.amount),
          reference_number: formData.reference,
          transaction_type: 'deposit'
        }]);

      if (txError) throw txError;

      toast({ title: 'Deposit Recorded', description: 'The deposit has been successfully recorded.' });
      if (onSuccess) onSuccess();
      onClose();
    } catch (err) {
      console.error('Error recording deposit:', err);
      toast({ title: 'Deposit Failed', description: err.message || 'An error occurred while saving.', variant: 'destructive' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={(val) => !loading && onClose(val)}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <DollarSign className="w-5 h-5 text-green-600" />
            Record Bank Deposit
          </DialogTitle>
          <DialogDescription>
            Record a new deposit for {bankAccount?.account_name} ({bankAccount?.bank_name}).
          </DialogDescription>
        </DialogHeader>

        <form id="deposit-form" onSubmit={handleSubmit} className="space-y-6 mt-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label className={errors.deposit_date ? "text-destructive" : ""}>Deposit Date *</Label>
              <Input 
                type="date" 
                value={formData.deposit_date} 
                onChange={e => setFormData({...formData, deposit_date: e.target.value})} 
                className={errors.deposit_date ? "border-destructive" : ""}
              />
              {errors.deposit_date && <p className="text-xs text-destructive">{errors.deposit_date}</p>}
            </div>

            <div className="space-y-2">
              <Label className={errors.deposit_type ? "text-destructive" : ""}>Deposit Type *</Label>
              <Select value={formData.deposit_type} onValueChange={v => setFormData({...formData, deposit_type: v})}>
                <SelectTrigger className={errors.deposit_type ? "border-destructive" : ""}>
                  <SelectValue placeholder="Select type..." />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Manual Payment">Manual Payment</SelectItem>
                  <SelectItem value="Transfer In">Transfer In</SelectItem>
                  <SelectItem value="Other">Other</SelectItem>
                </SelectContent>
              </Select>
              {errors.deposit_type && <p className="text-xs text-destructive">{errors.deposit_type}</p>}
            </div>

            <div className="space-y-2">
              <Label className={errors.amount ? "text-destructive" : ""}>Amount *</Label>
              <Input 
                type="number" 
                step="0.01" 
                min="0.01"
                placeholder="0.00"
                value={formData.amount} 
                onChange={e => setFormData({...formData, amount: e.target.value})} 
                className={errors.amount ? "border-destructive" : ""}
              />
              {errors.amount && <p className="text-xs text-destructive">{errors.amount}</p>}
            </div>

            <div className="space-y-2">
              <Label>Reference #</Label>
              <Input 
                placeholder="Check #, Transaction ID..." 
                value={formData.reference} 
                onChange={e => setFormData({...formData, reference: e.target.value})} 
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label>Description</Label>
            <Input 
              placeholder="Brief description of the deposit" 
              value={formData.description} 
              onChange={e => setFormData({...formData, description: e.target.value})} 
            />
          </div>

          <div className="space-y-2">
            <Label>Notes</Label>
            <Textarea 
              placeholder="Additional internal notes..." 
              value={formData.notes} 
              onChange={e => setFormData({...formData, notes: e.target.value})} 
              className="resize-none h-20"
            />
          </div>

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