'use client';
import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';

import { API_BASE_URL } from '@/lib/api';

interface TenantRow {
  id: string;
  name: string;
  document: string;
  email: string;
  plan: string;
  status: string;
  userCount: number;
  ownerEmail: string;
  createdAt: string;
}

const EMPTY_FORM = {
  tenantName: '',
  tenantDocument: '',
  tenantEmail: '',
  userName: '',
  userEmail: '',
  userPassword: '',
};

const PLAN_LABEL: Record<string, string> = {
  trial: 'Trial',
  basic: 'Básico',
  pro: 'Pro',
  enterprise: 'Enterprise',
};

const STATUS_COLOR: Record<string, string> = {
  active: 'bg-green-100 text-green-700',
  suspended: 'bg-yellow-100 text-yellow-700',
  cancelled: 'bg-red-100 text-red-700',
};

function formatDoc(doc: string) {
  if (doc?.length === 14) return doc.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, '$1.$2.$3/$4-$5');
  return doc;
}

export default function AdminPage() {
  const router = useRouter();
  const [token, setToken] = useState<string | null>(null);
  const [tenants, setTenants] = useState<TenantRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [form, setForm] = useState(EMPTY_FORM);
  const [saving, setSaving] = useState(false);
  const [formError, setFormError] = useState('');
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [deleting, setDeleting] = useState(false);
  const [success, setSuccess] = useState('');

  useEffect(() => {
    const t = localStorage.getItem('klavo_admin_token');
    if (!t) { router.replace('/admin/login'); return; }
    setToken(t);
  }, [router]);

  const load = useCallback(async (t: string) => {
    setLoading(true);
    try {
      const res = await fetch(`${API_BASE_URL}/admin/tenants`, {
        headers: { Authorization: `Bearer ${t}` },
      });
      if (res.status === 401) { localStorage.removeItem('klavo_admin_token'); router.replace('/admin/login'); return; }
      setTenants(await res.json());
    } finally {
      setLoading(false);
    }
  }, [router]);

  useEffect(() => { if (token) load(token); }, [token, load]);

  function logout() {
    localStorage.removeItem('klavo_admin_token');
    router.replace('/admin/login');
  }

  async function handleProvision(e: React.FormEvent) {
    e.preventDefault();
    setFormError('');
    setSaving(true);
    try {
      const res = await fetch(`${API_BASE_URL}/admin/tenants`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(Array.isArray(data.message) ? data.message.join(', ') : data.message);
      setShowModal(false);
      setForm(EMPTY_FORM);
      setSuccess(`Empresa "${data.tenant.name}" criada com sucesso. Acesso: ${data.userEmail}`);
      setTimeout(() => setSuccess(''), 6000);
      load(token!);
    } catch (err: any) {
      setFormError(err.message);
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete(id: string) {
    setDeleting(true);
    try {
      const res = await fetch(`${API_BASE_URL}/admin/tenants/${id}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) {
        const d = await res.json();
        throw new Error(d.message);
      }
      setDeleteId(null);
      load(token!);
    } catch (err: any) {
      alert(err.message);
    } finally {
      setDeleting(false);
    }
  }

  if (!token) return null;

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 rounded-lg bg-indigo-600 text-white flex items-center justify-center font-bold text-sm">K</div>
          <div>
            <span className="font-semibold text-gray-900">Klavo Admin</span>
            <span className="ml-2 text-xs bg-indigo-100 text-indigo-700 px-2 py-0.5 rounded-full">Plataforma</span>
          </div>
        </div>
        <button onClick={logout} className="text-sm text-gray-500 hover:text-gray-900 transition">Sair</button>
      </header>

      <main className="max-w-6xl mx-auto px-6 py-8 space-y-6">
        {/* Stats + action */}
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-semibold text-gray-900">Empresas cadastradas</h2>
            <p className="text-sm text-gray-500">{tenants.length} empresa{tenants.length !== 1 ? 's' : ''} na plataforma</p>
          </div>
          <button
            onClick={() => { setShowModal(true); setForm(EMPTY_FORM); setFormError(''); }}
            className="bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-medium px-4 py-2 rounded-lg transition"
          >
            + Nova empresa
          </button>
        </div>

        {success && (
          <div className="bg-green-50 border border-green-200 text-green-800 text-sm px-4 py-3 rounded-lg">{success}</div>
        )}

        {/* Table */}
        <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
          {loading ? (
            <div className="p-12 text-center text-sm text-gray-400">Carregando...</div>
          ) : tenants.length === 0 ? (
            <div className="p-12 text-center text-sm text-gray-400">Nenhuma empresa cadastrada.</div>
          ) : (
            <table className="w-full text-sm">
              <thead className="bg-gray-50 border-b border-gray-200">
                <tr>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Empresa</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">CNPJ</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Responsável</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Plano</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Status</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Criado em</th>
                  <th className="px-4 py-3"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {tenants.map(t => (
                  <tr key={t.id} className="hover:bg-gray-50 transition">
                    <td className="px-4 py-3">
                      <div className="font-medium text-gray-900">{t.name}</div>
                      <div className="text-xs text-gray-400">{t.email}</div>
                    </td>
                    <td className="px-4 py-3 text-gray-600 font-mono text-xs">{formatDoc(t.document)}</td>
                    <td className="px-4 py-3">
                      <div className="text-gray-700">{t.ownerEmail || '—'}</div>
                      <div className="text-xs text-gray-400">{t.userCount} usuário{t.userCount !== 1 ? 's' : ''}</div>
                    </td>
                    <td className="px-4 py-3">
                      <span className="bg-gray-100 text-gray-700 text-xs px-2 py-0.5 rounded-full">{PLAN_LABEL[t.plan] ?? t.plan}</span>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${STATUS_COLOR[t.status] ?? 'bg-gray-100 text-gray-600'}`}>
                        {t.status === 'active' ? 'Ativo' : t.status === 'suspended' ? 'Suspenso' : 'Cancelado'}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-gray-500 text-xs">
                      {new Date(t.createdAt).toLocaleDateString('pt-BR')}
                    </td>
                    <td className="px-4 py-3 text-right">
                      <button
                        onClick={() => setDeleteId(t.id)}
                        className="text-xs text-red-500 hover:text-red-700 transition"
                      >
                        Excluir
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </main>

      {/* Modal: nova empresa */}
      {showModal && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-lg">
            <div className="px-6 pt-6 pb-4 border-b border-gray-100">
              <h3 className="font-semibold text-gray-900 text-base">Nova empresa</h3>
              <p className="text-sm text-gray-500 mt-0.5">Provisiona a empresa e o usuário administrador</p>
            </div>
            <form onSubmit={handleProvision}>
              <div className="px-6 py-5 space-y-5">
                {/* Empresa */}
                <div>
                  <p className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3">Dados da empresa</p>
                  <div className="space-y-3">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Razão social</label>
                      <input
                        value={form.tenantName}
                        onChange={e => setForm(f => ({ ...f, tenantName: e.target.value }))}
                        className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                        placeholder="Empresa XYZ Ltda"
                        required
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">CNPJ</label>
                        <input
                          value={form.tenantDocument}
                          onChange={e => setForm(f => ({ ...f, tenantDocument: e.target.value.replace(/\D/g, '') }))}
                          className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                          placeholder="00000000000000"
                          maxLength={14}
                          required
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">E-mail da empresa</label>
                        <input
                          type="email"
                          value={form.tenantEmail}
                          onChange={e => setForm(f => ({ ...f, tenantEmail: e.target.value }))}
                          className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                          placeholder="contato@empresa.com"
                          required
                        />
                      </div>
                    </div>
                  </div>
                </div>

                {/* Usuário */}
                <div>
                  <p className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3">Usuário administrador</p>
                  <div className="space-y-3">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Nome completo</label>
                      <input
                        value={form.userName}
                        onChange={e => setForm(f => ({ ...f, userName: e.target.value }))}
                        className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                        placeholder="João Silva"
                        required
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">E-mail de acesso</label>
                        <input
                          type="email"
                          value={form.userEmail}
                          onChange={e => setForm(f => ({ ...f, userEmail: e.target.value }))}
                          className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                          placeholder="joao@empresa.com"
                          required
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Senha inicial</label>
                        <input
                          type="password"
                          value={form.userPassword}
                          onChange={e => setForm(f => ({ ...f, userPassword: e.target.value }))}
                          className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                          placeholder="mínimo 6 caracteres"
                          minLength={6}
                          required
                        />
                      </div>
                    </div>
                  </div>
                </div>

                {formError && (
                  <p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2">{formError}</p>
                )}
              </div>

              <div className="px-6 py-4 border-t border-gray-100 flex justify-end gap-3">
                <button
                  type="button"
                  onClick={() => setShowModal(false)}
                  className="px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition"
                >
                  Cancelar
                </button>
                <button
                  type="submit"
                  disabled={saving}
                  className="bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-medium px-5 py-2 rounded-lg transition disabled:opacity-50"
                >
                  {saving ? 'Criando...' : 'Criar empresa'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Modal: confirmar exclusão */}
      {deleteId && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 space-y-4">
            <div className="space-y-1">
              <h3 className="font-semibold text-gray-900">Excluir empresa</h3>
              <p className="text-sm text-gray-500">
                Esta ação é <strong>irreversível</strong>. Todos os dados da empresa serão permanentemente excluídos.
              </p>
            </div>
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => setDeleteId(null)}
                className="px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition"
              >
                Cancelar
              </button>
              <button
                onClick={() => handleDelete(deleteId)}
                disabled={deleting}
                className="bg-red-600 hover:bg-red-700 text-white text-sm font-medium px-4 py-2 rounded-lg transition disabled:opacity-50"
              >
                {deleting ? 'Excluindo...' : 'Excluir permanentemente'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
