import { FormEvent, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";

import {
  type AdminOverviewResponse,
  type AdminTenantRequest,
  createAdminTenant,
  fetchAdminOverview,
  updateAdminTenant,
  updateSuperAdminPassword
} from "../lib/api";
import { portalRuntimeConfig } from "../config/runtime";
import { usePortalSession } from "../context/PortalSessionContext";

const emptyTenantForm: AdminTenantRequest = {
  locale_name: "",
  address: "",
  phone_number: "",
  whatsapp_number: "",
  admin_name: "",
  username: "",
  email: "",
  password: ""
};

const emptyPasswordForm = {
  current_password: "",
  new_password: ""
};

export function AdminPage() {
  const navigate = useNavigate();
  const { currentUser, impersonate, platformAdmin } = usePortalSession();
  const [overview, setOverview] = useState<AdminOverviewResponse | null>(null);
  const [selectedTenantId, setSelectedTenantId] = useState<string | null>(null);
  const [createForm, setCreateForm] = useState<AdminTenantRequest>(emptyTenantForm);
  const [editForm, setEditForm] = useState<AdminTenantRequest>(emptyTenantForm);
  const [passwordForm, setPasswordForm] = useState(emptyPasswordForm);
  const [loading, setLoading] = useState(true);
  const [createBusy, setCreateBusy] = useState(false);
  const [saveBusy, setSaveBusy] = useState(false);
  const [passwordBusy, setPasswordBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const tenants = overview?.tenants ?? [];
  const selectedTenant = useMemo(
    () => tenants.find((item) => item.tenant.id === selectedTenantId) ?? null,
    [selectedTenantId, tenants]
  );

  useEffect(() => {
    if (currentUser?.role !== "super_admin") {
      navigate("/home", { replace: true });
      return;
    }

    if (platformAdmin?.is_impersonating) {
      navigate("/home", { replace: true });
      return;
    }

    async function loadOverview() {
      try {
        const payload = await fetchAdminOverview(portalRuntimeConfig.apiHubBaseUrl);
        setOverview(payload);
        setSelectedTenantId((current) => current ?? payload.tenants[0]?.tenant.id ?? null);
      } catch (nextError) {
        setError(nextError instanceof Error ? nextError.message : "Pannello admin non disponibile.");
      } finally {
        setLoading(false);
      }
    }

    void loadOverview();
  }, [currentUser?.role, navigate, platformAdmin?.is_impersonating]);

  useEffect(() => {
    if (!selectedTenant) {
      setEditForm(emptyTenantForm);
      return;
    }

    setEditForm({
      locale_name: selectedTenant.tenant.name,
      address: selectedTenant.venue?.address ?? "",
      phone_number: selectedTenant.venue?.phone_number ?? "",
      whatsapp_number: selectedTenant.venue?.whatsapp_number ?? "",
      admin_name: selectedTenant.admin_user?.name ?? "",
      username: selectedTenant.admin_user?.username ?? "",
      email: selectedTenant.admin_user?.email ?? "",
      password: ""
    });
  }, [selectedTenant]);

  async function reloadOverview(nextSelectedTenantId?: string | null) {
    const payload = await fetchAdminOverview(portalRuntimeConfig.apiHubBaseUrl);
    setOverview(payload);
    setSelectedTenantId(nextSelectedTenantId ?? payload.tenants[0]?.tenant.id ?? null);
  }

  async function handleCreateSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setCreateBusy(true);
    setError(null);
    setSuccess(null);

    try {
      const createdTenant = await createAdminTenant(portalRuntimeConfig.apiHubBaseUrl, createForm);
      await reloadOverview(createdTenant.tenant.id);
      setCreateForm(emptyTenantForm);
      setSuccess(`Locale ${createdTenant.tenant.name} creato correttamente.`);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : "Creazione locale non riuscita.");
    } finally {
      setCreateBusy(false);
    }
  }

  async function handleSaveTenant(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!selectedTenant) {
      return;
    }

    setSaveBusy(true);
    setError(null);
    setSuccess(null);

    try {
      const updatedTenant = await updateAdminTenant(
        portalRuntimeConfig.apiHubBaseUrl,
        selectedTenant.tenant.id,
        editForm
      );
      await reloadOverview(updatedTenant.tenant.id);
      setSuccess(`Locale ${updatedTenant.tenant.name} aggiornato.`);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : "Aggiornamento locale non riuscito.");
    } finally {
      setSaveBusy(false);
    }
  }

  async function handlePasswordSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setPasswordBusy(true);
    setError(null);
    setSuccess(null);

    try {
      await updateSuperAdminPassword(portalRuntimeConfig.apiHubBaseUrl, passwordForm);
      setPasswordForm(emptyPasswordForm);
      setSuccess("Password del super admin aggiornata.");
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : "Aggiornamento password non riuscito.");
    } finally {
      setPasswordBusy(false);
    }
  }

  async function handleEnterTenant(tenantId: string) {
    setError(null);
    setSuccess(null);

    try {
      await impersonate(tenantId);
      navigate("/home", { replace: true });
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : "Ingresso nel locale non riuscito.");
    }
  }

  if (loading) {
    return (
      <section className="panel narrow-panel stack-md">
        <p className="eyebrow">Admin</p>
        <h2 className="page-title">Carico la console piattaforma</h2>
        <p className="muted-copy">Sto recuperando locali, account admin e sessione piattaforma.</p>
      </section>
    );
  }

  const totalEnabledModules = tenants.reduce((sum, item) => sum + item.enabled_modules, 0);

  return (
    <section className="stack-lg">
      <section className="stats-grid">
        <article className="stat-card">
          <span>Locali clienti</span>
          <strong>{tenants.length}</strong>
          <small>Tenant registrati nella piattaforma</small>
        </article>
        <article className="stat-card">
          <span>Moduli attivi</span>
          <strong>{totalEnabledModules}</strong>
          <small>Somma dei moduli abilitati sui locali</small>
        </article>
        <article className="stat-card">
          <span>Super admin</span>
          <strong>{overview?.super_admin.username ?? "zanchinfede@gmail.com"}</strong>
          <small>Accesso piattaforma separato dai clienti</small>
        </article>
        <article className="stat-card">
          <span>Account cliente</span>
          <strong>{tenants.length}</strong>
          <small>Un admin principale per ogni locale</small>
        </article>
      </section>

      {error ? <p className="auth-error">{error}</p> : null}
      {success ? <div className="callout"><strong>Operazione completata</strong>{success}</div> : null}

      <section className="admin-layout">
        <section className="panel stack-md">
          <div className="panel-heading">
            <div>
              <p className="eyebrow">Nuovo cliente</p>
              <h3>Crea locale e admin cliente</h3>
            </div>
          </div>

          <form className="mock-form" onSubmit={handleCreateSubmit}>
            <div className="auth-inline-grid">
              <label className="field">
                <span>Nome locale</span>
                <input
                  type="text"
                  value={createForm.locale_name}
                  onChange={(event) => setCreateForm((current) => ({ ...current, locale_name: event.target.value }))}
                  required
                  minLength={2}
                  disabled={createBusy}
                />
              </label>
              <label className="field">
                <span>Nome admin cliente</span>
                <input
                  type="text"
                  value={createForm.admin_name}
                  onChange={(event) => setCreateForm((current) => ({ ...current, admin_name: event.target.value }))}
                  required
                  minLength={2}
                  disabled={createBusy}
                />
              </label>
            </div>

            <div className="auth-inline-grid">
              <label className="field">
                <span>Username admin</span>
                <input
                  type="text"
                  value={createForm.username}
                  onChange={(event) => setCreateForm((current) => ({ ...current, username: event.target.value }))}
                  required
                  minLength={3}
                  disabled={createBusy}
                />
              </label>
              <label className="field">
                <span>Email admin</span>
                <input
                  type="email"
                  value={createForm.email}
                  onChange={(event) => setCreateForm((current) => ({ ...current, email: event.target.value }))}
                  required
                  disabled={createBusy}
                />
              </label>
            </div>

            <div className="auth-inline-grid">
              <label className="field">
                <span>Telefono locale</span>
                <input
                  type="text"
                  value={createForm.phone_number}
                  onChange={(event) => setCreateForm((current) => ({ ...current, phone_number: event.target.value }))}
                  disabled={createBusy}
                />
              </label>
              <label className="field">
                <span>WhatsApp locale</span>
                <input
                  type="text"
                  value={createForm.whatsapp_number}
                  onChange={(event) =>
                    setCreateForm((current) => ({ ...current, whatsapp_number: event.target.value }))
                  }
                  disabled={createBusy}
                />
              </label>
            </div>

            <label className="field">
              <span>Indirizzo</span>
              <input
                type="text"
                value={createForm.address}
                onChange={(event) => setCreateForm((current) => ({ ...current, address: event.target.value }))}
                required
                disabled={createBusy}
              />
            </label>

            <label className="field">
              <span>Password iniziale admin cliente</span>
              <input
                type="password"
                value={createForm.password}
                onChange={(event) => setCreateForm((current) => ({ ...current, password: event.target.value }))}
                required
                minLength={8}
                disabled={createBusy}
              />
            </label>

            <button type="submit" className="button-primary" disabled={createBusy}>
              {createBusy ? "Creazione in corso" : "Crea nuovo locale"}
            </button>
          </form>
        </section>

        <section className="panel stack-md">
          <div className="panel-heading">
            <div>
              <p className="eyebrow">Locali attivi</p>
              <h3>Gestione tenant registrati</h3>
            </div>
            <p>{tenants.length} locali disponibili</p>
          </div>

          <div className="admin-tenant-list">
            {tenants.map((tenant) => (
              <article
                key={tenant.tenant.id}
                className={`admin-tenant-card${selectedTenantId === tenant.tenant.id ? " is-selected" : ""}`}
              >
                <button
                  type="button"
                  className="admin-tenant-select"
                  onClick={() => setSelectedTenantId(tenant.tenant.id)}
                >
                  <strong>{tenant.tenant.name}</strong>
                  <span>{tenant.admin_user?.email ?? "Admin non configurato"}</span>
                  <small>{tenant.enabled_modules}/{tenant.total_modules} moduli attivi</small>
                </button>
                <button
                  type="button"
                  className="button-secondary"
                  onClick={() => void handleEnterTenant(tenant.tenant.id)}
                >
                  Entra nel locale
                </button>
              </article>
            ))}
          </div>
        </section>
      </section>

      <section className="admin-layout">
        <section className="panel stack-md">
          <div className="panel-heading">
            <div>
              <p className="eyebrow">Modifica locale</p>
              <h3>Account admin del cliente</h3>
            </div>
          </div>

          {selectedTenant ? (
            <form className="mock-form" onSubmit={handleSaveTenant}>
              <div className="auth-inline-grid">
                <label className="field">
                  <span>Nome locale</span>
                  <input
                    type="text"
                    value={editForm.locale_name}
                    onChange={(event) => setEditForm((current) => ({ ...current, locale_name: event.target.value }))}
                    required
                    minLength={2}
                    disabled={saveBusy}
                  />
                </label>
                <label className="field">
                  <span>Nome admin cliente</span>
                  <input
                    type="text"
                    value={editForm.admin_name}
                    onChange={(event) => setEditForm((current) => ({ ...current, admin_name: event.target.value }))}
                    required
                    minLength={2}
                    disabled={saveBusy}
                  />
                </label>
              </div>

              <div className="auth-inline-grid">
                <label className="field">
                  <span>Username admin</span>
                  <input
                    type="text"
                    value={editForm.username}
                    onChange={(event) => setEditForm((current) => ({ ...current, username: event.target.value }))}
                    required
                    minLength={3}
                    disabled={saveBusy}
                  />
                </label>
                <label className="field">
                  <span>Email admin</span>
                  <input
                    type="email"
                    value={editForm.email}
                    onChange={(event) => setEditForm((current) => ({ ...current, email: event.target.value }))}
                    required
                    disabled={saveBusy}
                  />
                </label>
              </div>

              <div className="auth-inline-grid">
                <label className="field">
                  <span>Telefono locale</span>
                  <input
                    type="text"
                    value={editForm.phone_number}
                    onChange={(event) => setEditForm((current) => ({ ...current, phone_number: event.target.value }))}
                    disabled={saveBusy}
                  />
                </label>
                <label className="field">
                  <span>WhatsApp locale</span>
                  <input
                    type="text"
                    value={editForm.whatsapp_number}
                    onChange={(event) =>
                      setEditForm((current) => ({ ...current, whatsapp_number: event.target.value }))
                    }
                    disabled={saveBusy}
                  />
                </label>
              </div>

              <label className="field">
                <span>Indirizzo</span>
                <input
                  type="text"
                  value={editForm.address}
                  onChange={(event) => setEditForm((current) => ({ ...current, address: event.target.value }))}
                  required
                  disabled={saveBusy}
                />
              </label>

              <label className="field">
                <span>Nuova password admin cliente</span>
                <input
                  type="password"
                  value={editForm.password}
                  onChange={(event) => setEditForm((current) => ({ ...current, password: event.target.value }))}
                  minLength={8}
                  placeholder="Lascia vuoto per non cambiarla"
                  disabled={saveBusy}
                />
              </label>

              <button type="submit" className="button-primary" disabled={saveBusy}>
                {saveBusy ? "Salvataggio in corso" : "Salva modifiche locale"}
              </button>
            </form>
          ) : (
            <p className="muted-copy">Seleziona un locale dalla lista per modificare i suoi dati.</p>
          )}
        </section>

        <section className="panel stack-md">
          <div className="panel-heading">
            <div>
              <p className="eyebrow">Sicurezza</p>
              <h3>Password super admin</h3>
            </div>
          </div>

          <form className="mock-form" onSubmit={handlePasswordSubmit}>
            <label className="field">
              <span>Password attuale</span>
              <input
                type="password"
                value={passwordForm.current_password}
                onChange={(event) =>
                  setPasswordForm((current) => ({ ...current, current_password: event.target.value }))
                }
                required
                disabled={passwordBusy}
              />
            </label>
            <label className="field">
              <span>Nuova password super admin</span>
              <input
                type="password"
                value={passwordForm.new_password}
                onChange={(event) =>
                  setPasswordForm((current) => ({ ...current, new_password: event.target.value }))
                }
                required
                minLength={8}
                disabled={passwordBusy}
              />
            </label>

            <button type="submit" className="button-primary" disabled={passwordBusy}>
              {passwordBusy ? "Aggiornamento in corso" : "Aggiorna password admin"}
            </button>
          </form>
        </section>
      </section>
    </section>
  );
}
