'use client';

import { useEffect, useState, FormEvent } from 'react';
import Header from '@/components/header';
import Modal from '@/components/modal';
import ServiceListSelect from '@/components/service-list-select';
import CnaeSelect from '@/components/cnae-select';
import api from '@/lib/api';
import { Product } from '@/types';

const BILLING_LABELS: Record<string, string> = {
  monthly: 'Mensal',
  yearly:  'Anual',
  once:    'Avulso',
  hourly:  'Por hora',
};

const EMPTY_FORM = {
  name: '', description: '', serviceListItem: '', cnaeCode: '',
  issAliquota: '', issRetained: false, discrimination: '', contractTemplate: '',
};
const EMPTY_VARIANT = { id: undefined as string | undefined, name: '', price: '', billingCycle: 'monthly', setupFee: '', description: '' };

export default function ProdutosPage() {
  const [items, setItems] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState(EMPTY_FORM);
  const [variants, setVariants] = useState([{ ...EMPTY_VARIANT }]);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [removing, setRemoving] = useState<string | null>(null);
  const [editingId, setEditingId] = useState<string | null>(null);

  function load() {
    setLoading(true);
    api.get('/products').then((r) => setItems(r.data.data ?? r.data)).catch(() => {}).finally(() => setLoading(false));
  }

  useEffect(load, []);

  function openModal() {
    setEditingId(null);
    setForm(EMPTY_FORM);
    setVariants([{ ...EMPTY_VARIANT }]);
    setError('');
    setOpen(true);
  }

  function openEditModal(product: any) {
    setEditingId(product.id);
    setForm({
      name: product.name ?? '',
      description: product.description ?? '',
      serviceListItem: product.serviceListItem ?? '',
      cnaeCode: product.cnaeCode ?? '',
      issAliquota: product.issAliquota != null ? String(product.issAliquota) : '',
      issRetained: !!product.issRetained,
      discrimination: product.discrimination ?? '',
      contractTemplate: product.contractTemplate ?? '',
    });
    const existing = (product.variants ?? []).map((v: any) => ({
      id: v.id as string | undefined,
      name: v.name ?? '',
      price: v.price != null ? String(v.price) : '',
      billingCycle: v.billingCycle ?? 'monthly',
      setupFee: v.setupFee != null ? String(v.setupFee) : '',
      description: v.description ?? '',
    }));
    setVariants(existing.length ? existing : [{ ...EMPTY_VARIANT }]);
    setError('');
    setOpen(true);
  }

  function setF(field: string, value: string | boolean) {
    setForm((p) => ({ ...p, [field]: value }));
  }
  function setVariantField(idx: number, field: string, value: string) {
    setVariants((vs) => vs.map((v, i) => (i === idx ? { ...v, [field]: value } : v)));
  }
  function addVariant() {
    setVariants((vs) => [...vs, { ...EMPTY_VARIANT }]);
  }
  function removeVariant(idx: number) {
    setVariants((vs) => (vs.length > 1 ? vs.filter((_, i) => i !== idx) : vs));
  }

  function onCnaeChange(code: string, suggestedAliquota: number) {
    setForm((p) => ({
      ...p,
      cnaeCode: code,
      // Only auto-fill if the user hasn't entered an aliquota yet
      issAliquota: p.issAliquota === '' && suggestedAliquota > 0
        ? String(suggestedAliquota)
        : p.issAliquota,
    }));
  }

  async function handleRemove(product: Product) {
    const label = product.isUsed ? 'inativar' : 'excluir permanentemente';
    if (!window.confirm(`Deseja ${label} o produto "${product.name}"?`)) return;
    setRemoving(product.id);
    try {
      await api.delete(`/products/${product.id}`);
      load();
    } catch (err: unknown) {
      const e = err as { response?: { data?: { message?: string } } };
      alert(e.response?.data?.message ?? 'Erro ao remover produto');
    } finally {
      setRemoving(null);
    }
  }

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setError('');
    setSaving(true);
    try {
      const payload: any = {
        name: form.name,
        ...(form.description && { description: form.description }),
        ...(form.serviceListItem && { serviceListItem: form.serviceListItem }),
        ...(form.cnaeCode && { cnaeCode: form.cnaeCode }),
        ...(form.issAliquota && { issAliquota: Number(form.issAliquota) }),
        ...(form.discrimination && { discrimination: form.discrimination }),
        ...(form.contractTemplate && { contractTemplate: form.contractTemplate }),
        issRetained: form.issRetained,
        variants: variants.map((v) => ({
          ...(v.id && { id: v.id }),
          name: v.name,
          price: Number(v.price),
          billingCycle: v.billingCycle,
          ...(v.setupFee && { setupFee: Number(v.setupFee) }),
          ...(v.description && { description: v.description }),
        })),
      };
      if (editingId) {
        await api.put(`/products/${editingId}`, payload);
      } else {
        await api.post('/products', payload);
      }
      setOpen(false);
      load();
    } catch (err: any) {
      setError(err.response?.data?.message ?? 'Erro ao salvar produto');
    } finally {
      setSaving(false);
    }
  }

  return (
    <>
      <Header
        title="Produtos & Serviços"
        subtitle="Itens utilizados em propostas e contratos"
        action={<button className="btn-primary" onClick={openModal}>+ Novo produto</button>}
      />

      <div className="bg-white rounded-xl border border-[#EAE4D9] overflow-x-auto">
        {loading ? (
          <p className="p-6 text-sm text-[#0E0F12]/50">Carregando...</p>
        ) : items.length === 0 ? (
          <p className="p-6 text-sm text-[#0E0F12]/50">Nenhum produto cadastrado ainda.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-[#FAF7F2] border-b border-[#EAE4D9]">
              <tr>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Nome</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">CNAE</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">ISS</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Variações</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Preço inicial</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Status</th>
                <th className="px-6 py-3" />
              </tr>
            </thead>
            <tbody className="divide-y divide-[#EAE4D9]">
              {items.map((p) => {
                const firstVariant = (p as any).variants?.[0];
                return (
                  <tr key={p.id} className="hover:bg-[#FAF7F2]">
                    <td className="px-6 py-3 font-medium text-[#0E0F12]">{p.name}</td>
                    <td className="px-6 py-3 text-[#0E0F12]/50 font-mono text-xs">{(p as any).cnaeCode ?? '—'}</td>
                    <td className="px-6 py-3 text-[#0E0F12]/50">
                      {(p as any).issAliquota != null ? `${Number((p as any).issAliquota).toFixed(2)}%` : '—'}
                    </td>
                    <td className="px-6 py-3 text-[#0E0F12]/50">{(p as any).variants?.length ?? 0}</td>
                    <td className="px-6 py-3 text-[#0E0F12]">
                      {firstVariant ? `R$ ${Number(firstVariant.price).toFixed(2)} / ${BILLING_LABELS[firstVariant.billingCycle] ?? firstVariant.billingCycle}` : '—'}
                    </td>
                    <td className="px-6 py-3">
                      <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${p.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-[#EAE4D9] text-[#0E0F12]/60'}`}>
                        {p.status === 'active' ? 'Ativo' : 'Inativo'}
                      </span>
                    </td>
                    <td className="px-6 py-3 text-right whitespace-nowrap">
                      <button
                        onClick={() => openEditModal(p)}
                        className="text-xs font-medium text-[#B7895A] hover:text-[#9a7048] mr-4"
                      >
                        Editar
                      </button>
                      {p.status === 'active' && (
                        <button
                          onClick={() => handleRemove(p)}
                          disabled={removing === p.id}
                          className={`text-xs font-medium ${p.isUsed ? 'text-[#0E0F12]/50 hover:text-[#0E0F12]' : 'text-red-500 hover:text-red-700'} disabled:opacity-40`}
                        >
                          {removing === p.id ? '...' : p.isUsed ? 'Inativar' : 'Excluir'}
                        </button>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>

      <Modal open={open} onClose={() => setOpen(false)} title={editingId ? 'Editar produto' : 'Novo produto'}>
        <form onSubmit={handleSubmit} className="space-y-4">
          {error && <div className="bg-red-50 text-red-700 text-sm px-4 py-3 rounded-lg">{error}</div>}

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Nome do produto / serviço <span className="text-red-500">*</span></label>
            <input className="input" required minLength={2} value={form.name} onChange={(e) => setF('name', e.target.value)} placeholder="Consultoria mensal" />
          </div>

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Descrição</label>
            <textarea className="input resize-none" rows={2} value={form.description} onChange={(e) => setF('description', e.target.value)} placeholder="Descreva o serviço..." />
          </div>

          <div className="border-t border-[#EAE4D9] pt-4">
            <p className="text-xs font-semibold text-[#0E0F12]/40 uppercase tracking-wide mb-3">Configuração fiscal</p>

            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">CNAE</label>
                <CnaeSelect value={form.cnaeCode} onChange={onCnaeChange} />
                {form.cnaeCode && form.issAliquota && (
                  <p className="text-xs text-[#B7895A] mt-1">Alíquota ISS sugerida preenchida automaticamente.</p>
                )}
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Item lista serviços (LC116)</label>
                  <ServiceListSelect value={form.serviceListItem} onChange={(v) => setF('serviceListItem', v)} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Alíquota ISS (%)</label>
                  <input
                    className="input"
                    type="number"
                    min="0"
                    max="100"
                    step="0.01"
                    value={form.issAliquota}
                    onChange={(e) => setF('issAliquota', e.target.value)}
                    placeholder="5.00"
                  />
                </div>
              </div>

              <div>
                <label className="flex items-center gap-2 text-sm text-[#0E0F12] cursor-pointer">
                  <input
                    type="checkbox"
                    className="h-4 w-4 rounded border-[#EAE4D9] accent-[#B7895A]"
                    checked={form.issRetained}
                    onChange={(e) => setF('issRetained', e.target.checked)}
                  />
                  ISS retido pelo tomador
                </label>
              </div>

              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Discriminação padrão (NFS-e)</label>
                <textarea
                  className="input resize-none"
                  rows={2}
                  value={form.discrimination}
                  onChange={(e) => setF('discrimination', e.target.value)}
                  placeholder="Texto padrão para discriminação da nota fiscal..."
                />
              </div>
            </div>
          </div>

          <div className="border-t border-[#EAE4D9] pt-4">
            <p className="text-xs font-semibold text-[#0E0F12]/40 uppercase tracking-wide mb-3">Template do contrato</p>
            <div className="space-y-2">
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">
                Texto do contrato
                <span className="ml-2 text-xs font-normal text-[#0E0F12]/40">(use os mnemônicos abaixo)</span>
              </label>
              <textarea
                className="input resize-y font-mono text-xs"
                rows={8}
                value={form.contractTemplate}
                onChange={(e) => setF('contractTemplate', e.target.value)}
                placeholder="CONTRATO DE PRESTAÇÃO DE SERVIÇOS&#10;&#10;Pelo presente instrumento, {{NOME_PRESTADOR}} (CNPJ: {{CNPJ_PRESTADOR}}) e {{NOME_CLIENTE}} (CNPJ: {{CNPJ_CLIENTE}}) celebram o seguinte contrato..."
              />
              <div className="bg-[#FAF7F2] rounded-lg p-3 text-xs text-[#0E0F12]/60 leading-relaxed">
                <p className="font-semibold text-[#0E0F12]/80 mb-1.5">Mnemônicos disponíveis:</p>
                <div className="grid grid-cols-2 gap-x-4 gap-y-0.5 font-mono">
                  {[
                    '{{CONTRACT_NUMBER}}','{{ISSUE_DATE}}','{{CLIENT_NAME}}','{{CLIENT_DOCUMENT}}',
                    '{{CLIENT_ADDRESS}}','{{CLIENT_EMAIL}}','{{CONTRACT_DURATION}}','{{PRODUCT_NAME}}',
                    '{{BILLING_TYPE}}','{{QUANTITY}}','{{UNIT_PRICE}}','{{TOTAL_PRICE}}',
                    '{{LICENSE_TOTAL}}','{{BILLING_CYCLE}}','{{ADJUSTMENT_INDEX}}',
                  ].map((m) => (
                    <button
                      key={m}
                      type="button"
                      onClick={() => setF('contractTemplate', form.contractTemplate + m)}
                      className="text-left text-[#B7895A] hover:text-[#9a7048] transition-colors"
                    >
                      {m}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </div>

          <div className="border-t border-[#EAE4D9] pt-4">
            <div className="flex items-center justify-between mb-3">
              <p className="text-xs font-semibold text-[#0E0F12]/40 uppercase tracking-wide">Variações / Planos</p>
              <button type="button" onClick={addVariant} className="text-xs font-medium text-[#B7895A] hover:text-[#9a7048]">
                + Adicionar variação
              </button>
            </div>

            <div className="space-y-4">
              {variants.map((v, idx) => (
                <div key={idx} className="bg-[#FAF7F2] rounded-lg p-4 border border-[#EAE4D9]">
                  <div className="flex items-start gap-3">
                    <div className="flex-1">
                      <label className="block text-sm font-medium text-[#0E0F12] mb-1">Nome do plano <span className="text-red-500">*</span></label>
                      <input className="input" required minLength={2} value={v.name} onChange={(e) => setVariantField(idx, 'name', e.target.value)} placeholder="Plano Básico" />
                    </div>
                    {variants.length > 1 && (
                      <button
                        type="button"
                        onClick={() => removeVariant(idx)}
                        className="mt-6 text-xs font-medium text-red-500 hover:text-red-700"
                      >
                        Remover
                      </button>
                    )}
                  </div>

                  <div className="grid grid-cols-2 gap-3 mt-3">
                    <div>
                      <label className="block text-sm font-medium text-[#0E0F12] mb-1">Preço (R$) <span className="text-red-500">*</span></label>
                      <input className="input" type="number" required min="0" step="0.01" value={v.price} onChange={(e) => setVariantField(idx, 'price', e.target.value)} placeholder="90.00" />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-[#0E0F12] mb-1">Ciclo de cobrança</label>
                      <select className="input" value={v.billingCycle} onChange={(e) => setVariantField(idx, 'billingCycle', e.target.value)}>
                        <option value="monthly">Mensal</option>
                        <option value="yearly">Anual</option>
                        <option value="once">Avulso</option>
                        <option value="hourly">Por hora</option>
                      </select>
                    </div>
                  </div>

                  <div className="mt-3">
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">Descrição do plano</label>
                    <input
                      className="input"
                      value={v.description}
                      onChange={(e) => setVariantField(idx, 'description', e.target.value)}
                      placeholder="ex: 1 empresa, 1 usuário"
                    />
                  </div>

                  <div className="mt-3">
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">Taxa de setup (R$)</label>
                    <input className="input" type="number" min="0" step="0.01" value={v.setupFee} onChange={(e) => setVariantField(idx, 'setupFee', e.target.value)} placeholder="0.00" />
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="flex justify-end gap-3 pt-2">
            <button type="button" className="btn-secondary" onClick={() => setOpen(false)}>Cancelar</button>
            <button type="submit" className="btn-primary" disabled={saving}>
              {saving ? 'Salvando...' : editingId ? 'Salvar alterações' : 'Salvar produto'}
            </button>
          </div>
        </form>
      </Modal>
    </>
  );
}
