"use client";
import { FormEvent, useMemo, useState } from "react";
import Link from "next/link";
type Row = Record<string, unknown>;
type Props = {
  data: Row | null;
  onCreate: (e: FormEvent<HTMLFormElement>) => void | Promise<void>;
  onUpdate: (id: number, e: FormEvent<HTMLFormElement>) => void | Promise<void>;
  onSaveNotary: (
    id: number | null,
    e: FormEvent<HTMLFormElement>,
  ) => void | Promise<void>;
  onSaveCatalogEntity: (
    id: number,
    e: FormEvent<HTMLFormElement>,
  ) => boolean | void | Promise<boolean | void>;
  onRotateCredential: (
    id: number,
    e: FormEvent<HTMLFormElement>,
  ) => void | Promise<void>;
  onDeleteCredential: (id: number, p: string) => void | Promise<void>;
  onTestGesnot: (id: number) => void | Promise<void>;
  onResetMfa: (id: number) => void | Promise<void>;
};
const rutFormat = (v: string) => {
  const c = v.replace(/[^0-9kK]/g, "").toUpperCase();
  return c.length < 2
    ? c
    : `${c.slice(0, -1).replace(/\B(?=(\d{3})+(?!\d))/g, ".")}-${c.slice(-1)}`;
};
function Modal({
  title,
  onClose,
  children,
}: {
  title: string;
  onClose: () => void;
  children: React.ReactNode;
}) {
  return (
    <div
      className="admin-modal-backdrop"
      onMouseDown={(e) => e.target === e.currentTarget && onClose()}
    >
      <section className="admin-modal">
        <header>
          <h2>{title}</h2>
          <button className="modal-close" onClick={onClose}>
            ×
          </button>
        </header>
        <div className="admin-modal-content">{children}</div>
      </section>
    </div>
  );
}

