import React, { useState, useEffect } from 'react';
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 { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Plus, Trash2, Loader2, PlayCircle } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

export default function FinancialRuleDialog({ isOpen, onClose, onSave, initialData }) {
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: '', description: '', rule_type: 'Charge',
    parameters: [], conditions: [], actions: [],
  });
  const [errors, setErrors] = useState({});

  useEffect(() => {
    if (isOpen) {
      if (initialData) {
        setFormData({
          name: initialData.name || '',
          description: initialData.description || '',
          rule_type: initialData.rule_type || 'Charge',
          parameters: initialData.parameters || [],
          conditions: initialData.conditions || [],
          actions: initialData.actions || [],
        });
      } else {
        setFormData({ name: '', description: '', rule_type: 'Charge', parameters: [], conditions: [], actions: [] });
      }
      setErrors({});
    }
  }, [isOpen, initialData]);

  const handleAddParam = () => {
    setFormData(prev => ({
      ...prev,
      parameters: [...prev.parameters, { id: crypto.randomUUID(), name: '', type: 'Text', defaultValue: '' }]
    }));
  };

  const handleUpdateParam = (id, field, value) => {
    setFormData(prev => ({
      ...prev,
      parameters: prev.parameters.map(p => p.id === id ? { ...p, [field]: value } : p)
    }));
  };

  const handleRemoveParam = (id) => {
    setFormData(prev => ({ ...prev, parameters: prev.parameters.filter(p => p.id !== id) }));
  };

  const handleAddCondition = () => {
    setFormData(prev => ({
      ...prev,
      conditions: [...prev.conditions, { id: crypto.randomUUID(), field: '', operator: 'equals', value: '', logic: 'AND' }]
    }));
  };

  const handleUpdateCondition = (id, field, value) => {
    setFormData(prev => ({
      ...prev,
      conditions: prev.conditions.map(c => c.id === id ? { ...c, [field]: value } : c)
    }));
  };

  const handleRemoveCondition = (id) => {
    setFormData(prev => ({ ...prev, conditions: prev.conditions.filter(c => c.id !== id) }));
  };

  const handleAddAction = () => {
    setFormData(prev => ({
      ...prev,
      actions: [...prev.actions, { id: crypto.randomUUID(), type: 'Apply Charge', target: '', amount: '' }]
    }));
  };

  const handleUpdateAction = (id, field, value) => {
    setFormData(prev => ({
      ...prev,
      actions: prev.actions.map(a => a.id === id ? { ...a, [field]: value } : a)
    }));
  };

  const handleRemoveAction = (id) => {
    setFormData(prev => ({ ...prev, actions: prev.actions.filter(a => a.id !== id) }));
  };

  const validate = () => {
    const newErrors = {};
    if (!formData.name.trim()) newErrors.name = 'Rule name is required';
    if (!formData.rule_type) newErrors.rule_type = 'Rule type is required';
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validate()) return;
    setLoading(true);
    try {
      await onSave(formData);
      onClose();
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="text-2xl font-bold">
            {initialData ? 'Edit Financial Rule' : 'Create New Rule'}
          </DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-6 py-4">
          <div className="space-y-4">
            <div>
              <Label className="font-semibold">Rule Name *</Label>
              <Input 
                value={formData.name} 
                onChange={e => setFormData({...formData, name: e.target.value})} 
                placeholder="e.g., Late Fee on Overdue Balances"
                className={`mt-1 ${errors.name ? 'border-destructive' : ''}`}
              />
              {errors.name && <p className="text-destructive text-xs mt-1">{errors.name}</p>}
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label className="font-semibold">Rule Type *</Label>
                <Select value={formData.rule_type} onValueChange={v => setFormData({...formData, rule_type: v})}>
                  <SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="Charge">Charge Rule</SelectItem>
                    <SelectItem value="Payment">Payment Rule</SelectItem>
                    <SelectItem value="Adjustment">Adjustment</SelectItem>
                    <SelectItem value="Fee Rule">Fee Rule</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <Label className="font-semibold">Description</Label>
              <Textarea 
                value={formData.description} 
                onChange={e => setFormData({...formData, description: e.target.value})} 
                placeholder="Optional description of what this rule does..."
                className="mt-1" rows={2}
              />
            </div>
          </div>

          {/* Parameters Section */}
          <div className="p-4 rounded-xl bg-muted/50 border space-y-4">
            <div className="flex justify-between items-center">
              <Label className="font-bold text-base">Custom Parameters</Label>
              <Button type="button" variant="outline" size="sm" onClick={handleAddParam} className="h-8 gap-1 rounded-full">
                <Plus className="w-3 h-3" /> Add Parameter
              </Button>
            </div>
            <AnimatePresence>
              {formData.parameters.map((param) => (
                <motion.div key={param.id} initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, height: 0 }} className="flex gap-2 items-center bg-background p-2 rounded-lg border shadow-sm">
                  <Input placeholder="Param Name" value={param.name} onChange={e => handleUpdateParam(param.id, 'name', e.target.value)} className="flex-1" />
                  <Select value={param.type} onValueChange={v => handleUpdateParam(param.id, 'type', v)}>
                    <SelectTrigger className="w-[120px]"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Text">Text</SelectItem>
                      <SelectItem value="Number">Number</SelectItem>
                      <SelectItem value="Date">Date</SelectItem>
                      <SelectItem value="Percentage">Percentage</SelectItem>
                    </SelectContent>
                  </Select>
                  <Input placeholder="Default" value={param.defaultValue} onChange={e => handleUpdateParam(param.id, 'defaultValue', e.target.value)} className="w-[120px]" />
                  <Button type="button" variant="ghost" size="icon" onClick={() => handleRemoveParam(param.id)} className="text-muted-foreground hover:text-destructive"><Trash2 className="w-4 h-4" /></Button>
                </motion.div>
              ))}
            </AnimatePresence>
            {formData.parameters.length === 0 && <p className="text-sm text-muted-foreground italic">No custom parameters defined.</p>}
          </div>

          {/* Conditions Section */}
          <div className="p-4 rounded-xl bg-accent/30 border space-y-4">
            <div className="flex justify-between items-center">
              <Label className="font-bold text-base">Conditions</Label>
              <Button type="button" variant="outline" size="sm" onClick={handleAddCondition} className="h-8 gap-1 rounded-full">
                <Plus className="w-3 h-3" /> Add Condition
              </Button>
            </div>
            <AnimatePresence>
              {formData.conditions.map((cond, idx) => (
                <motion.div key={cond.id} initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, height: 0 }} className="flex gap-2 items-center bg-background p-2 rounded-lg border shadow-sm">
                  {idx > 0 && (
                    <Select value={cond.logic} onValueChange={v => handleUpdateCondition(cond.id, 'logic', v)}>
                      <SelectTrigger className="w-[80px] bg-muted"><SelectValue /></SelectTrigger>
                      <SelectContent><SelectItem value="AND">AND</SelectItem><SelectItem value="OR">OR</SelectItem></SelectContent>
                    </Select>
                  )}
                  <Input placeholder="Field (e.g. balance)" value={cond.field} onChange={e => handleUpdateCondition(cond.id, 'field', e.target.value)} className="flex-1" />
                  <Select value={cond.operator} onValueChange={v => handleUpdateCondition(cond.id, 'operator', v)}>
                    <SelectTrigger className="w-[120px]"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="equals">Equals</SelectItem>
                      <SelectItem value=">">{'>'}</SelectItem>
                      <SelectItem value="<">{'<'}</SelectItem>
                      <SelectItem value="contains">Contains</SelectItem>
                    </SelectContent>
                  </Select>
                  <Input placeholder="Value" value={cond.value} onChange={e => handleUpdateCondition(cond.id, 'value', e.target.value)} className="flex-1" />
                  <Button type="button" variant="ghost" size="icon" onClick={() => handleRemoveCondition(cond.id)} className="text-muted-foreground hover:text-destructive"><Trash2 className="w-4 h-4" /></Button>
                </motion.div>
              ))}
            </AnimatePresence>
            {formData.conditions.length === 0 && <p className="text-sm text-muted-foreground italic">Rule applies unconditionally if empty.</p>}
          </div>

          {/* Actions Section */}
          <div className="p-4 rounded-xl bg-green-50/50 border space-y-4">
            <div className="flex justify-between items-center">
              <Label className="font-bold text-base">Actions</Label>
              <Button type="button" variant="outline" size="sm" onClick={handleAddAction} className="h-8 gap-1 rounded-full">
                <Plus className="w-3 h-3" /> Add Action
              </Button>
            </div>
            <AnimatePresence>
              {formData.actions.map((act) => (
                <motion.div key={act.id} initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, height: 0 }} className="flex gap-2 items-center bg-background p-2 rounded-lg border shadow-sm">
                  <Select value={act.type} onValueChange={v => handleUpdateAction(act.id, 'type', v)}>
                    <SelectTrigger className="w-[160px]"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Apply Charge">Apply Charge</SelectItem>
                      <SelectItem value="Waive Fee">Waive Fee</SelectItem>
                      <SelectItem value="Send Notice">Send Notice</SelectItem>
                    </SelectContent>
                  </Select>
                  <Input placeholder="Target (e.g. Account)" value={act.target} onChange={e => handleUpdateAction(act.id, 'target', e.target.value)} className="flex-1" />
                  <Input placeholder="Amount / Value" value={act.amount} onChange={e => handleUpdateAction(act.id, 'amount', e.target.value)} className="w-[120px]" />
                  <Button type="button" variant="ghost" size="icon" onClick={() => handleRemoveAction(act.id)} className="text-muted-foreground hover:text-destructive"><Trash2 className="w-4 h-4" /></Button>
                </motion.div>
              ))}
            </AnimatePresence>
            {formData.actions.length === 0 && <p className="text-sm text-muted-foreground italic">Add actions to execute when conditions are met.</p>}
          </div>

          {/* Preview */}
          <div className="p-4 rounded-xl bg-card border space-y-2 relative overflow-hidden">
            <div className="absolute top-0 right-0 p-4 opacity-10"><PlayCircle className="w-24 h-24" /></div>
            <Label className="text-muted-foreground font-bold uppercase text-xs tracking-wider">Preview Summary</Label>
            <p className="text-sm font-medium">
              {formData.name ? `Rule: ${formData.name}` : 'Unnamed Rule'} ({formData.rule_type})
            </p>
            <p className="text-xs text-muted-foreground">
              If {formData.conditions.length} condition(s) met, execute {formData.actions.length} action(s).
            </p>
          </div>

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