"use client";

import Link from "next/link";
import { useMemo, useState } from "react";

// Inline SVGs if needed, but let's try to keep it clean.
function SearchIcon({ className }: { className?: string }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
      <circle cx="11" cy="11" r="8" />
      <path d="m21 21-4.3-4.3" />
    </svg>
  );
}

type AccessRow = {
  id: string;
  email: string;
  name: string | null;
  status: string | null;
  plan_name: string | null;
  expires_at: string | null;
  created_at: string | null;
};

type ActionState = {
  id: string;
  type: "activate" | "deactivate" | "reset_password" | "set_password";
};

type PasswordDialogState = {
  row: AccessRow;
  password: string;
  confirmPassword: string;
  error: string | null;
};

export default function CompaniesClient({ initialRows }: { initialRows: AccessRow[] }) {
  const [rows, setRows] = useState<AccessRow[]>(initialRows);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState<"all" | "active" | "inactive" | "expired">("all");
  const [actionState, setActionState] = useState<ActionState | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [formMode, setFormMode] = useState<"grant" | "renew">("grant");
  const [formEmail, setFormEmail] = useState("");
  const [formName, setFormName] = useState("");
  const [formPlan, setFormPlan] = useState<"mensal" | "anual" | "custom">("mensal");
  const [formCustomDays, setFormCustomDays] = useState("30");
  const [formPlanName, setFormPlanName] = useState("Ktalogu - Mensal");
  const [formStatus, setFormStatus] = useState<"active" | "inactive">("active");
  const [savingAccess, setSavingAccess] = useState(false);
  const [passwordDialog, setPasswordDialog] = useState<PasswordDialogState | null>(null);

  const now = Date.now();

  const filtered = useMemo(() => {
    const term = search.trim().toLowerCase();
    return rows.filter((row) => {
      const normalizedStatus = (row.status || "active").toLowerCase();
      const expiresAt = row.expires_at ? new Date(row.expires_at).getTime() : null;
      const derivedStatus =
        normalizedStatus !== "active"
          ? "inactive"
          : expiresAt && expiresAt < now
            ? "expired"
            : "active";

      if (statusFilter !== "all" && derivedStatus !== statusFilter) return false;

      if (!term) return true;
      const haystack = [row.name || "", row.email || ""].join(" ").toLowerCase();
      return haystack.includes(term);
    });
  }, [rows, search, statusFilter, now]);

  function planDefaults(plan: "mensal" | "anual" | "custom") {
    if (plan === "anual") return { name: "Ktalogu - Anual", days: 365 };
    if (plan === "custom") return { name: "Ktalogu - Personalizado", days: 30 };
    return { name: "Ktalogu - Mensal", days: 30 };
  }

  function resolveDays() {
    if (formPlan === "custom") {
      const parsed = Number(formCustomDays);
      return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 1;
    }
    return planDefaults(formPlan).days;
  }

  function fillRenewForm(row: AccessRow) {
    setFormMode("renew");
    setFormEmail(row.email);
    setFormName(row.name || "");
    setFormPlan("mensal");
    setFormCustomDays("30");
    setFormPlanName(row.plan_name || "Ktalogu - Mensal");
    setFormStatus("active");
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  function openPasswordDialog(row: AccessRow) {
    setPasswordDialog({
      row,
      password: "",
      confirmPassword: "",
      error: null,
    });
  }

  async function handlePasswordSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!passwordDialog) return;

    if (passwordDialog.password.length < 6) {
      setPasswordDialog((prev) =>
        prev ? { ...prev, error: "A senha deve ter pelo menos 6 caracteres." } : prev
      );
      return;
    }

    if (passwordDialog.password !== passwordDialog.confirmPassword) {
      setPasswordDialog((prev) =>
        prev ? { ...prev, error: "A confirmacao da senha nao confere." } : prev
      );
      return;
    }

    await runAction(passwordDialog.row, "set_password", { password: passwordDialog.password });
  }

  async function runAction(
    row: AccessRow,
    action: ActionState["type"],
    extras?: {
      password?: string;
    }
  ) {
    setMessage(null);
    setActionState({ id: row.id, type: action });
    try {
      const res = await fetch("/api/owner/companies", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          email: row.email,
          action,
          password: extras?.password,
        }),
      });
      const json = (await res.json().catch(() => null)) as { error?: string } | null;
      if (!res.ok) {
        if (action === "set_password") {
          setPasswordDialog((prev) =>
            prev ? { ...prev, error: json?.error || "Nao foi possivel definir a senha." } : prev
          );
        }
        setMessage(json?.error || "Não foi possível executar a ação.");
        return;
      }

      if (action === "activate") {
        setRows((prev) =>
          prev.map((item) => (item.id === row.id ? { ...item, status: "active" } : item))
        );
        setMessage("Empresa ativada.");
      } else if (action === "deactivate") {
        setRows((prev) =>
          prev.map((item) => (item.id === row.id ? { ...item, status: "inactive" } : item))
        );
        setMessage("Empresa desativada.");
      } else if (action === "set_password") {
        setPasswordDialog(null);
        setMessage("Senha definida com sucesso.");
      } else {
        setMessage("Reset de senha enviado.");
      }
    } finally {
      setActionState(null);
    }
  }

  async function handleAccessSubmit(e: React.FormEvent) {
    e.preventDefault();
    setMessage(null);
    setSavingAccess(true);
    try {
      const payload = {
        action: formMode === "grant" ? "grant_access" : "renew_access",
        email: formEmail.trim(),
        name: formName.trim(),
        plan: formPlan,
        plan_name: formPlanName.trim(),
        days: resolveDays(),
        status: formStatus,
      };
      const res = await fetch("/api/owner/companies", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(payload),
      });
      const json = (await res.json().catch(() => null)) as
        | { error?: string; record?: AccessRow }
        | null;
      if (!res.ok) {
        setMessage(json?.error || "Não foi possível salvar o acesso.");
        return;
      }
      if (json?.record) {
        setRows((prev) => {
          const idx = prev.findIndex((row) => row.id === json.record!.id);
          if (idx === -1) return [json.record!, ...prev];
          const next = [...prev];
          next[idx] = json.record!;
          return next;
        });
      }
      setMessage(formMode === "grant" ? "Acesso concedido com sucesso." : "Acesso renovado.");
      setFormMode("grant");
      setFormEmail("");
      setFormName("");
      setFormPlan("mensal");
      setFormCustomDays("30");
      setFormPlanName("Ktalogu - Mensal");
      setFormStatus("active");
    } finally {
      setSavingAccess(false);
    }
  }

  return (
    <div className="min-h-screen bg-slate-50/50 p-6 sm:p-8">
      <div className="mx-auto flex max-w-[1920px] flex-col gap-8">
        
        {/* Header Section */}
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h1 className="text-3xl font-bold text-slate-900 tracking-tight">Empresas</h1>
            <p className="mt-1 text-slate-500">Gerencie acessos, renovações e status das contas.</p>
          </div>
          <Link
            href="/"
            className="inline-flex items-center justify-center rounded-xl bg-white px-4 py-2.5 text-sm font-medium text-slate-700 shadow-sm ring-1 ring-slate-200 transition-all hover:bg-slate-50 hover:text-slate-900 active:scale-95"
          >
            Voltar ao Dashboard
          </Link>
        </div>

        {/* Action Form */}
        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
           <div className="mb-6 flex items-center justify-between">
             <h2 className="text-lg font-semibold text-slate-900">
                {formMode === 'grant' ? 'Conceder Novo Acesso' : 'Renovar Acesso'}
             </h2>
             {message && (
                <span className={`text-sm font-medium ${message.includes('sucesso') || message.includes('ativada') ? 'text-emerald-600' : 'text-blue-600'}`}>
                  {message}
                </span>
             )}
           </div>

           <form onSubmit={handleAccessSubmit} className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
              <div className="flex flex-col gap-1.5">
                <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Ação</label>
                <select
                  value={formMode}
                  onChange={(e) => setFormMode(e.target.value as typeof formMode)}
                  className="block w-full rounded-xl border-0 bg-slate-50 py-2.5 pl-3 pr-10 text-slate-900 ring-1 ring-inset ring-slate-200 focus:ring-2 focus:ring-inset focus:ring-blue-500 sm:text-sm sm:leading-6"
                >
                  <option value="grant">Conceder acesso</option>
                  <option value="renew">Renovar acesso</option>
                </select>
              </div>

              <div className="flex flex-col gap-1.5 xl:col-span-1">
                <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Email</label>
                <input
                  value={formEmail}
                  onChange={(e) => setFormEmail(e.target.value)}
                  className="block w-full rounded-xl border-0 bg-slate-50 py-2.5 px-3 text-slate-900 ring-1 ring-inset ring-slate-200 placeholder:text-slate-400 focus:ring-2 focus:ring-inset focus:ring-blue-500 sm:text-sm sm:leading-6"
                  placeholder="cliente@email.com"
                  required
                />
              </div>

              <div className="flex flex-col gap-1.5 xl:col-span-1">
                <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Empresa</label>
                <input
                  value={formName}
                  onChange={(e) => setFormName(e.target.value)}
                  className="block w-full rounded-xl border-0 bg-slate-50 py-2.5 px-3 text-slate-900 ring-1 ring-inset ring-slate-200 placeholder:text-slate-400 focus:ring-2 focus:ring-inset focus:ring-blue-500 sm:text-sm sm:leading-6"
                  placeholder="Nome da empresa"
                />
              </div>

              <div className="flex flex-col gap-1.5">
                <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Plano</label>
                <select
                  value={formPlan}
                  onChange={(e) => {
                    const nextPlan = e.target.value as typeof formPlan;
                    const defaults = planDefaults(nextPlan);
                    setFormPlan(nextPlan);
                    setFormPlanName(defaults.name);
                    setFormCustomDays(String(defaults.days));
                  }}
                  className="block w-full rounded-xl border-0 bg-slate-50 py-2.5 pl-3 pr-10 text-slate-900 ring-1 ring-inset ring-slate-200 focus:ring-2 focus:ring-inset focus:ring-blue-500 sm:text-sm sm:leading-6"
                >
                  <option value="mensal">Mensal</option>
                  <option value="anual">Anual</option>
                  <option value="custom">Custom</option>
                </select>
              </div>

              <div className="flex flex-col gap-1.5">
                <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Dias</label>
                <input
                  value={formCustomDays}
                  onChange={(e) => setFormCustomDays(e.target.value)}
                  className="block w-full rounded-xl border-0 bg-slate-50 py-2.5 px-3 text-slate-900 ring-1 ring-inset ring-slate-200 placeholder:text-slate-400 focus:ring-2 focus:ring-inset focus:ring-blue-500 sm:text-sm sm:leading-6 disabled:opacity-50"
                  disabled={formPlan !== "custom"}
                />
              </div>

               <div className="flex items-end">
                <button
                  type="submit"
                  disabled={savingAccess}
                  className="w-full rounded-xl bg-blue-600 px-4 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                >
                  {savingAccess ? "Salvando..." : "Salvar Acesso"}
                </button>
              </div>
           </form>
            <p className="mt-4 text-xs text-slate-500">
              Nota: O plano customizado usa o número de dias informado. Mensal = 30 dias, Anual = 365 dias.
            </p>
        </div>

        {/* List Section */}
        <div className="flex flex-col gap-4">
           {/* Filters */}
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center">
             <div className="relative flex-1">
                <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                  <SearchIcon className="text-slate-400" />
                </div>
                <input
                  type="text"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  placeholder="Buscar por empresa ou email..."
                  className="block w-full rounded-xl border-0 bg-white py-2.5 pl-10 pr-4 text-slate-900 ring-1 ring-inset ring-slate-200 placeholder:text-slate-400 focus:ring-2 focus:ring-inset focus:ring-blue-500 sm:text-sm sm:leading-6 shadow-sm"
                />
              </div>
              <div className="sm:w-48">
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value as typeof statusFilter)}
                  className="block w-full rounded-xl border-0 bg-white py-2.5 pl-3 pr-10 text-slate-900 ring-1 ring-inset ring-slate-200 focus:ring-2 focus:ring-inset focus:ring-blue-500 sm:text-sm sm:leading-6 shadow-sm"
                >
                  <option value="all">Todos os status</option>
                  <option value="active">Ativas</option>
                  <option value="inactive">Inativas</option>
                  <option value="expired">Expiradas</option>
                </select>
              </div>
          </div>

          <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
            <div className="overflow-x-auto">
              <table className="min-w-full text-sm">
                <thead>
                  <tr className="border-b border-slate-100 bg-slate-50/50 text-left text-xs uppercase tracking-wider text-slate-500">
                    <th className="px-6 py-4 font-semibold">Empresa / Email</th>
                    <th className="px-6 py-4 font-semibold">Plano</th>
                    <th className="px-6 py-4 font-semibold">Status</th>
                    <th className="px-6 py-4 font-semibold">Expira em</th>
                    <th className="px-6 py-4 text-right font-semibold">Ações</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {filtered.map((row) => {
                    const normalizedStatus = (row.status || "active").toLowerCase();
                    const expiresAt = row.expires_at ? new Date(row.expires_at) : null;
                    const isExpired = expiresAt ? expiresAt.getTime() < now : false;
                    const statusLabel =
                      normalizedStatus !== "active"
                        ? "Inativo"
                        : isExpired
                          ? "Expirado"
                          : "Ativo";
                    const statusStyles =
                      statusLabel === "Ativo"
                        ? "bg-emerald-50 text-emerald-700 ring-emerald-600/20"
                        : statusLabel === "Expirado"
                          ? "bg-amber-50 text-amber-700 ring-amber-600/20"
                          : "bg-slate-100 text-slate-700 ring-slate-600/20";
                    const isBusy = actionState?.id === row.id;

                    return (
                      <tr key={row.id} className="group hover:bg-slate-50/50 transition-colors">
                        <td className="px-6 py-4">
                           {/* Link so no nome, e nao um onClick na linha inteira:
                               a linha tem quatro botoes de acao, e clique de
                               linha engoliria ou competiria com eles. */}
                           <Link href={`/companies/${row.id}`} className="flex flex-col group/link">
                              <span className="font-medium text-slate-900 group-hover/link:text-sky-700 group-hover/link:underline underline-offset-2">
                                {row.name || "Sem nome"}
                              </span>
                              <span className="text-xs text-slate-500">{row.email}</span>
                           </Link>
                        </td>
                        <td className="px-6 py-4 text-slate-600">{row.plan_name || "-"}</td>
                        <td className="px-6 py-4">
                           <span className={`inline-flex items-center rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset ${statusStyles}`}>
                              {statusLabel}
                           </span>
                        </td>
                        <td className="px-6 py-4 text-slate-500">
                          {expiresAt ? expiresAt.toLocaleDateString("pt-BR") : "Sem prazo"}
                        </td>
                        <td className="px-6 py-4 text-right">
                          <div className="flex justify-end gap-2">
                            <button
                              type="button"
                              disabled={isBusy}
                              onClick={() => fillRenewForm(row)}
                              className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                            >
                              Renovar
                            </button>
                            {normalizedStatus === "active" ? (
                              <button
                                type="button"
                                disabled={isBusy}
                                onClick={() => runAction(row, "deactivate")}
                                className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-rose-600 hover:bg-rose-50 disabled:opacity-50"
                              >
                                Desativar
                              </button>
                            ) : (
                              <button
                                type="button"
                                disabled={isBusy}
                                onClick={() => runAction(row, "activate")}
                                className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-emerald-600 hover:bg-emerald-50 disabled:opacity-50"
                              >
                                Ativar
                              </button>
                            )}
                            <button
                              type="button"
                              disabled={isBusy}
                              onClick={() => openPasswordDialog(row)}
                              className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-violet-700 hover:bg-violet-50 disabled:opacity-50"
                            >
                              Definir senha
                            </button>
                            <button
                              type="button"
                              disabled={isBusy}
                              onClick={() => runAction(row, "reset_password")}
                              className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-50 disabled:opacity-50"
                            >
                              Reset
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                  {filtered.length === 0 && (
                    <tr>
                      <td colSpan={5} className="px-6 py-12 text-center text-slate-500">
                        Nenhuma empresa encontrada.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
      {passwordDialog && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/40 p-4 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-2xl border border-slate-200 bg-white p-6 shadow-2xl">
            <div className="mb-5">
              <h3 className="text-lg font-semibold text-slate-900">Definir senha do usuario</h3>
              <p className="mt-1 text-sm text-slate-500">
                Usuario: <span className="font-medium text-slate-700">{passwordDialog.row.email}</span>
              </p>
            </div>

            <form onSubmit={handlePasswordSubmit} className="space-y-4">
              <div className="flex flex-col gap-1.5">
                <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Nova senha</label>
                <input
                  type="password"
                  value={passwordDialog.password}
                  onChange={(e) =>
                    setPasswordDialog((prev) => (prev ? { ...prev, password: e.target.value, error: null } : prev))
                  }
                  className="block w-full rounded-xl border-0 bg-slate-50 px-3 py-2.5 text-slate-900 ring-1 ring-inset ring-slate-200 focus:ring-2 focus:ring-inset focus:ring-blue-500 sm:text-sm"
                  placeholder="Minimo de 6 caracteres"
                  autoFocus
                />
              </div>

              <div className="flex flex-col gap-1.5">
                <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Confirmar senha</label>
                <input
                  type="password"
                  value={passwordDialog.confirmPassword}
                  onChange={(e) =>
                    setPasswordDialog((prev) =>
                      prev ? { ...prev, confirmPassword: e.target.value, error: null } : prev
                    )
                  }
                  className="block w-full rounded-xl border-0 bg-slate-50 px-3 py-2.5 text-slate-900 ring-1 ring-inset ring-slate-200 focus:ring-2 focus:ring-inset focus:ring-blue-500 sm:text-sm"
                  placeholder="Repita a senha"
                />
              </div>

              {passwordDialog.error ? (
                <div className="rounded-xl border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700">
                  {passwordDialog.error}
                </div>
              ) : null}

              <div className="flex items-center justify-end gap-3 pt-2">
                <button
                  type="button"
                  onClick={() => setPasswordDialog(null)}
                  disabled={actionState?.type === "set_password"}
                  className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                >
                  Cancelar
                </button>
                <button
                  type="submit"
                  disabled={actionState?.type === "set_password"}
                  className="rounded-xl bg-violet-600 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-violet-500 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {actionState?.type === "set_password" ? "Salvando..." : "Salvar senha"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
