import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Loader2, Save, Sparkles } from 'lucide-react';

/**
 * Modal para categorizar uma transação
 * Formulário simples que permite editar categoria, caixinha e beneficiário/pagador
 */
export const CategorizarTransacaoModal = ({
  isOpen,
  onClose,
  transaction,
  categories = [],
  caixinhas = [],
  onSubmit,
  onSwitchToCriarRegra,
  isLoading = false
}) => {
  const [formData, setFormData] = useState({
    idextrato: '',
    categoria: '',
    caixinha: '0',
    beneficiario_pagador: '',
    descricao: '',
    data: '',
    valor: '',
    tipo: ''
  });

  useEffect(() => {
    if (transaction) {
      setFormData({
        idextrato: transaction.id || '',
        categoria: transaction.categoriaId || transaction.categoria || '',
        caixinha: transaction.caixaId || transaction.caixinha || '0',
        beneficiario_pagador: transaction.beneficiario || transaction.beneficiario_pagador || '',
        descricao: transaction.descricao || '',
        data: transaction.data || '',
        valor: transaction.valor || 0,
        tipo: transaction.tipo || ''
      });
    }
  }, [transaction]);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!formData.categoria) {
      return;
    }
    onSubmit(formData);
  };

  const handleSwitchToRegra = () => {
    if (onSwitchToCriarRegra) {
      onSwitchToCriarRegra(formData);
    }
  };

  const formatCurrency = (value) => {
    if (!value) return 'R$ 0,00';
    return new Intl.NumberFormat('pt-BR', {
      style: 'currency',
      currency: 'BRL'
    }).format(value);
  };

  const formatDate = (dateStr) => {
    if (!dateStr) return '';
    // Se já está no formato DD/MM/YYYY, retorna direto
    if (/^\d{2}\/\d{2}\/\d{4}$/.test(dateStr)) return dateStr;
    // Se está no formato YYYY-MM-DD, converte
    if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
      const [year, month, day] = dateStr.split('-');
      return `${day}/${month}/${year}`;
    }
    return dateStr;
  };

  const isDebito = formData.tipo === 'DEBITO' || formData.tipo === 'D';

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle className="text-xl font-bold uppercase tracking-tight">
            Categorizar Transação
          </DialogTitle>
          <DialogDescription className="text-sm text-slate-500">
            Preencha os campos abaixo para categorizar esta transação
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-6 mt-4">
          {/* Informações da transação (somente leitura) */}
          <div className="grid grid-cols-2 gap-4 p-4 bg-slate-50 dark:bg-[#1e1e1e] rounded-xl border border-slate-200 dark:border-white/10">
            <div className="space-y-1">
              <label className="text-[10px] font-bold text-slate-500 uppercase tracking-[0.2em]">
                Data
              </label>
              <div className="text-sm font-medium text-slate-700 dark:text-stone-300">
                {formatDate(formData.data)}
              </div>
            </div>
            <div className="space-y-1">
              <label className="text-[10px] font-bold text-slate-500 uppercase tracking-[0.2em]">
                Valor
              </label>
              <div className={`text-sm font-bold font-mono ${
                isDebito ? 'text-red-600 dark:text-red-400' : 'text-green-600 dark:text-green-400'
              }`}>
                {formatCurrency(formData.valor)}
              </div>
            </div>
            <div className="space-y-1">
              <label className="text-[10px] font-bold text-slate-500 uppercase tracking-[0.2em]">
                Tipo
              </label>
              <div className={`text-xs font-bold uppercase ${
                isDebito ? 'text-red-600 dark:text-red-400' : 'text-green-600 dark:text-green-400'
              }`}>
                {formData.tipo || 'DEBITO'}
              </div>
            </div>
          </div>

          {/* Descrição / Condicional (editável) */}
          <div className="space-y-2">
            <label className="text-[10px] font-bold text-slate-600 dark:text-stone-400 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 dark:bg-[#252525] border-slate-200 dark:border-white/10 text-slate-900 dark:text-stone-300 font-medium focus:border-[#26b1c7] transition-all shadow-sm"
              placeholder="Descrição da transação"
              required
            />
          </div>

          {/* Categoria e Caixa */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <label className="text-[10px] font-bold text-slate-600 dark:text-stone-400 uppercase tracking-[0.2em] px-1">
                Categoria *
              </label>
              <select
                value={formData.categoria}
                onChange={(e) => setFormData(prev => ({ ...prev, categoria: e.target.value }))}
                className="w-full rounded-xl border border-slate-200 dark:border-white/10 bg-white dark:bg-[#252525] h-12 px-3 text-sm text-slate-900 dark:text-stone-300 outline-none focus:border-[#26b1c7] transition-all font-medium shadow-sm"
                required
              >
                <option value="" className="text-slate-400">Selecione uma categoria</option>
                {categories.map(cat => (
                  <option key={cat.id} value={cat.id}>{cat.name}</option>
                ))}
              </select>
            </div>
            <div className="space-y-2">
              <label className="text-[10px] font-bold text-slate-600 dark:text-stone-400 uppercase tracking-[0.2em] px-1">
                Caixa *
              </label>
              <select
                value={formData.caixinha}
                onChange={(e) => setFormData(prev => ({ ...prev, caixinha: e.target.value }))}
                className="w-full rounded-xl border border-slate-200 dark:border-white/10 bg-white dark:bg-[#252525] h-12 px-3 text-sm text-slate-900 dark:text-stone-300 outline-none focus:border-[#26b1c7] 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>

          {/* Beneficiário / Pagador */}
          <div className="space-y-2">
            <label className="text-[10px] font-bold text-slate-600 dark:text-stone-400 uppercase tracking-[0.2em] px-1">
              Beneficiário / Pagador *
            </label>
            <Input
              value={formData.beneficiario_pagador}
              onChange={(e) => setFormData(prev => ({ ...prev, beneficiario_pagador: e.target.value }))}
              className="rounded-xl h-12 bg-white dark:bg-[#252525] border-slate-200 dark:border-white/10 text-slate-900 dark:text-stone-300 font-medium focus:border-[#26b1c7] transition-all shadow-sm"
              placeholder="Ex: Fornecedor ABC Ltda"
              required
            />
          </div>

          {/* Botões */}
          <div className="flex gap-3 pt-4">
            <Button
              type="button"
              variant="outline"
              onClick={onClose}
              className="flex-1 rounded-xl h-12 font-bold uppercase tracking-widest text-[10px] border-slate-200 dark:border-white/10 text-slate-600 dark:text-stone-400 hover:bg-slate-50 dark:hover:bg-[#1e1e1e]"
              disabled={isLoading}
            >
              X Cancelar
            </Button>
            <Button
              type="button"
              variant="outline"
              onClick={handleSwitchToRegra}
              className="rounded-xl h-12 font-bold uppercase tracking-widest text-[10px] border-[#26b1c7] text-[#26b1c7] hover:bg-[#26b1c7]/10 gap-2"
              disabled={isLoading}
            >
              <Sparkles className="w-4 h-4" />
              Criar Regra
            </Button>
            <Button
              type="submit"
              className="flex-1 rounded-xl bg-[#26b1c7] hover:bg-[#1f9fb3] text-white font-bold uppercase tracking-widest text-[10px] shadow-lg shadow-[#26b1c7]/20 gap-2"
              disabled={isLoading || !formData.categoria}
            >
              {isLoading ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Save className="w-4 h-4" />
              )}
              Categorizar
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
};
