"use client";

import { useEffect, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  EmptyState,
  PageHeader,
  PageLoader,
  Pagination,
  StatusBadge,
  usePagination,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatDate } from "@/lib/utils";
import { IconSend, IconSparkle, IconTrash } from "@/components/icons";
import { emsConfirm } from "@/components/ConfirmDialog";

interface DemoRequest {
  id: number;
  name: string;
  email: string;
  phone: string | null;
  institutionName: string;
  institutionType: string;
  message: string | null;
  status: string;
  createdAt: string;
  contactedAt: string | null;
  decidedAt: string | null;
  demoSentAt: string | null;
  /// validity window (days) the central admin set for this demo
  validDays: number;
  demoExpiresAt: string | null;
}

const FILTERS = ["ALL", "PENDING", "CONTACTED", "CONVERTED", "REJECTED"] as const;

/** display label + pill color for the consolidated demo-form audience values */
function demoTypeMeta(type: string, t: ReturnType<typeof useLang>["t"]) {
  const labels: Record<string, string> = {
    KG_PRIMARY: t.landing.demoTypeKgPrimary,
    HIGH_SCHOOL: t.landing.demoTypeHighSchool,
    PRIMARY_HIGH: t.landing.demoTypePrimaryHigh,
    COLLEGE_UNI: t.landing.demoTypeCollegeUni,
    COACHING: t.landing.demoTypeCoaching,
    MADRASHA: t.landing.demoTypeMadrasha,
  };
  const pills: Record<string, string> = {
    KG_PRIMARY: "ems-type-KINDERGARTEN",
    HIGH_SCHOOL: "ems-type-HIGH_SCHOOL",
    PRIMARY_HIGH: "ems-type-PRIMARY",
    COLLEGE_UNI: "ems-type-COLLEGE",
    COACHING: "ems-type-COACHING",
    MADRASHA: "ems-type-MADRASHA",
  };
  return {
    label: labels[type] ?? t.types[type as keyof typeof t.types] ?? type,
    pill: pills[type] ?? "ems-type-HIGH_SCHOOL",
  };
}