function LocationFields({
  communes,
  initialCommuneId,
}: {
  communes: Row[];
  initialCommuneId?: unknown;
}) {
  const initial = communes.find((item) => Number(item.id) === Number(initialCommuneId));
  const [regionId, setRegionId] = useState(String(initial?.region_id || ""));
  const [communeId, setCommuneId] = useState(String(initial?.id || ""));
  const regions = useMemo(() => {
    const unique = new Map<string, string>();
    communes.forEach((item) => unique.set(String(item.region_id), String(item.region)));
    return [...unique.entries()];
  }, [communes]);
  const availableCommunes = communes.filter(
    (item) => !regionId || String(item.region_id) === regionId,
  );
  return (
    <div className="form-pair">
      <label>
        Región
        <select
          value={regionId}
          onChange={(event) => {
            const nextRegion = event.currentTarget.value;
            const first = communes.find((item) => String(item.region_id) === nextRegion);
            setRegionId(nextRegion);
            setCommuneId(first ? String(first.id) : "");
          }}
          required
        >
          <option value="">Seleccionar región</option>
          {regions.map(([id, name]) => (
            <option key={id} value={id}>{name}</option>
          ))}
        </select>
      </label>
      <label>
        Comuna
        <select
          name="comuna_id"
          value={communeId}
          onChange={(event) => setCommuneId(event.currentTarget.value)}
          required
        >
          <option value="">Seleccionar comuna</option>
          {availableCommunes.map((item) => (
            <option key={String(item.id)} value={String(item.id)}>
              {String(item.comuna)}
            </option>
          ))}
        </select>
      </label>
    </div>
  );
}
function CredentialCard({
  provider,
  notary,
  existing,
  onSave,
  onDelete,
  onTest,
}: {
  provider: "GESNOT" | "WEBPAY" | "KLAP" | "GETNET";
  notary: Row;
  existing?: Row;
  onSave: Props["onRotateCredential"];
  onDelete: Props["onDeleteCredential"];
  onTest: Props["onTestGesnot"];
}) {
  const [editing, setEditing] = useState(!existing),
    [busy, setBusy] = useState(false);
  async function save(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setBusy(true);
    try {
      await onSave(Number(notary.id), e);
      setEditing(false);
    } finally {
      setBusy(false);
    }
  }
  async function remove() {
    if (!confirm(`¿Eliminar la credencial ${provider}?`)) return;
    setBusy(true);
    try {
      await onDelete(Number(notary.id), provider);
      setEditing(true);
    } finally {
      setBusy(false);
    }
  }
  return (
    <article className="credential-provider-card">
      <div className="card-heading">
        <div>
          <span className="section-kicker">{provider}</span>
          <h3>{existing ? "Credencial configurada" : "Sin configurar"}</h3>
          <p className="muted-copy">
            {existing
              ? `${existing.ambiente} · versión ${existing.version || "actual"}`
              : "Solo se permite una credencial activa."}
          </p>
        </div>
        {existing && !editing && (
          <span className="status-pill status-realizado">Activa</span>
        )}
      </div>
      {existing && !editing ? (
        <div className="wizard-actions">
          <button
            className="button button-secondary"
            onClick={() => setEditing(true)}
          >
            Editar / reemplazar
          </button>
          {provider === "GESNOT" && (
            <button
              className="button button-secondary"
              onClick={() => void onTest(Number(notary.id))}
            >
              Probar
            </button>
          )}
          <button
            className="button button-danger"
            disabled={busy}
            onClick={() => void remove()}
          >
            {busy ? "Eliminando…" : "Eliminar"}
          </button>
        </div>
      ) : (
        <form className="profile-form" onSubmit={save}>
          <input name="proveedor" type="hidden" value={provider} />
          <label>
            Ambiente
            <select
              name="ambiente"
              defaultValue={String(existing?.ambiente || "INTEGRACION")}
            >
              <option value="INTEGRACION">Integración</option>
              <option value="PRODUCCION">Producción</option>
            </select>
          </label>
          <label>
            {provider === "GESNOT" ? "keyCliente" : "API Key / secreto Webpay"}
            <input name="secreto" type="password" minLength={8} required />
          </label>
          <label>
            {provider === "GESNOT" ? "ID notaría GesNot" : "Código de comercio"}
            <input
              name="identificador_publico"
              defaultValue={String(existing?.identificador_publico || "")}
              required
            />
          </label>
          <label>
            Endpoint base
            <input
              name="endpoint_base"
              type="url"
              defaultValue={String(
                existing?.endpoint_base ||
                  (provider === "GESNOT"
                    ? "https://api.gesnot.cl/ot"
                    : "https://webpay3gint.transbank.cl"),
              )}
            />
          </label>
          <input name="fingerprint" type="hidden" />
          <label>
            Motivo
            <input name="motivo" minLength={5} required />
          </label>
          <div className="wizard-actions">
            {existing && (
              <button
                type="button"
                className="button button-secondary"
                onClick={() => setEditing(false)}
              >
                Cancelar
              </button>
            )}
            <button className="button button-primary" disabled={busy}>
              {busy ? "Cifrando y guardando…" : "Guardar credencial"}
            </button>
          </div>
        </form>
      )}
    </article>
  );
}
export default function AdminManagement(p: Props) {
  const {
      data,
      onCreate,
      onUpdate,
      onSaveNotary,
      onSaveCatalogEntity,
      onRotateCredential,
      onDeleteCredential,
      onTestGesnot,
      onResetMfa,
    } = p,
    [tab, setTab] = useState<"users" | "entities" | "catalog">("users"),
    [query, setQuery] = useState(""),
    [page, setPage] = useState(1),
    [userModal, setUserModal] = useState<Row | null | false>(false),
    [notaryModal, setNotaryModal] = useState<Row | null | false>(false),
    [catalogModal, setCatalogModal] = useState<Row | null | false>(false),
    [credential, setCredential] = useState<Row | null>(null),
    [busy, setBusy] = useState(false);
  const users = (data?.users || []) as Row[],
    notaries = (data?.entidades || data?.notarias || []) as Row[],
    catalogEntities = (data?.catastro_publico || []) as Row[],
    communes = (data?.comunas || []) as Row[],
    credentials = (data?.credenciales || []) as Row[],
    capabilityCatalog = (data?.capacidades_entidad || [
      { codigo: "NOTARIA", nombre: "Notaría" },
      { codigo: "CONSERVADOR", nombre: "Conservador" },
      { codigo: "ARCHIVERO", nombre: "Archivero judicial" },
    ]) as Row[],
    sourceCatalog = data?.catalogo_entidades as Row | undefined,
    source = tab === "users" ? users : tab === "entities" ? notaries : catalogEntities,
    filtered = useMemo(
      () =>
        source.filter(
          (r) =>
            !query ||
            Object.values(r).some((v) =>
              String(v ?? "")
                .toLowerCase()
                .includes(query.toLowerCase()),
            ),
        ),
      [source, query],
    ),
    pages = Math.max(1, Math.ceil(filtered.length / 12)),
    rows = filtered.slice((page - 1) * 12, page * 12);
  async function submit(action: () => void | Promise<void>) {
    setBusy(true);
    try {
      await action();
    } finally {
      setBusy(false);
    }
  }
  return (
    <section className="panel-card management-browser">
      <div className="security-tabs">
        <button
          className={tab === "users" ? "is-active" : ""}
          onClick={() => { setTab("users"); setPage(1); }}
        >
          Usuarios
        </button>
        <button
          className={tab === "entities" ? "is-active" : ""}
          onClick={() => { setTab("entities"); setPage(1); }}
        >
          Entidades enroladas
        </button>
        <button
          className={tab === "catalog" ? "is-active" : ""}
          onClick={() => { setTab("catalog"); setPage(1); }}
        >
          Catastro público
        </button>
      </div>
      <div className="table-toolbar">
        <input
          type="search"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Buscar…"
        />
        <span>{filtered.length} registros</span>
        {tab !== "catalog" && (
          <button
            className="button button-primary"
            onClick={() =>
              tab === "users" ? setUserModal(null) : setNotaryModal(null)
            }
          >
            Agregar {tab === "users" ? "usuario" : "entidad"}
          </button>
        )}
      </div>
      <div className="panel-table-wrap">
        <table>
          <thead>
            {tab === "users" ? (
              <tr>
                <th>Usuario</th>
                <th>Rol</th>
                <th>Activo</th>
                <th>2FA</th>
                <th></th>
              </tr>
            ) : tab === "entities" ? (
              <tr>
                <th>Entidad</th>
                <th>Capacidades</th>
                <th>RUT</th>
                <th>Comuna</th>
                <th>Estado</th>
                <th></th>
              </tr>
            ) : (
              <tr>
                <th>Entidad del catastro</th>
                <th>Tipo</th>
                <th>Ubicación</th>
                <th>Publicación</th>
                <th></th>
              </tr>
            )}
          </thead>
          <tbody>
            {tab === "users"
              ? rows.map((x) => (
                  <tr key={String(x.id)}>
                    <td>
                      <strong>
                        {String(x.nombres)} {String(x.apellidos)}
                      </strong>
                      <small>{String(x.email)}</small>
                    </td>
                    <td>{String(x.roles || "—")}</td>
                    <td>{x.activo ? "Sí" : "No"}</td>
                    <td>
                      {x.mfa_habilitado
                        ? "Configurado"
                        : x.mfa_requerido
                          ? "Exigido, pendiente"
                          : "Opcional"}
                    </td>
                    <td>
                      <div className="download-actions">
                        <button
                          className="table-action"
                          onClick={() => setUserModal(x)}
                        >
                          Editar
                        </button>
                        {Boolean(x.mfa_habilitado) && (
                          <button
                            className="table-action danger"
                            disabled={busy}
                            onClick={() => {
                              if (!confirm("¿Resetear el 2FA de este usuario? Se cerrarán todas sus sesiones activas.")) return;
                              void submit(() => onResetMfa(Number(x.id)));
                            }}
                          >
                            Resetear 2FA
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              : tab === "entities"
              ? rows.map((x) => (
                  <tr key={String(x.id)}>
                    <td>
                      <strong>{String(x.nombre_fantasia)}</strong>
                      <small>{String(x.razon_social)}</small>
                    </td>
                    <td>
                      {((x.capacidades || []) as string[]).join(" · ") || "Sin definir"}
                    </td>
                    <td>{String(x.rut)}</td>
                    <td>{String(x.comuna || "—")}</td>
                    <td>{x.activa ? "Activa" : "Inactiva"}</td>
                    <td>
                      <div className="download-actions">
                        <button
                          className="table-action"
                          onClick={() => setNotaryModal(x)}
                        >
                          Editar
                        </button>
                        <Link
                          className="table-action"
                          href={`/panel/entidad/${x.id}/credenciales`}
                        >
                          Credenciales
                        </Link>
                      </div>
                    </td>
                  </tr>
                ))
              : rows.map((x) => (
                  <tr key={String(x.id)}>
                    <td>
                      <strong>{String(x.nombre_directorio)}</strong>
                      <small>{String(x.cargo || "Sin responsable informado")}</small>
                    </td>
                    <td>{((x.capacidades || []) as string[]).join(" · ") || "Sin definir"}</td>
                    <td>
                      {String(x.comuna || "Sin comuna")}
                      <small>{String(x.region || "Sin región")}</small>
                    </td>
                    <td>
                      {x.estado_revision === "DESCARTADO"
                        ? "Oculta"
                        : String(x.estado_revision || "Pendiente")}
                    </td>
                    <td>
                      <button className="table-action" onClick={() => setCatalogModal(x)}>
                        Editar
                      </button>
                    </td>
                  </tr>
                ))}
          </tbody>
        </table>
      </div>
      <div className="table-pagination">
        <button disabled={page <= 1} onClick={() => setPage((v) => v - 1)}>
          Anterior
        </button>
        <span>
          Página {page} de {pages}
        </span>
        <button disabled={page >= pages} onClick={() => setPage((v) => v + 1)}>
          Siguiente
        </button>
      </div>
      {tab === "catalog" && sourceCatalog && (
        <div className="integration-note">
          <strong>Catastro institucional cargado en staging</strong>
          <span>
            {Number(sourceCatalog.entidades_fuente || 0).toLocaleString("es-CL")} registros de origen · {Number(sourceCatalog.pendientes || 0).toLocaleString("es-CL")} pendientes · {Number(sourceCatalog.observadas || 0).toLocaleString("es-CL")} observados · {Number(sourceCatalog.incidencias_abiertas || 0).toLocaleString("es-CL")} incidencias abiertas.
          </span>
        </div>
      )}
      {userModal !== false && (
        <Modal
          title={userModal ? "Editar usuario" : "Crear usuario"}
          onClose={() => setUserModal(false)}
        >
          <form
            className="profile-form"
            onSubmit={(e) =>
              void submit(() =>
                userModal ? onUpdate(Number(userModal.id), e) : onCreate(e),
              )
            }
          >
            <div className="form-pair">
              <label>
                Nombres
                <input
                  name="nombres"
                  defaultValue={String(userModal?.nombres || "")}
                  required
                />
              </label>
              <label>
                Apellidos
                <input
                  name="apellidos"
                  defaultValue={String(userModal?.apellidos || "")}
                  required
                />
              </label>
            </div>
            <label>
              Correo
              <input
                name="email"
                type="email"
                defaultValue={String(userModal?.email || "")}
                required
              />
            </label>
            <label>
              Contraseña
              <input
                name="password"
                type="password"
                minLength={12}
                required={!userModal}
              />
            </label>
            <div className="form-pair">
              <label>
                Rol
                <select
                  name="rol"
                  defaultValue={String(
                    userModal?.roles || "NOTARIA_FUNCIONARIO",
                  )}
                >
                  <option value="NOTARIA_FUNCIONARIO">Funcionario de entidad</option>
                  <option value="NOTARIA_ADMIN">Administrador de entidad</option>
                  <option value="ADMIN_PLATAFORMA">
                    Administrador Documenta
                  </option>
                  <option value="CLIENTE">Cliente</option>
                </select>
              </label>
              <label>
                Entidad
                <select
                  name="notaria_id"
                  defaultValue={String(userModal?.notaria_id || "")}
                >
                  <option value="">Sin asignación</option>
                  {notaries.map((n) => (
                    <option key={String(n.id)} value={String(n.id)}>
                      {String(n.nombre_fantasia)}
                    </option>
                  ))}
                </select>
              </label>
            </div>
            <label>
              <input
                name="activo"
                type="checkbox"
                defaultChecked={!userModal || Boolean(userModal.activo)}
              />{" "}
              Usuario activo
            </label>
            <label>
              <input
                name="mfa_requerido"
                type="checkbox"
                defaultChecked={Boolean(userModal?.mfa_requerido)}
              />{" "}
              Exigir 2FA
            </label>
            <button className="button button-primary" disabled={busy}>
              {busy ? "Guardando…" : "Guardar usuario"}
            </button>
          </form>
        </Modal>
      )}
      {notaryModal !== false && (
        <Modal
          title={notaryModal ? "Editar entidad" : "Agregar entidad"}
          onClose={() => setNotaryModal(false)}
        >
          <form
            className="profile-form"
            onSubmit={(e) =>
              void submit(() =>
                onSaveNotary(notaryModal ? Number(notaryModal.id) : null, e),
              )
            }
          >
            <div className="form-pair">
              <label>
                RUT
                <input
                  name="rut"
                  defaultValue={String(notaryModal?.rut || "")}
                  onChange={(e) =>
                    (e.currentTarget.value = rutFormat(e.currentTarget.value))
                  }
                  required
                />
              </label>
              <label>
                Nombre fantasía
                <input
                  name="nombre_fantasia"
                  defaultValue={String(notaryModal?.nombre_fantasia || "")}
                  required
                />
              </label>
            </div>
            <label>
              Razón social
              <input
                name="razon_social"
                defaultValue={String(notaryModal?.razon_social || "")}
                required
              />
            </label>
            <label>
              Nombre del titular o responsable
              <input
                name="nombre_notario"
                defaultValue={String(notaryModal?.nombre_notario || "")}
              />
            </label>
            <fieldset className="entity-capabilities">
              <legend>Capacidades de la entidad</legend>
              {capabilityCatalog.map((capability) => {
                const code = String(capability.codigo);
                const selected = ((notaryModal?.capacidades || ["NOTARIA"]) as string[]).includes(code);
                return (
                  <label key={code}>
                    <input
                      name="capacidades"
                      type="checkbox"
                      value={code}
                      defaultChecked={selected}
                    />{" "}
                    {String(capability.nombre)}
                  </label>
                );
              })}
              <small>Una entidad puede tener una o varias capacidades.</small>
            </fieldset>
            <LocationFields
              communes={communes}
              initialCommuneId={notaryModal?.comuna_id}
            />
            <label>
              Dirección
              <input
                name="direccion"
                defaultValue={String(notaryModal?.direccion || "")}
                required
              />
            </label>
            <label>
              Ciudad
              <input
                name="ciudad"
                defaultValue={String(notaryModal?.ciudad || notaryModal?.comuna || "")}
                placeholder="Ej. Copiapó"
              />
            </label>
            <div className="form-pair">
              <label>Latitud<input name="latitud" type="number" step="0.0000001" min="-90" max="90" defaultValue={notaryModal?.latitud ? Number(notaryModal.latitud) : undefined} placeholder="-33.4489000" /></label>
              <label>Longitud<input name="longitud" type="number" step="0.0000001" min="-180" max="180" defaultValue={notaryModal?.longitud ? Number(notaryModal.longitud) : undefined} placeholder="-70.6693000" /></label>
            </div>
            <div className="form-pair">
              <label>
                Teléfono
                <input
                  name="telefono"
                  defaultValue={String(notaryModal?.telefono || "")}
                />
              </label>
              <label>
                Días vencimiento
                <input
                  name="dias_vencimiento"
                  type="number"
                  defaultValue={Number(notaryModal?.dias_vencimiento || 30)}
                  required
                />
              </label>
            </div>
            <label>
              Correo operaciones
              <input
                name="email_operaciones"
                type="email"
                defaultValue={String(notaryModal?.email_operaciones || "")}
                required
              />
            </label>
            <label>
              Correo notificaciones
              <input
                name="email_notificaciones"
                type="email"
                defaultValue={String(notaryModal?.email_notificaciones || "")}
                required
              />
            </label>
            <label>
              Logo para el membrete
              <input name="logo" type="file" accept="image/png,image/jpeg" />
              <small>
                {notaryModal?.logo_configurado
                  ? "Ya existe un logo configurado. Selecciona otro archivo para reemplazarlo."
                  : "PNG o JPEG, máximo 2 MB. Se mostrará pequeño en la esquina superior izquierda."}
              </small>
            </label>
            <label>
              <input
                name="activa"
                type="checkbox"
                defaultChecked={!notaryModal || Boolean(notaryModal.activa)}
              />{" "}
              Entidad activa
            </label>
            <button className="button button-primary" disabled={busy}>
              {busy ? "Guardando…" : "Guardar entidad"}
            </button>
          </form>
        </Modal>
      )}
      {catalogModal !== false && catalogModal && (
        <Modal
          title="Editar ficha del catastro público"
          onClose={() => setCatalogModal(false)}
        >
          <form
            className="profile-form"
            onSubmit={(event) =>
              void submit(async () => {
                const saved = await onSaveCatalogEntity(Number(catalogModal.id), event);
                if (saved !== false) setCatalogModal(false);
              })
            }
          >
            <label>
              Nombre de la entidad
              <input
                name="nombre_directorio"
                defaultValue={String(catalogModal.nombre_directorio || "")}
                required
              />
            </label>
            <label>
              Titular, responsable o descripción
              <input
                name="cargo"
                defaultValue={String(catalogModal.cargo || "")}
                required
              />
            </label>
            <fieldset className="entity-capabilities">
              <legend>Tipo de entidad</legend>
              {capabilityCatalog.map((capability) => {
                const code = String(capability.codigo);
                const selected = ((catalogModal.capacidades || []) as string[]).includes(code);
                return (
                  <label key={code}>
                    <input
                      name="capacidades"
                      type="checkbox"
                      value={code}
                      defaultChecked={selected}
                    />{" "}
                    {String(capability.nombre)}
                  </label>
                );
              })}
            </fieldset>
            <LocationFields
              communes={communes}
              initialCommuneId={catalogModal.comuna_id}
            />
            <label>
              Dirección
              <input name="direccion" defaultValue={String(catalogModal.direccion || "")} />
            </label>
            <div className="form-pair">
              <label>
                Teléfono
                <input name="telefono" defaultValue={String(catalogModal.telefono || "")} />
              </label>
              <label>
                Correo
                <input name="correo" defaultValue={String(catalogModal.correo || "")} />
              </label>
            </div>
            <label>
              Sitio web
              <input name="sitio_web" defaultValue={String(catalogModal.sitio_web || "")} />
            </label>
            <label>
              Horario
              <input name="horario" defaultValue={String(catalogModal.horario || "")} />
            </label>
            <label>
              Estado de publicación
              <select
                name="estado_revision"
                defaultValue={String(catalogModal.estado_revision || "VALIDADO")}
              >
                <option value="VALIDADO">Validada y visible</option>
                <option value="PENDIENTE">Pendiente y visible</option>
                <option value="OBSERVADO">Observada y visible</option>
                <option value="DESCARTADO">Oculta del portal</option>
              </select>
            </label>
            <div className="integration-note">
              <strong>La región se determina desde la comuna</strong>
              <span>No se guarda una región independiente, por lo que no pueden quedar combinaciones incompatibles.</span>
            </div>
            <button className="button button-primary" disabled={busy}>
              {busy ? "Guardando…" : "Guardar ficha pública"}
            </button>
          </form>
        </Modal>
      )}
      {credential && (
        <Modal
          title={`Credenciales · ${credential.nombre_fantasia}`}
          onClose={() => setCredential(null)}
        >
          <div className="integration-note">
            <strong>Integraciones y medios de pago de la entidad</strong>
            <span>Los secretos quedan cifrados y nunca se muestran.</span>
          </div>
          <div className="credential-grid">
            {(["GESNOT", "WEBPAY", "KLAP", "GETNET"] as const).map((provider) => (
              <CredentialCard
                key={provider}
                provider={provider}
                notary={credential}
                existing={credentials.find(
                  (c) =>
                    Number(c.notaria_id) === Number(credential.id) &&
                    c.proveedor === provider &&
                    c.activa !== false,
                )}
                onSave={onRotateCredential}
                onDelete={onDeleteCredential}
                onTest={onTestGesnot}
              />
            ))}
          </div>
        </Modal>
      )}
    </section>
  );
}
