import { useState, useEffect, useRef } from 'react';
import { ProdutoService } from '../services/api';
import {
  Package, Plus, Search, Upload, RefreshCw, Pencil, Trash2, X, Check,
  ChevronDown, BarChart3, Tag,
} from 'lucide-react';

// ─── helpers ──────────────────────────────────────────────────────────────────

const formatBRL = (v: number) => Number(v).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });

function Badge({ children, color = 'slate' }: { children: React.ReactNode; color?: string }) {
  const cls: Record<string, string> = {
    emerald: 'bg-emerald-400/10 text-emerald-400',
    rose:    'bg-rose-400/10 text-rose-400',
    slate:   'bg-slate-700 text-slate-400',
    cyan:    'bg-cyan-400/10 text-cyan-400',
  };
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded-lg text-[10px] font-black uppercase tracking-widest ${cls[color] || cls.slate}`}>
      {children}
    </span>
  );
}

// ─── Modal produto ────────────────────────────────────────────────────────────

function ProdutoModal({ produto, categorias, onClose, onSave }: {
  produto: any | null;
  categorias: string[];
  onClose: () => void;
  onSave: () => void;
}) {
  const isEdit = !!produto;
  const [form, setForm] = useState({
    sku: produto?.sku || '',
    nome: produto?.nome || '',
    descricao: produto?.descricao || '',
    unidade: produto?.unidade || 'un',
    preco: produto?.preco ?? '',
    preco_promocional: produto?.preco_promocional ?? '',
    estoque: produto?.estoque ?? '',
    categoria: produto?.categoria || '',
    ativo: produto?.ativo !== false,
  });
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState('');

  const f = (k: string) => (e: any) => setForm(p => ({ ...p, [k]: e.target.value }));

  async function salvar() {
    setErr('');
    if (!form.nome.trim()) return setErr('Nome é obrigatório');
    if (form.preco === '' || isNaN(Number(form.preco))) return setErr('Preço inválido');
    setSaving(true);
    try {
      const data = {
        ...form,
        preco: Number(form.preco),
        preco_promocional: form.preco_promocional !== '' ? Number(form.preco_promocional) : null,
        estoque: Number(form.estoque) || 0,
      };
      if (isEdit) await ProdutoService.update(produto.id, data);
      else await ProdutoService.create(data);
      onSave();
    } catch (e: any) {
      setErr(e.response?.data?.error || 'Erro ao salvar');
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
      <div className="bg-slate-900 border border-slate-800 rounded-3xl w-full max-w-lg shadow-2xl">
        <div className="flex items-center justify-between p-6 border-b border-slate-800">
          <h3 className="text-lg font-black text-white">{isEdit ? 'Editar Produto' : 'Novo Produto'}</h3>
          <button onClick={onClose} className="text-slate-500 hover:text-white transition-colors"><X size={20} /></button>
        </div>
        <div className="p-6 space-y-4 max-h-[70vh] overflow-y-auto">
          {err && <p className="text-rose-400 text-sm bg-rose-400/10 px-3 py-2 rounded-xl">{err}</p>}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-black text-slate-400 uppercase tracking-widest mb-1">SKU</label>
              <input value={form.sku} onChange={f('sku')} placeholder="ex: ARROZ-5KG"
                className="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500" />
            </div>
            <div>
              <label className="block text-xs font-black text-slate-400 uppercase tracking-widest mb-1">Unidade</label>
              <select value={form.unidade} onChange={f('unidade')}
                className="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500">
                {['un','kg','lt','cx','pct','fdo','dz'].map(u => <option className="bg-slate-900 text-white" key={u}>{u}</option>)}
              </select>
            </div>
          </div>
          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-widest mb-1">Nome *</label>
            <input value={form.nome} onChange={f('nome')} placeholder="Nome do produto"
              className="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500" />
          </div>
          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-widest mb-1">Descrição</label>
            <textarea value={form.descricao} onChange={f('descricao')} rows={2}
              className="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500 resize-none" />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-black text-slate-400 uppercase tracking-widest mb-1">Preço *</label>
              <input type="number" step="0.01" value={form.preco} onChange={f('preco')} placeholder="0,00"
                className="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500" />
            </div>
            <div>
              <label className="block text-xs font-black text-slate-400 uppercase tracking-widest mb-1">
                Preço Promo <span className="text-slate-600 normal-case font-normal">(opcional)</span>
              </label>
              <input type="number" step="0.01" value={form.preco_promocional} onChange={f('preco_promocional')} placeholder="—"
                className="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-emerald-500" />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-black text-slate-400 uppercase tracking-widest mb-1">Estoque</label>
              <input type="number" step="0.001" value={form.estoque} onChange={f('estoque')} placeholder="0"
                className="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500" />
            </div>
            <div className="flex items-end pb-2">
              {form.preco_promocional !== '' && Number(form.preco_promocional) > 0 && Number(form.preco) > 0 && (
                <p className="text-xs text-emerald-400 font-bold">
                  {Math.round((1 - Number(form.preco_promocional) / Number(form.preco)) * 100)}% de desconto
                </p>
              )}
            </div>
          </div>
          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-widest mb-1">Categoria</label>
            <input value={form.categoria} onChange={f('categoria')} list="cats" placeholder="ex: Bebidas"
              className="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500" />
            <datalist id="cats">{categorias.map(c => <option className="bg-slate-900 text-white" key={c} value={c} />)}</datalist>
          </div>
          {isEdit && (
            <label className="flex items-center gap-3 cursor-pointer">
              <div className={`w-10 h-6 rounded-full transition-colors ${form.ativo ? 'bg-emerald-500' : 'bg-slate-700'}`}
                onClick={() => setForm(p => ({ ...p, ativo: !p.ativo }))}>
                <div className={`w-4 h-4 bg-white rounded-full mt-1 transition-all ${form.ativo ? 'ml-5' : 'ml-1'}`} />
              </div>
              <span className="text-sm text-slate-300 font-medium">Produto ativo</span>
            </label>
          )}
        </div>
        <div className="p-6 border-t border-slate-800 flex gap-3 justify-end">
          <button onClick={onClose} className="px-4 py-2 text-slate-400 hover:text-white transition-colors text-sm font-bold">Cancelar</button>
          <button onClick={salvar} disabled={saving}
            className="px-6 py-2 bg-cyan-500 hover:bg-cyan-400 disabled:opacity-50 rounded-xl text-black font-black text-sm transition-colors flex items-center gap-2">
            {saving ? <RefreshCw size={14} className="animate-spin" /> : <Check size={14} />}
            {isEdit ? 'Salvar' : 'Criar'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Modal importar CSV ───────────────────────────────────────────────────────

function ImportModal({ onClose, onDone }: { onClose: () => void; onDone: () => void }) {
  const [csv, setCsv] = useState('');
  const [result, setResult] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState('');
  const fileRef = useRef<HTMLInputElement>(null);

  function parseCSV(text: string) {
    const lines = text.trim().split('\n');
    const headers = lines[0].split(';').map(h => h.trim().toLowerCase().replace(/"/g, ''));
    return lines.slice(1).map(line => {
      const vals = line.split(';').map(v => v.trim().replace(/"/g, ''));
      const obj: any = {};
      headers.forEach((h, i) => { obj[h] = vals[i] || '' });
      return obj;
    }).filter(r => r.nome || r.sku);
  }

  async function importar() {
    setErr(''); setResult(null);
    if (!csv.trim()) return setErr('Cole o conteúdo CSV ou carregue um arquivo');
    const produtos = parseCSV(csv);
    if (!produtos.length) return setErr('Nenhum produto válido encontrado no CSV');
    setLoading(true);
    try {
      const r = await ProdutoService.importar(produtos.map(p => ({
        sku: p.sku || p.codigo,
        nome: p.nome || p.descricao,
        descricao: p.observacao || '',
        unidade: p.unidade || 'un',
        preco: parseFloat((p.preco || '0').replace(',', '.')),
        estoque: parseFloat((p.estoque || p.quantidade || '0').replace(',', '.')),
        categoria: p.categoria || p.grupo || '',
      })));
      setResult(r);
    } catch (e: any) {
      setErr(e.response?.data?.error || 'Erro na importação');
    } finally {
      setLoading(false);
    }
  }

  function onFile(e: React.ChangeEvent<HTMLInputElement>) {
    const f = e.target.files?.[0];
    if (!f) return;
    const reader = new FileReader();
    reader.onload = ev => setCsv(ev.target?.result as string || '');
    reader.readAsText(f, 'utf-8');
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
      <div className="bg-slate-900 border border-slate-800 rounded-3xl w-full max-w-2xl shadow-2xl">
        <div className="flex items-center justify-between p-6 border-b border-slate-800">
          <h3 className="text-lg font-black text-white flex items-center gap-2"><Upload size={18} className="text-cyan-400" /> Importar CSV</h3>
          <button onClick={onClose} className="text-slate-500 hover:text-white"><X size={20} /></button>
        </div>
        <div className="p-6 space-y-4">
          <p className="text-slate-400 text-sm">Colunas esperadas (separadas por <code className="text-cyan-400 text-xs">;</code>):</p>
          <code className="block bg-slate-800 rounded-xl px-4 py-3 text-xs text-slate-300">sku;nome;descricao;unidade;preco;estoque;categoria</code>
          <div className="flex gap-3">
            <button onClick={() => fileRef.current?.click()}
              className="flex items-center gap-2 px-4 py-2 bg-slate-800 hover:bg-slate-700 rounded-xl text-sm text-slate-300 font-bold transition-colors">
              <Upload size={14} /> Carregar arquivo
            </button>
            <input ref={fileRef} type="file" accept=".csv,.txt" className="hidden" onChange={onFile} />
          </div>
          <textarea value={csv} onChange={e => setCsv(e.target.value)} rows={8} placeholder="Ou cole o CSV aqui..."
            className="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-xs text-slate-300 font-mono focus:outline-none focus:border-cyan-500 resize-none" />
          {err && <p className="text-rose-400 text-sm bg-rose-400/10 px-3 py-2 rounded-xl">{err}</p>}
          {result && (
            <div className="bg-slate-800 rounded-xl p-4 space-y-1 text-sm">
              <p className="text-emerald-400 font-bold">Inseridos: {result.inseridos}</p>
              <p className="text-cyan-400 font-bold">Atualizados: {result.atualizados}</p>
              {result.erros?.length > 0 && (
                <div className="text-rose-400">
                  <p className="font-bold">Erros ({result.erros.length}):</p>
                  <ul className="list-disc list-inside text-xs mt-1 space-y-0.5">
                    {result.erros.map((e: any, i: number) => <li key={i}>{e.sku}: {e.erro}</li>)}
                  </ul>
                </div>
              )}
            </div>
          )}
        </div>
        <div className="p-6 border-t border-slate-800 flex gap-3 justify-end">
          {result ? (
            <button onClick={() => { onDone(); onClose(); }}
              className="px-6 py-2 bg-emerald-500 hover:bg-emerald-400 rounded-xl text-black font-black text-sm transition-colors">
              Concluído
            </button>
          ) : (
            <>
              <button onClick={onClose} className="px-4 py-2 text-slate-400 hover:text-white transition-colors text-sm font-bold">Cancelar</button>
              <button onClick={importar} disabled={loading}
                className="px-6 py-2 bg-cyan-500 hover:bg-cyan-400 disabled:opacity-50 rounded-xl text-black font-black text-sm transition-colors flex items-center gap-2">
                {loading ? <RefreshCw size={14} className="animate-spin" /> : <Upload size={14} />}
                Importar
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Main ─────────────────────────────────────────────────────────────────────

export default function CatalogPage() {
  const [produtos, setProdutos]       = useState<any[]>([]);
  const [categorias, setCategorias]   = useState<string[]>([]);
  const [loading, setLoading]         = useState(true);
  const [search, setSearch]           = useState('');
  const [catFiltro, setCatFiltro]     = useState('');
  const [modal, setModal]             = useState<'new' | 'edit' | 'import' | null>(null);
  const [selected, setSelected]       = useState<any>(null);

  async function load() {
    setLoading(true);
    try {
      const [prods, cats] = await Promise.all([
        ProdutoService.list({ search: search || undefined, categoria: catFiltro || undefined }),
        ProdutoService.categorias(),
      ]);
      setProdutos(prods);
      setCategorias(cats);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => { load(); }, [search, catFiltro]);

  async function deletar(id: number) {
    if (!confirm('Remover produto?')) return;
    await ProdutoService.delete(id);
    load();
  }

  const ativos   = produtos.filter(p => p.ativo).length;
  const semEstoque = produtos.filter(p => Number(p.estoque) <= 0).length;

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-700">
      <header className="flex flex-wrap justify-between items-start gap-4">
        <div>
          <h2 className="text-3xl font-black text-white tracking-tighter flex items-center gap-3">
            <Package className="text-cyan-400" size={28} /> Catálogo de Produtos
          </h2>
          <p className="text-slate-400 mt-1 font-medium">{produtos.length} produtos · {ativos} ativos · {semEstoque} sem estoque</p>
        </div>
        <div className="flex gap-3 flex-wrap">
          <button onClick={() => setModal('import')}
            className="flex items-center gap-2 px-4 py-2 bg-slate-800 hover:bg-slate-700 border border-slate-700 rounded-xl text-sm text-slate-300 font-bold transition-colors">
            <Upload size={16} /> Importar CSV
          </button>
          <button onClick={() => { setSelected(null); setModal('new'); }}
            className="flex items-center gap-2 px-4 py-2 bg-cyan-500 hover:bg-cyan-400 rounded-xl text-black font-black text-sm transition-colors">
            <Plus size={16} /> Novo Produto
          </button>
        </div>
      </header>

      {/* Filtros */}
      <div className="flex gap-3 flex-wrap">
        <div className="relative flex-1 min-w-48">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar por nome, SKU..."
            className="w-full bg-slate-900 border border-slate-800 rounded-xl pl-9 pr-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500" />
        </div>
        <div className="relative">
          <Tag size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
          <select value={catFiltro} onChange={e => setCatFiltro(e.target.value)}
            className="bg-slate-900 border border-slate-800 rounded-xl pl-9 pr-8 py-2 text-sm text-slate-300 focus:outline-none focus:border-cyan-500 appearance-none cursor-pointer">
            <option className="bg-slate-900 text-white" value="">Todas as categorias</option>
            {categorias.map(c => <option className="bg-slate-900 text-white" key={c} value={c}>{c}</option>)}
          </select>
          <ChevronDown size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 pointer-events-none" />
        </div>
        <button onClick={load} className="p-2 bg-slate-900 border border-slate-800 rounded-xl text-slate-400 hover:text-white transition-colors">
          <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
        </button>
      </div>

      {/* Tabela */}
      <div className="bg-slate-900/40 border border-slate-800 rounded-3xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-800 text-left">
                <th className="px-6 py-4 text-xs font-black text-slate-500 uppercase tracking-widest">Produto</th>
                <th className="px-4 py-4 text-xs font-black text-slate-500 uppercase tracking-widest">SKU</th>
                <th className="px-4 py-4 text-xs font-black text-slate-500 uppercase tracking-widest">Categoria</th>
                <th className="px-4 py-4 text-xs font-black text-slate-500 uppercase tracking-widest text-right">Preço</th>
                <th className="px-4 py-4 text-xs font-black text-slate-500 uppercase tracking-widest text-right">Estoque</th>
                <th className="px-4 py-4 text-xs font-black text-slate-500 uppercase tracking-widest">Status</th>
                <th className="px-4 py-4" />
              </tr>
            </thead>
            <tbody>
              {loading ? (
                [...Array(5)].map((_, i) => (
                  <tr key={i} className="border-b border-slate-800/50 animate-pulse">
                    {[...Array(7)].map((_, j) => (
                      <td key={j} className="px-4 py-4"><div className="h-4 bg-slate-800 rounded w-full" /></td>
                    ))}
                  </tr>
                ))
              ) : produtos.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-6 py-16 text-center text-slate-600 text-sm italic">
                    Nenhum produto encontrado. Importe um CSV ou crie manualmente.
                  </td>
                </tr>
              ) : (
                produtos.map(p => (
                  <tr key={p.id} className="border-b border-slate-800/50 hover:bg-slate-800/20 transition-colors group">
                    <td className="px-6 py-4">
                      <div>
                        <p className="font-bold text-white">{p.nome}</p>
                        {p.descricao && <p className="text-xs text-slate-500 truncate max-w-48">{p.descricao}</p>}
                      </div>
                    </td>
                    <td className="px-4 py-4 text-slate-400 font-mono text-xs">{p.sku || '—'}</td>
                    <td className="px-4 py-4">
                      {p.categoria ? <Badge color="cyan">{p.categoria}</Badge> : <span className="text-slate-600 text-xs">—</span>}
                    </td>
                    <td className="px-4 py-4 text-right tabular-nums">
                      {p.preco_promocional ? (
                        <>
                          <p className="text-xs text-slate-500 line-through">{formatBRL(p.preco)}</p>
                          <p className="font-bold text-emerald-400">{formatBRL(p.preco_promocional)}</p>
                        </>
                      ) : (
                        <span className="font-bold text-white">{formatBRL(p.preco)}</span>
                      )}
                    </td>
                    <td className="px-4 py-4 text-right tabular-nums">
                      <span className={`font-bold ${Number(p.estoque) <= 0 ? 'text-rose-400' : Number(p.estoque) < 5 ? 'text-yellow-400' : 'text-slate-300'}`}>
                        {Number(p.estoque).toLocaleString('pt-BR')} {p.unidade}
                      </span>
                    </td>
                    <td className="px-4 py-4">
                      <Badge color={p.ativo ? 'emerald' : 'rose'}>{p.ativo ? 'Ativo' : 'Inativo'}</Badge>
                    </td>
                    <td className="px-4 py-4">
                      <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity justify-end">
                        <button onClick={() => { setSelected(p); setModal('edit'); }}
                          className="p-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition-colors">
                          <Pencil size={14} />
                        </button>
                        <button onClick={() => deletar(p.id)}
                          className="p-2 rounded-lg bg-slate-800 hover:bg-rose-500/20 text-slate-400 hover:text-rose-400 transition-colors">
                          <Trash2 size={14} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Stats rápidos */}
      {!loading && produtos.length > 0 && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {[
            { label: 'Total', value: produtos.length, icon: Package, color: 'text-cyan-400' },
            { label: 'Ativos', value: ativos, icon: Check, color: 'text-emerald-400' },
            { label: 'Sem estoque', value: semEstoque, icon: BarChart3, color: 'text-rose-400' },
            { label: 'Categorias', value: categorias.length, icon: Tag, color: 'text-purple-400' },
          ].map(s => (
            <div key={s.label} className="bg-slate-900/40 border border-slate-800 rounded-2xl p-4 flex items-center gap-3">
              <s.icon size={20} className={s.color} />
              <div>
                <p className="text-xs font-black text-slate-500 uppercase tracking-widest">{s.label}</p>
                <p className="text-xl font-black text-white tabular-nums">{s.value}</p>
              </div>
            </div>
          ))}
        </div>
      )}

      {(modal === 'new' || modal === 'edit') && (
        <ProdutoModal
          produto={modal === 'edit' ? selected : null}
          categorias={categorias}
          onClose={() => setModal(null)}
          onSave={() => { setModal(null); load(); }}
        />
      )}
      {modal === 'import' && (
        <ImportModal onClose={() => setModal(null)} onDone={load} />
      )}
    </div>
  );
}
