'use client';

import { useEffect, useState, FormEvent } from 'react';
import Header from '@/components/header';
import Modal from '@/components/modal';
import api from '@/lib/api';

interface License {
  id: string;
  licenseName: string;
  licenseKey: string;
  status: string;
  createdAt: string;
  provisionedTenantId?: string;
}

interface Client {
  id: string;
  name: string;
  document: string;
  email: string | null;
  emailCommercial: string | null;
  emailNf: string | null;
}

interface ProductVariant {
  id: string;
  name: string;
  price: number;
  description?: string;
}

interface Product {
  id: string;
  name: string;
  variants?: ProductVariant[];
}

interface Contract {
  id: string;
  number: string;
  title: string | null;
  status: string;
}

interface ProvisionedAccess {
  licenseName: string;
  email: string;
  password: string;
  companyName: string;
}

const STATUS_COLORS: Record<string, string> = {
  active:    'bg-green-100 text-green-700',
  suspended: 'bg-yellow-100 text-yellow-700',
  revoked:   'bg-red-100 text-red-700',
  expired:   'bg-[#EAE4D9] text-[#0E0F12]/60',
};

const BILLING_METRICS = [
  { value: 'fixed',        label: 'Fixo' },
  { value: 'per_call',     label: 'Por chamada' },
  { value: 'per_endpoint', label: 'Por endpoint' },
];

const EMPTY_FORM = {
  clientId: '',
  productId: '',
  productVariantId: '',
  contractId: '',
  licenseName: '',
  description: '',
  expiresAt: '',
  billingMetric: 'fixed',
  unitPrice: '',
  companyName: '',
  companyDocument: '',
  companyEmail: '',
  operatorName: '',
  operatorEmail: '',
  operatorPassword: '',
};

