
import React, { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } 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 { Switch } from '@/components/ui/switch';
import { Loader2 } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';

export default function RuleEditorDialog({ open, onOpenChange, rule, onSuccess }) {
  const { toast } = useToast();
  const { user } = useAuth();
  const [loading, setLoading] = useState(false);
  const [accounts, setAccounts] = useState([]);
  
  const [formData, setFormData] = useState({
    transaction_type: 'vendor_bill', category_key: '', fund_type: 'operating',
    debit_account_id: '', credit_account_id: '', priority: 10, is_active: true, description: ''
  });

  useEffect(() => { fetchAccounts(); }, []);

  useEffect(() => {
    if (open && rule) {
      setFormData({
        transaction_type: rule.transaction_type || 'vendor_bill', category_key: rule.category_key || '',
        fund_type: rule.fund_type || 'operating', debit_account_id: rule.debit_account_id || '',
        credit_account_id: rule.credit_account_id || '', priority: rule.priority || 10,
        is_active: rule.is_active !== false, description: rule.description || ''
      });
    } else if (open) {
      setFormData({ transaction_type: 'vendor_bill', category_key: '', fund_type: 'operating', debit_account_id: '', credit_account_id: '', priority: 10, is_active: true, description: '' });
    }
  }, [open, rule]);

  const fetchAccounts = async () => {
    try {
      const { data } = await supabase.from('chart_of_accounts').select('id, account_name, account_number, account_type').order('account_number');
      if (data) setAccounts(data);
    } catch (err) { console.error(err); }
  };

  const handleChange = (e) => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (formData.debit_account_id === formData.credit_account_id) {
      toast({ variant: 'destructive', title: 'Error', description: 'Debit and Credit accounts must be different.' }); return;
    }
    if (formData.priority <= 0) {
      toast({ variant: 'destructive', title: 'Error', description: 'Priority must be > 0.' }); return;
    }

    setLoading(true);
    try {
      const payload = { ...formData };

      if (rule?.id) {
        const { error } = await supabase.from('coa_mapping_rules').update(payload).eq('id', rule.id);
        if (error) throw error;
        toast({ title: 'Success', description: 'Rule updated successfully.' });
      } else {
        const { error } = await supabase.from('coa_mapping_rules').insert([payload]);
        if (error) throw error;
        toast({ title: 'Success', description: 'Rule created successfully.' });
      }
      onSuccess?.();
      onOpenChange(false);
    } catch (err) {
      console.error(err);
      toast({ variant: 'destructive', title: 'Error saving rule', description: err.message });
    } finally { setLoading(false); }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader><DialogTitle>{rule ? 'Edit Mapping Rule' : 'Create Mapping Rule'}</DialogTitle></DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4 py-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Transaction Type</Label>
              <Select value={formData.transaction_type} onValueChange={(val) => setFormData(p => ({...p, transaction_type: val}))}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="vendor_bill">Vendor Bill</SelectItem>
                  <SelectItem value="owner_charge">Owner Charge</SelectItem>
                  <SelectItem value="owner_payment">Owner Payment</SelectItem>
                  <SelectItem value="bank_deposit">Bank Deposit</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Fund Type</Label>
              <Select value={formData.fund_type} onValueChange={(val) => setFormData(p => ({...p, fund_type: val}))}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="operating">Operating</SelectItem>
                  <SelectItem value="reserve">Reserve</SelectItem>
                  <SelectItem value="special">Special</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="space-y-2"><Label>Category Key (Optional)</Label><Input name="category_key" value={formData.category_key} onChange={handleChange} placeholder="e.g. landscaping" /></div>
          <div className="space-y-2">
            <Label>Debit Account</Label>
            <Select value={formData.debit_account_id} onValueChange={(val) => setFormData(p => ({...p, debit_account_id: val}))}>
              <SelectTrigger><SelectValue placeholder="Select Account" /></SelectTrigger>
              <SelectContent>{accounts.map(acc => <SelectItem key={acc.id} value={acc.id}>{acc.account_number} - {acc.account_name}</SelectItem>)}</SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Credit Account</Label>
            <Select value={formData.credit_account_id} onValueChange={(val) => setFormData(p => ({...p, credit_account_id: val}))}>
              <SelectTrigger><SelectValue placeholder="Select Account" /></SelectTrigger>
              <SelectContent>{accounts.map(acc => <SelectItem key={acc.id} value={acc.id}>{acc.account_number} - {acc.account_name}</SelectItem>)}</SelectContent>
            </Select>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2"><Label>Priority</Label><Input type="number" name="priority" value={formData.priority} onChange={handleChange} min="1" /></div>
            <div className="space-y-2 flex flex-col justify-end">
              <div className="flex items-center space-x-2 pb-2">
                <Switch checked={formData.is_active} onCheckedChange={(c) => setFormData(p => ({...p, is_active: c}))} id="active-mode" />
                <Label htmlFor="active-mode">Is Active</Label>
              </div>
            </div>
          </div>
          <div className="space-y-2"><Label>Description</Label><Input name="description" value={formData.description} onChange={handleChange} placeholder="Rule notes..." /></div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button type="submit" disabled={loading}>{loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />} Save Rule</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
