import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Save, Loader2 } from 'lucide-react';

export const CategoryForm = ({ initialData = null, onSubmit, onCancel, isLoading }) => {
  const isEditMode = !!initialData;
  const [formData, setFormData] = useState({ categoria: '', idcategoria: '' });

  useEffect(() => {
    if (initialData) {
      setFormData({
        categoria: initialData.name || initialData.categoria || '',
        idcategoria: initialData.id || initialData.idcategoria || ''
      });
    }
  }, [initialData]);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!formData.categoria.trim()) return;
    const payload = isEditMode 
      ? { idcategoria: formData.idcategoria, categoria: formData.categoria }
      : { categoria: formData.categoria };
    onSubmit(payload);
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="space-y-2.5">
        <label className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] px-1">Título da Categoria / Tag</label>
        <Input
          placeholder="Ex: Fornecedores de Nuvem"
          value={formData.categoria}
          onChange={(e) => setFormData(prev => ({ ...prev, categoria: e.target.value }))}
          className="rounded-xl h-12 bg-white border-slate-200 text-slate-900 placeholder:text-slate-400 focus:border-emerald-500 transition-all font-medium shadow-sm"
          required
        />
      </div>
      <div className="flex gap-3 pt-6">
        <Button type="button" variant="outline" onClick={onCancel} className="flex-1 rounded-xl h-12 font-black uppercase tracking-widest text-[10px] border-slate-200 text-slate-600 hover:bg-slate-50" disabled={isLoading}>Descartar</Button>
        <Button type="submit" className="flex-1 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-black uppercase tracking-widest text-[10px] shadow-lg shadow-emerald-500/20" disabled={isLoading || !formData.categoria.trim()}>
          {isLoading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Save className="w-4 h-4 mr-2" />}
          {isEditMode ? 'Confirmar Edição' : 'Gerar Categoria'}
        </Button>
      </div>
    </form>
  );
};

export const CaixinhaForm = ({ initialData = null, onSubmit, onCancel, isLoading }) => {
  const isEditMode = !!initialData;
  const [formData, setFormData] = useState({ caixinha: '', idcaixinhas_financeiro: '' });

  useEffect(() => {
    if (initialData) {
      setFormData({
        caixinha: initialData.name || initialData.caixinha || '',
        idcaixinhas_financeiro: initialData.id || initialData.idcaixinhas_financeiro || ''
      });
    }
  }, [initialData]);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!formData.caixinha.trim()) return;
    const payload = isEditMode 
      ? { idcaixinhas_financeiro: formData.idcaixinhas_financeiro, caixinha: formData.caixinha }
      : { caixinha: formData.caixinha };
    onSubmit(payload);
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="space-y-2.5">
        <label className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] px-1">Título do Cofre / Destino</label>
        <Input
          placeholder="Ex: Reserva Emergencial"
          value={formData.caixinha}
          onChange={(e) => setFormData(prev => ({ ...prev, caixinha: e.target.value }))}
          className="rounded-xl h-12 bg-white border-slate-200 text-slate-900 placeholder:text-slate-400 focus:border-emerald-500 transition-all font-medium shadow-sm"
          required
        />
      </div>
      <div className="flex gap-3 pt-6">
        <Button type="button" variant="outline" onClick={onCancel} className="flex-1 rounded-xl h-12 font-black uppercase tracking-widest text-[10px] border-slate-200 text-slate-600 hover:bg-slate-50" disabled={isLoading}>Descartar</Button>
        <Button type="submit" className="flex-1 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-black uppercase tracking-widest text-[10px] shadow-lg shadow-emerald-500/20" disabled={isLoading || !formData.caixinha.trim()}>
          {isLoading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Save className="w-4 h-4 mr-2" />}
          {isEditMode ? 'Confirmar Edição' : 'Instanciar Cofre'}
        </Button>
      </div>
    </form>
  );
};