export default function CentralDemoRequestsPage() {
  const { t, locale } = useLang();
  const { data, loading, reload } = useApi<{ requests: DemoRequest[]; defaultValidDays: number }>(
    "/api/central/demo-requests"
  );
  const [filter, setFilter] = useState<(typeof FILTERS)[number]>("ALL");
  const [message, setMessage] = useState<{
    type: "success" | "error" | "warning";
    text: string;
  } | null>(null);
  const [busyId, setBusyId] = useState<number | null>(null);
  // platform default validity (days) the central admin configures
  const [defaultDays, setDefaultDays] = useState("");
  const [savingDefault, setSavingDefault] = useState(false);
  // per-request validity (days), editable in the table
  const [daysById, setDaysById] = useState<Record<number, string>>({});

  useEffect(() => {
    if (!data) return;
    setDefaultDays((cur) => cur || String(data.defaultValidDays));
    setDaysById((cur) => {
      const next = { ...cur };
      for (const r of data.requests) {
        if (next[r.id] === undefined) next[r.id] = String(r.validDays);
      }
      return next;
    });
  }, [data]);

  function setDay(id: number, value: string) {
    setDaysById((cur) => ({ ...cur, [id]: value }));
  }

  /** Save the platform-wide default validity applied to new demo requests. */
  async function saveDefault() {
    const days = Number(defaultDays);
    if (!Number.isFinite(days) || days < 1 || days > 365) {
      setMessage({ type: "error", text: t.central.demoRequestsPage.validityInvalid });
      return;
    }
    setSavingDefault(true);
    try {
      await api("/api/central/demo-requests", {
        method: "PUT",
        body: JSON.stringify({ validDays: days }),
      });
      setMessage({
        type: "success",
        text: t.central.demoRequestsPage.validitySaved.replace("{days}", String(days)),
      });
      reload();
    } catch (err) {
      setMessage({ type: "error", text: err instanceof Error ? err.message : t.common.tryAgain });
    } finally {
      setSavingDefault(false);
    }
  }

  /** Update the validity window of one request (recomputes an existing grant's expiry). */
  async function updateValidity(demo: DemoRequest) {
    const days = Number(daysById[demo.id]);
    if (!Number.isFinite(days) || days < 1 || days > 365) {
      setMessage({ type: "error", text: t.central.demoRequestsPage.validityInvalid });
      return;
    }
    setBusyId(demo.id);
    try {
      await api(`/api/central/demo-requests/${demo.id}`, {
        method: "PATCH",
        body: JSON.stringify({ validDays: days }),
      });
      setMessage({
        type: "success",
        text: t.central.demoRequestsPage.validityUpdatedMsg,
      });
      reload();
    } catch (err) {
      setMessage({ type: "error", text: err instanceof Error ? err.message : t.common.tryAgain });
    } finally {
      setBusyId(null);
    }
  }

  async function setStatus(demo: DemoRequest, status: "CONTACTED" | "CONVERTED" | "REJECTED") {
    const confirmText =
      status === "CONVERTED"
        ? t.central.demoRequestsPage.convertConfirm
        : status === "REJECTED"
          ? t.central.demoRequestsPage.rejectConfirm
          : null;
    if (confirmText && !(await emsConfirm({ message: confirmText, danger: status === "REJECTED" }))) return;
    setBusyId(demo.id);
    try {
      await api(`/api/central/demo-requests/${demo.id}`, {
        method: "PATCH",
        body: JSON.stringify({ status }),
      });
      setMessage({
        type: "success",
        text:
          status === "CONTACTED"
            ? t.central.demoRequestsPage.contactedMsg
            : status === "CONVERTED"
              ? t.central.demoRequestsPage.convertedMsg
              : t.central.demoRequestsPage.rejectedMsg,
      });
      reload();
    } catch (err) {
      setMessage({ type: "error", text: err instanceof Error ? err.message : t.common.tryAgain });
    } finally {
      setBusyId(null);
    }
  }

  /** Provision a demo environment and email the login credentials to the requester. */
  async function sendDemo(demo: DemoRequest) {
    const days = Number(daysById[demo.id] ?? demo.validDays);
    if (!Number.isFinite(days) || days < 1 || days > 365) {
      setMessage({ type: "error", text: t.central.demoRequestsPage.validityInvalid });
      return;
    }
    const confirmText = `${t.central.demoRequestsPage.sendDemoConfirm} ${t.central.demoRequestsPage.sendDemoDaysNote.replace("{n}", String(days))}`;
    if (!(await emsConfirm({ message: confirmText }))) return;
    setBusyId(demo.id);
    try {
      const res = await api<{ sent: boolean; password: string }>(
        `/api/central/demo-requests/${demo.id}`,
        { method: "PATCH", body: JSON.stringify({ sendDemo: true, validDays: days }) }
      );
      if (res.sent) {
        setMessage({
          type: "success",
          text: demo.demoSentAt
            ? t.central.demoRequestsPage.demoResentMsg
            : t.central.demoRequestsPage.demoSentMsg,
        });
      } else {
        setMessage({
          type: "warning",
          text: `${t.central.demoRequestsPage.demoSentManual} ${res.password}`,
        });
      }
      reload();
    } catch (err) {
      setMessage({
        type: "error",
        text:
          err instanceof Error && err.message === "EMAIL_TAKEN"
            ? t.central.demoRequestsPage.demoEmailTaken
            : t.common.tryAgain,
      });
    } finally {
      setBusyId(null);
    }
  }

  async function remove(demo: DemoRequest) {
    if (!(await emsConfirm({ message: t.central.demoRequestsPage.deleteConfirm, danger: true }))) return;
    setBusyId(demo.id);
    try {
      await api(`/api/central/demo-requests/${demo.id}`, { method: "DELETE" });
      setMessage({ type: "success", text: t.central.demoRequestsPage.deletedMsg });
      reload();
    } catch (err) {
      setMessage({ type: "error", text: err instanceof Error ? err.message : t.common.tryAgain });
    } finally {
      setBusyId(null);
    }
  }

  const all = data?.requests ?? [];
  const requests = filter === "ALL" ? all : all.filter((r) => r.status === filter);
  const requestsPager = usePagination(requests, 10);
  const countBy = (f: string) => (f === "ALL" ? all.length : all.filter((r) => r.status === f).length);

  return (
    <div>
      <PageHeader
        title={t.central.demoRequestsPage.title}
        subtitle={t.central.demoRequestsPage.subtitle}
      />

      {message && (
        <div className="mb-4">
          <Alert type={message.type} onClose={() => setMessage(null)}>{message.text}</Alert>
        </div>
      )}

      {/* central admin sets how long a granted demo stays usable */}
      <div className="card p-3 mb-4">
        <div className="d-flex flex-wrap align-items-center gap-2">
          <label className="f-w-700 ems-fs-13 mb-0">
            {t.central.demoRequestsPage.validityLabel}
          </label>
          <input
            type="number"
            min={1}
            max={365}
            className="form-control form-control-sm"
            style={{ maxWidth: 90 }}
            value={defaultDays}
            onChange={(e) => setDefaultDays(e.target.value)}
          />
          <Button size="sm" variant="primary" loading={savingDefault} onClick={saveDefault}>
            {t.common.save}
          </Button>
          <span className="ems-fs-12 text-muted">{t.central.demoRequestsPage.validityHint}</span>
        </div>
      </div>

      {/* status filter tabs with counts */}
      <div className="d-flex flex-wrap gap-2 mb-4">
        {FILTERS.map((f) => (
          <button
            key={f}
            className={`btn btn-sm f-w-600 ${filter === f ? "btn-primary" : "btn-outline-secondary"}`}
            onClick={() => setFilter(f)}
          >
            {f === "ALL"
              ? `${t.central.demoRequestsPage.filterAll} (${all.length})`
              : `${t.status[f as keyof typeof t.status]} (${countBy(f)})`}
          </button>
        ))}
      </div>

      {loading ? (
        <PageLoader text={t.common.loading} />
      ) : requests.length === 0 ? (
        <div className="card">
          <EmptyState icon={<IconSparkle />} title={t.central.demoRequestsPage.noRequests} />
        </div>
      ) : (
        <div className="card">
          <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="ems-table-head">
                <tr>
                  <th>{t.central.demoRequestsPage.requester}</th>
                  <th>{t.central.demoRequestsPage.institutionLabel}</th>
                  <th>{t.central.demoRequestsPage.messageLabel}</th>
                  <th>{t.central.demoRequestsPage.requestedOn}</th>
                  <th>{t.central.demoRequestsPage.daysColumn}</th>
                  <th>{t.common.status}</th>
                  <th className="text-end">{t.common.actions}</th>
                </tr>
              </thead>
              <tbody>
                {requestsPager.paged.map((demo) => {
                  const exp = demo.demoExpiresAt ? new Date(demo.demoExpiresAt) : null;
                  const daysLeft = exp
                    ? Math.ceil((exp.getTime() - Date.now()) / 86_400_000)
                    : null;
                  const expired = daysLeft !== null && daysLeft <= 0;
                  return (
                  <tr key={demo.id} className={demo.status === "REJECTED" ? "opacity-50" : ""}>
                    <td>
                      <div className="media align-items-center gap-3">
                        <span
                          className="rounded-circle d-flex align-items-center justify-content-center f-w-800 ems-fs-12"
                          style={{ width: 40, height: 40, background: "rgba(36,105,92,0.13)", color: "#24695c" }}
                        >
                          {demo.name.slice(0, 2).toUpperCase()}
                        </span>
                        <div className="media-body">
                          <h6 className="mb-0 f-w-700">{demo.name}</h6>
                          <p className="mb-0 ems-fs-11 text-muted">{demo.email}</p>
                          {demo.phone && (
                            <p className="mb-0 ems-fs-11 text-muted">{demo.phone}</p>
                          )}
                        </div>
                      </div>
                    </td>
                    <td>
                      <p className="mb-0 f-w-600 ems-fs-13">{demo.institutionName}</p>
                      {(() => {
                        const meta = demoTypeMeta(demo.institutionType, t);
                        return (
                          <span className={`ems-type-pill ${meta.pill} mt-1`}>{meta.label}</span>
                        );
                      })()}
                    </td>
                    <td style={{ maxWidth: 220 }}>
                      <p
                        className="mb-0 ems-fs-12 text-muted text-truncate"
                        title={demo.message ?? ""}
                      >
                        {demo.message ?? "—"}
                      </p>
                    </td>
                    <td className="ems-fs-12 text-muted">{formatDate(demo.createdAt, locale)}</td>
                    <td>
                      {(demo.status === "PENDING" || demo.status === "CONTACTED") && (
                        <div className="input-group input-group-sm" style={{ width: 112 }}>
                          <input
                            type="number"
                            min={1}
                            max={365}
                            className="form-control"
                            value={daysById[demo.id] ?? String(demo.validDays)}
                            onChange={(e) => setDay(demo.id, e.target.value)}
                          />
                          {demo.demoSentAt && (
                            <button
                              className="btn btn-outline-primary"
                              title={t.central.demoRequestsPage.validityUpdatedMsg}
                              disabled={busyId === demo.id}
                              onClick={() => updateValidity(demo)}
                            >
                              ✓
                            </button>
                          )}
                        </div>
                      )}
                    </td>
                    <td>
                      <StatusBadge
                        status={demo.status}
                        label={t.status[demo.status as keyof typeof t.status]}
                      />
                      {exp && (
                        <p
                          className={`mb-0 ems-fs-11 mt-1 f-w-600 ${expired ? "text-danger" : "text-muted"}`}
                        >
                          {t.central.demoRequestsPage.expiresLabel}: {formatDate(demo.demoExpiresAt!, locale)}
                          {" · "}
                          {expired
                            ? t.central.demoRequestsPage.expiredBadge
                            : t.central.demoRequestsPage.daysLeft.replace("{n}", String(daysLeft))}
                        </p>
                      )}
                      {demo.demoSentAt && (
                        <p className="mb-0 ems-fs-11 text-muted mt-1">
                          ✉ {t.central.demoRequestsPage.demoBadge}: {formatDate(demo.demoSentAt, locale)}
                        </p>
                      )}
                      {demo.contactedAt && demo.status !== "PENDING" && !demo.demoSentAt && (
                        <p className="mb-0 ems-fs-11 text-muted mt-1">
                          {t.central.demoRequestsPage.decidedOn}:{" "}
                          {formatDate(demo.decidedAt ?? demo.contactedAt, locale)}
                        </p>
                      )}
                    </td>
                    <td className="text-end">
                      <div className="d-inline-flex gap-1 align-items-center">
                        {(demo.status === "PENDING" || demo.status === "CONTACTED") && (
                          <Button
                            size="sm"
                            variant="primary"
                            loading={busyId === demo.id}
                            onClick={() => sendDemo(demo)}
                            title={t.central.demoRequestsPage.sendDemoConfirm}
                          >
                            <IconSend className="svg-14" />
                            <span className="d-none d-xl-inline ms-1">
                              {demo.demoSentAt
                                ? t.central.demoRequestsPage.demoBadge
                                : t.central.demoRequestsPage.sendDemo}
                            </span>
                          </Button>
                        )}
                        {demo.status === "PENDING" && (
                          <Button
                            size="sm"
                            variant="info"
                            loading={busyId === demo.id}
                            onClick={() => setStatus(demo, "CONTACTED")}
                          >
                            <span className="d-none d-lg-inline">
                              {t.central.demoRequestsPage.contacted}
                            </span>
                          </Button>
                        )}
                        {(demo.status === "PENDING" || demo.status === "CONTACTED") && (
                          <Button
                            size="sm"
                            variant="success"
                            loading={busyId === demo.id}
                            onClick={() => setStatus(demo, "CONVERTED")}
                          >
                            <span className="d-none d-lg-inline">
                              {t.central.demoRequestsPage.convert}
                            </span>
                          </Button>
                        )}
                        {(demo.status === "PENDING" || demo.status === "CONTACTED") && (
                          <Button
                            size="sm"
                            variant="danger"
                            loading={busyId === demo.id}
                            onClick={() => setStatus(demo, "REJECTED")}
                          >
                            <span className="d-none d-lg-inline">
                              {t.central.demoRequestsPage.reject}
                            </span>
                          </Button>
                        )}
                        <button
                          className="ems-price-act danger ms-1"
                          title={t.common.delete}
                          onClick={() => remove(demo)}
                        >
                          <IconTrash className="svg-14" />
                        </button>
                      </div>
                    </td>
                  </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          <Pagination {...requestsPager} onPageChange={requestsPager.setPage} onSizeChange={requestsPager.setSize} />
        </div>
      )}
    </div>
  );
}