export default function SaasPage() {
  const [items, setItems] = useState<License[]>([]);
  const [loading, setLoading] = useState(true);

  const [modalOpen, setModalOpen] = useState(false);
  const [successModal, setSuccessModal] = useState(false);
  const [provisioned, setProvisioned] = useState<ProvisionedAccess | null>(null);

  const [clients, setClients] = useState<Client[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [contracts, setContracts] = useState<Contract[]>([]);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const [form, setForm] = useState(EMPTY_FORM);

  function loadLicenses() {
    api.get('/saas/licenses')
      .then((r) => setItems(r.data.data ?? r.data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }

  useEffect(() => { loadLicenses(); }, []);

  function openModal() {
    setError('');
    setForm(EMPTY_FORM);
    setContracts([]);
    Promise.all([
      api.get('/clients').then((r) => setClients(r.data.data ?? r.data)),
      api.get('/products').then((r) => setProducts(r.data.data ?? r.data)),
    ]).catch(() => {});
    setModalOpen(true);
  }

  function handleClientChange(clientId: string) {
    const client = clients.find((c) => c.id === clientId);
    setContracts([]);
    setForm((f) => ({ ...f, clientId, contractId: '' }));
    if (!client) return;
    const email = client.emailCommercial ?? client.email ?? client.emailNf ?? '';
    setForm((f) => {
      // Se já tem produto/variação escolhidos, re-deriva o nome da licença com o novo cliente.
      const product = products.find((p) => p.id === f.productId);
      const variant = product?.variants?.find((v) => v.id === f.productVariantId);
      const licenseName = product
        ? [variant?.name ?? product.name, client.name].filter(Boolean).join(' — ')
        : f.licenseName;
      return {
        ...f,
        clientId,
        contractId: '',
        companyName: client.name,
        companyDocument: client.document ?? '',
        companyEmail: email,
        licenseName,
      };
    });
    api.get(`/contracts?clientId=${clientId}&status=active`)
      .then((r) => setContracts(r.data.data ?? r.data))
      .catch(() => {});
  }

  function applyVariant(variant: ProductVariant | undefined, product: Product, companyName: string) {
    setForm((f) => ({
      ...f,
      productVariantId: variant?.id ?? '',
      licenseName: [variant?.name ?? product.name, companyName].filter(Boolean).join(' — '),
      unitPrice: variant ? String(variant.price) : f.unitPrice,
      description: variant?.description ?? f.description,
    }));
  }

  function handleProductChange(productId: string) {
    const product = products.find((p) => p.id === productId);
    setForm((f) => ({ ...f, productId, productVariantId: '' }));
    if (!product) return;
    applyVariant(product.variants?.[0], product, form.companyName);
  }

  function handleVariantChange(variantId: string) {
    const product = products.find((p) => p.id === form.productId);
    if (!product) return;
    const variant = product.variants?.find((v) => v.id === variantId);
    applyVariant(variant, product, form.companyName);
  }

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setError('');
    setSaving(true);
    try {
      const payload: Record<string, unknown> = {
        clientId: form.clientId,
        productId: form.productId,
        licenseName: form.licenseName,
        companyName: form.companyName,
        companyDocument: form.companyDocument,
        companyEmail: form.companyEmail,
        operatorName: form.operatorName,
        operatorEmail: form.operatorEmail,
        operatorPassword: form.operatorPassword,
      };
      if (form.contractId) payload.contractId = form.contractId;
      if (form.description) payload.description = form.description;
      if (form.expiresAt) payload.expiresAt = form.expiresAt;
      if (form.billingMetric !== 'fixed') payload.billingMetric = form.billingMetric;
      if (form.unitPrice) payload.unitPrice = parseFloat(form.unitPrice);

      await api.post('/saas/licenses', payload);

      setModalOpen(false);
      setLoading(true);
      loadLicenses();

      setProvisioned({
        licenseName: form.licenseName,
        email: form.operatorEmail,
        password: form.operatorPassword,
        companyName: form.companyName,
      });
      setSuccessModal(true);
    } catch (err: any) {
      const msg = err?.response?.data?.message;
      setError(Array.isArray(msg) ? msg.join(', ') : (msg ?? 'Erro ao criar licença'));
    } finally {
      setSaving(false);
    }
  }

  return (
    <>
      <Header
        title="Gestão SaaS"
        subtitle="Licenças e acesso à plataforma para clientes"
        action={<button className="btn-primary" onClick={openModal}>+ Nova licença</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">Nenhuma licença criada 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">Empresa</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Chave (prefixo)</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Status</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Criado em</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#EAE4D9]">
              {items.map((l) => (
                <tr key={l.id} className="hover:bg-[#FAF7F2]">
                  <td className="px-6 py-3 font-medium text-[#0E0F12]">{l.licenseName}</td>
                  <td className="px-6 py-3 font-mono text-[#0E0F12]/50 text-xs">{l.licenseKey.slice(0, 12)}…</td>
                  <td className="px-6 py-3">
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${STATUS_COLORS[l.status] ?? 'bg-[#EAE4D9] text-[#0E0F12]/60'}`}>{l.status}</span>
                  </td>
                  <td className="px-6 py-3 text-[#0E0F12]/50">{new Date(l.createdAt).toLocaleDateString('pt-BR')}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {/* Modal: criar licença + provisionar acesso */}
      <Modal open={modalOpen} onClose={() => setModalOpen(false)} title="Nova licença — Provisionar acesso" wide>
        <form onSubmit={handleSubmit} className="space-y-5">

          {/* Seção: empresa licenciada */}
          <div>
            <p className="text-xs font-semibold text-[#0E0F12]/40 uppercase tracking-wide mb-3">Empresa que vai usar o Klavo</p>
            <div className="space-y-3">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Razão social *</label>
                  <input className="input w-full" required minLength={2} placeholder="Empresa Exemplo Ltda"
                    value={form.companyName} onChange={(e) => setForm({ ...form, companyName: e.target.value })} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">CNPJ *</label>
                  <input className="input w-full" required minLength={14} placeholder="00.000.000/0001-00"
                    value={form.companyDocument} onChange={(e) => setForm({ ...form, companyDocument: e.target.value })} />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">E-mail corporativo *</label>
                <input className="input w-full" required type="email" placeholder="contato@empresa.com.br"
                  value={form.companyEmail} onChange={(e) => setForm({ ...form, companyEmail: e.target.value })} />
              </div>
            </div>
          </div>

          {/* Seção: operador */}
          <div className="border-t border-[#EAE4D9] pt-4">
            <p className="text-xs font-semibold text-[#0E0F12]/40 uppercase tracking-wide mb-3">Operador / Responsável pelo acesso</p>
            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Nome completo *</label>
                <input className="input w-full" required minLength={2} placeholder="João da Silva"
                  value={form.operatorName} onChange={(e) => setForm({ ...form, operatorName: e.target.value })} />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">E-mail de acesso *</label>
                  <input className="input w-full" required type="email" placeholder="joao@empresa.com.br"
                    value={form.operatorEmail} onChange={(e) => setForm({ ...form, operatorEmail: e.target.value })} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Senha inicial *</label>
                  <input className="input w-full" required minLength={8} type="password" placeholder="mín. 8 caracteres"
                    value={form.operatorPassword} onChange={(e) => setForm({ ...form, operatorPassword: e.target.value })} />
                </div>
              </div>
            </div>
          </div>

          {/* Seção: licença */}
          <div className="border-t border-[#EAE4D9] pt-4">
            <p className="text-xs font-semibold text-[#0E0F12]/40 uppercase tracking-wide mb-3">Licença</p>
            <div className="space-y-3">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Cliente vinculado *</label>
                  <select className="input w-full" required value={form.clientId}
                    onChange={(e) => handleClientChange(e.target.value)}>
                    <option value="">Selecione</option>
                    {clients.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Produto / plano *</label>
                  <select className="input w-full" required value={form.productId}
                    onChange={(e) => handleProductChange(e.target.value)}>
                    <option value="">Selecione</option>
                    {products.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
                  </select>
                </div>
              </div>
              {(products.find((p) => p.id === form.productId)?.variants?.length ?? 0) >= 2 && (
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Variação / Plano</label>
                  <select className="input w-full" value={form.productVariantId}
                    onChange={(e) => handleVariantChange(e.target.value)}>
                    {products.find((p) => p.id === form.productId)?.variants?.map((v) => (
                      <option key={v.id} value={v.id}>{v.name} — R$ {Number(v.price).toFixed(2)}</option>
                    ))}
                  </select>
                </div>
              )}
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">
                  Contrato vinculado
                  <span className="ml-1 font-normal text-[#0E0F12]/40 text-xs">(opcional)</span>
                </label>
                <select
                  className="input w-full"
                  value={form.contractId}
                  onChange={(e) => setForm({ ...form, contractId: e.target.value })}
                  disabled={!form.clientId}
                >
                  <option value="">
                    {!form.clientId ? 'Selecione o cliente primeiro' : contracts.length === 0 ? 'Nenhum contrato ativo' : 'Sem vínculo'}
                  </option>
                  {contracts.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.number}{c.title ? ` — ${c.title}` : ''}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Nome da licença *</label>
                <input className="input w-full" required minLength={2} placeholder="Klavo — Empresa Exemplo"
                  value={form.licenseName} onChange={(e) => setForm({ ...form, licenseName: e.target.value })} />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Métrica de cobrança</label>
                  <select className="input w-full" value={form.billingMetric}
                    onChange={(e) => setForm({ ...form, billingMetric: e.target.value })}>
                    {BILLING_METRICS.map((m) => <option key={m.value} value={m.value}>{m.label}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Expiração</label>
                  <input className="input w-full" type="date" value={form.expiresAt}
                    onChange={(e) => setForm({ ...form, expiresAt: e.target.value })} />
                </div>
              </div>
            </div>
          </div>

          {error && <p className="text-sm text-red-600">{error}</p>}

          <div className="flex justify-end gap-3 pt-2">
            <button type="button" className="btn-secondary" onClick={() => setModalOpen(false)}>Cancelar</button>
            <button type="submit" className="btn-primary" disabled={saving}>
              {saving ? 'Provisionando…' : 'Criar licença e provisionar acesso'}
            </button>
          </div>
        </form>
      </Modal>

      {/* Modal: credenciais geradas */}
      <Modal open={successModal} onClose={() => setSuccessModal(false)} title="Acesso provisionado com sucesso">
        {provisioned && (
          <div className="space-y-4">
            <div className="bg-green-50 border border-green-200 rounded-lg px-4 py-3 text-sm text-green-800">
              A conta da empresa <strong>{provisioned.companyName}</strong> foi criada e o operador já pode acessar a plataforma.
            </div>
            <div className="bg-[#FAF7F2] rounded-lg p-4 space-y-2 text-sm border border-[#EAE4D9]">
              <p className="font-semibold text-[#0E0F12] mb-2">Credenciais de acesso</p>
              <div className="flex justify-between">
                <span className="text-[#0E0F12]/50">URL</span>
                <span className="font-mono text-[#0E0F12]">http://localhost:3001</span>
              </div>
              <div className="flex justify-between">
                <span className="text-[#0E0F12]/50">E-mail</span>
                <span className="font-mono text-[#0E0F12]">{provisioned.email}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-[#0E0F12]/50">Senha</span>
                <span className="font-mono text-[#0E0F12]">{provisioned.password}</span>
              </div>
            </div>
            <p className="text-xs text-[#0E0F12]/40">Guarde e repasse estas credenciais ao operador. A senha não poderá ser recuperada aqui.</p>
            <div className="flex justify-end pt-1">
              <button className="btn-primary" onClick={() => setSuccessModal(false)}>Fechar</button>
            </div>
          </div>
        )}
      </Modal>
    </>
  );
}