export const RuleForm = ({ categories = [], caixinhas = [], initialData = null, onSubmit, onCancel, isLoading }) => {
  const isEditMode = !!initialData;
  const [formData, setFormData] = useState({ regra: '', condicional: '', categoria: '', caixinha: '', beneficiario_pagador: '', id: '' });

  useEffect(() => {
    if (initialData) {
      setFormData({
        regra: initialData.name || initialData.regra || '',
        condicional: initialData.condition || initialData.condicional || '',
        categoria: initialData.categoryId || initialData.categoria || '',
        caixinha: initialData.caixinha || '',
        beneficiario_pagador: initialData.beneficiario || initialData.beneficiario_pagador || '',
        id: initialData.id || ''
      });
    }
  }, [initialData]);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!formData.regra.trim() || !formData.condicional.trim()) return;
    const payload = { ...formData, caixinha: formData.caixinha || '0', beneficiario_pagador: formData.beneficiario_pagador || '0' };
    onSubmit(payload);
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="space-y-2.5">
        <label className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] px-1">Identificação da Regra</label>
        <Input 
            value={formData.regra} 
            onChange={(e) => setFormData(prev => ({...prev, regra: e.target.value}))} 
            className="rounded-xl h-12 bg-white border-slate-200 text-slate-900 placeholder:text-slate-400 focus:border-emerald-500 transition-all font-medium shadow-sm" 
            placeholder="Ex: Conciliação Automática de Tarifas"
            required 
        />
      </div>
      <div className="space-y-2.5">
        <label className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] px-1">Termo Técnico de Busca</label>
        <Input 
            value={formData.condicional} 
            onChange={(e) => setFormData(prev => ({...prev, condicional: e.target.value}))} 
            className="rounded-xl h-12 bg-white border-slate-200 font-mono text-emerald-600 placeholder:text-slate-400 focus:border-emerald-500 transition-all shadow-sm" 
            placeholder="Ex: TAR CONV"
            required 
        />
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2.5">
          <label className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] px-1">Atribuir à Tag</label>
          <select 
            value={formData.categoria} 
            onChange={(e) => setFormData(prev => ({...prev, categoria: e.target.value}))} 
            className="w-full rounded-xl border border-slate-200 bg-white h-12 px-3 text-sm text-slate-900 outline-none focus:border-emerald-500 transition-all shadow-sm" 
            required
          >
            <option value="" className="text-slate-400">Selecionar...</option>
            {categories.map(cat => <option key={cat.id} value={cat.id}>{cat.name}</option>)}
          </select>
        </div>
        <div className="space-y-2.5">
          <label className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] px-1">Direcionar para Cofre</label>
          <select 
            value={formData.caixinha} 
            onChange={(e) => setFormData(prev => ({...prev, caixinha: e.target.value}))} 
            className="w-full rounded-xl border border-slate-200 bg-white h-12 px-3 text-sm text-slate-900 outline-none focus:border-emerald-500 transition-all shadow-sm"
          >
            <option value="" className="text-slate-400">Nenhum</option>
            {caixinhas.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </div>
      </div>
      <div className="flex gap-3 pt-6">
        <Button type="button" variant="outline" onClick={onCancel} className="flex-1 rounded-xl h-12 font-black uppercase tracking-widest text-[10px] border-slate-200 text-slate-600 hover:bg-slate-50" disabled={isLoading}>Descartar</Button>
        <Button type="submit" className="flex-1 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-black uppercase tracking-widest text-[10px] shadow-lg shadow-emerald-500/20" disabled={isLoading}>
          {isLoading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Save className="w-4 h-4 mr-2" />}
          {isEditMode ? 'Consolidar Alterações' : 'Decretar Nova Regra'}
        </Button>
      </div>
    </form>
  );
};

export const ReconciliationForm = ({ transaction, categories = [], caixinhas = [], onSubmit, onCancel, onSwitchToRule, isLoading }) => {
  const [formData, setFormData] = useState({
    idextrato: '',
    categoria: '',
    caixinha: '0',
    beneficiario_pagador: '',
    descricao: '',
    dataEntrada: '',
    valor: ''
  });

  useEffect(() => {
    if (transaction) {
      setFormData({
        idextrato: transaction.id || '',
        categoria: transaction.externalCategoryId || '',
        caixinha: transaction.raw?.caixinha || '0',
        beneficiario_pagador: transaction.raw?.beneficiario_pagador || '',
        descricao: transaction.description || '',
        dataEntrada: transaction.date?.toLocaleDateString('pt-BR') || '',
        valor: new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(transaction.amount)
      });
    }
  }, [transaction]);

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit(formData);
  };

  const handleRuleSwitch = () => {
    onSwitchToRule({
      name: '',
      condition: formData.descricao,
      categoryId: formData.categoria,
      caixinha: formData.caixinha,
      beneficiario: formData.beneficiario_pagador
    });
  };

  const isEntry = transaction?.amount > 0;

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="space-y-2.5">
          <label className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] px-1">Data</label>
          <Input value={formData.dataEntrada} disabled className="rounded-xl h-12 bg-slate-50 border-slate-200 text-slate-500 font-medium" />
        </div>
        <div className="space-y-2.5">
          <label className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] px-1">Montante</label>
          <Input value={formData.valor} disabled className={`rounded-xl h-12 bg-slate-50 border-slate-200 font-mono font-bold ${transaction?.amount < 0 ? 'text-rose-500' : 'text-emerald-600'}`} />
        </div>
      </div>

      <div className="space-y-2.5">
        <label className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] px-1">Descrição / Condicional</label>
        <Input 
          value={formData.descricao} 
          onChange={(e) => setFormData(prev => ({ ...prev, descricao: e.target.value }))}
          className="rounded-xl h-12 bg-white border-slate-200 text-slate-900 font-medium focus:border-emerald-500 transition-all shadow-sm" 
          required
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="space-y-2.5">
          <label className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] px-1">Tag (Categoria)</label>
          <select 
            value={formData.categoria} 
            onChange={(e) => setFormData(prev => ({ ...prev, categoria: e.target.value }))} 
            className="w-full rounded-xl border border-slate-200 bg-white h-12 px-3 text-sm text-slate-900 outline-none focus:border-emerald-500 transition-all font-medium shadow-sm"
            required
          >
            <option value="" className="text-slate-400">Selecione...</option>
            {categories.map(cat => <option key={cat.id} value={cat.id}>{cat.name}</option>)}
          </select>
        </div>
        <div className="space-y-2.5">
          <label className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] px-1">Cofre (Caixinha)</label>
          <select 
            value={formData.caixinha} 
            onChange={(e) => setFormData(prev => ({ ...prev, caixinha: e.target.value }))} 
            className="w-full rounded-xl border border-slate-200 bg-white h-12 px-3 text-sm text-slate-900 outline-none focus:border-emerald-500 transition-all font-medium shadow-sm"
            required
          >
            <option value="0" className="text-slate-400">Nenhum</option>
            {caixinhas.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </div>
      </div>

      <div className="space-y-2.5">
        <label className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] px-1">
          {isEntry ? 'Recebido de' : 'Enviado para'}
        </label>
        <Input 
          value={formData.beneficiario_pagador} 
          onChange={(e) => setFormData(prev => ({ ...prev, beneficiario_pagador: e.target.value }))}
          className="rounded-xl h-12 bg-white border-slate-200 text-slate-900 font-medium focus:border-emerald-500 transition-all shadow-sm" 
          placeholder="Nome do favorecido ou pagador"
          required
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-3 pt-6">
        <Button 
          type="button" 
          variant="outline" 
          onClick={onCancel} 
          className="rounded-xl h-12 font-black uppercase tracking-widest text-[10px] border-slate-200 text-slate-600 hover:bg-slate-50"
          disabled={isLoading}
        >
          Descartar
        </Button>
        <Button 
          type="button" 
          variant="outline" 
          onClick={handleRuleSwitch} 
          className="rounded-xl h-12 font-black uppercase tracking-widest text-[10px] border-emerald-200 text-emerald-600 hover:bg-emerald-50 gap-2 shadow-lg shadow-emerald-500/5"
          disabled={isLoading}
        >
          <Save className="w-3.5 h-3.5" />
          Regra
        </Button>
        <Button 
          type="submit" 
          className="rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-black uppercase tracking-widest text-[10px] shadow-lg shadow-emerald-500/20 gap-2"
          disabled={isLoading}
        >
          {isLoading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Save className="w-3.5 h-3.5" />}
          Enviar
        </Button>
      </div>
    </form>
  );
};

