"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useState } from "react";
import { apiGet, apiPost } from "@/lib/api";
import type { AppNotificationSnapshot, NotificationEmailDigestHistory, NotificationEmailDigestPreview, NotificationEmailDigestSendResult, NotificationEmailDigestTriggerCheckResult } from "@/types";

type PreviewResponse = { result: NotificationEmailDigestPreview };
type SendResponse = { result: NotificationEmailDigestSendResult };
type TriggerCheckResponse = { result: NotificationEmailDigestTriggerCheckResult };
type HistoryResponse = { history: NotificationEmailDigestHistory };

type DigestStatus = "idle" | "preparing" | "ready" | "sending" | "sent" | "error";

function statusClass(status: string) {
  if (status === "READY" || status === "SENT" || status === "READY_FOR_APPROVAL") return "border-emerald-200 bg-emerald-50 text-emerald-700";
  if (status === "NO_ALERTS" || status === "COOLDOWN" || status === "NO_RUNS") return "border-blue-200 bg-blue-50 text-blue-700";
  if (status === "OFF") return "border-slate-200 bg-slate-50 text-slate-600";
  if (status === "PENDING" || status === "AUTOMATION_LOCKED" || status === "LOCKED" || status === "NOT_CONFIGURED") return "border-sky-200 bg-sky-50 text-sky-700";
  if (status === "FAILED" || status === "SETUP_NEEDED") return "border-amber-200 bg-amber-50 text-amber-700";
  return "border-slate-200 bg-slate-50 text-slate-700";
}

function statusLabel(status: string) {
  if (status === "READY") return "Ready to send";
  if (status === "READY_FOR_APPROVAL") return "Ready for approval";
  if (status === "COOLDOWN") return "Guarded";
  if (status === "AUTOMATION_LOCKED") return "Approval-first";
  if (status === "SENT") return "Sent";
  if (status === "NO_ALERTS") return "No digest needed";
  if (status === "OFF") return "Off";
  if (status === "SETUP_NEEDED") return "Needs setup";
  if (status === "PENDING") return "Waiting";
  if (status === "FAILED") return "Needs attention";
  return "Review";
}

function readinessLabel(status: string) {
  if (status === "CONNECTED") return "Ready";
  if (status === "OFF") return "Email choices off";
  return "Needs setup";
}

function readinessMessage(status: string) {
  if (status === "CONNECTED") return "Company email is ready for approved digest sends.";
  if (status === "OFF") return "Turn on at least one email alert choice before sending digests.";
  return "Connect and test company email in Workspace Integrations, then return here to send.";
}

function formatDate(value?: string | null) {
  if (!value) return "—";
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? value : d.toLocaleString();
}

export function NotificationEmailDigestPanel({ snapshot }: { snapshot: AppNotificationSnapshot }) {
  const [status, setStatus] = useState<DigestStatus>("idle");
  const [preview, setPreview] = useState<NotificationEmailDigestPreview | null>(null);
  const [sendResult, setSendResult] = useState<NotificationEmailDigestSendResult | null>(null);
  const [triggerCheck, setTriggerCheck] = useState<NotificationEmailDigestTriggerCheckResult | null>(null);
  const [history, setHistory] = useState<NotificationEmailDigestHistory | null>(null);
  const [historyLoading, setHistoryLoading] = useState(false);
  const [historyError, setHistoryError] = useState<string | null>(null);

  const emailChoiceCount = useMemo(() => [
    snapshot.preferences.emailUrgent,
    snapshot.preferences.emailOverdue,
    snapshot.preferences.emailDueToday,
    snapshot.preferences.teamDigest,
  ].filter(Boolean).length, [snapshot.preferences]);

  const loadHistory = useCallback(async () => {
    setHistoryLoading(true);
    setHistoryError(null);
    try {
      const response = await apiGet<HistoryResponse>("/api/app-notifications/email-digest");
      setHistory(response.history);
    } catch (error: any) {
      setHistoryError(error?.message ?? "Digest history could not be loaded.");
    } finally {
      setHistoryLoading(false);
    }
  }, []);

  useEffect(() => {
    loadHistory();
  }, [loadHistory]);

  async function prepareDigest() {
    setStatus("preparing");
    setPreview(null);
    setSendResult(null);
    setTriggerCheck(null);
    try {
      const response = await apiPost<PreviewResponse>("/api/app-notifications/email-digest", { action: "PREVIEW" });
      setPreview(response.result);
      setStatus(response.result.status === "READY" ? "ready" : response.result.ok ? "idle" : "error");
    } catch (error: any) {
      setStatus("error");
      setPreview({
        ok: false,
        status: "SETUP_NEEDED",
        message: error?.message ?? "Notification email digest could not be prepared.",
        itemCount: 0,
        urgentCount: 0,
        watchCount: 0,
        previewLines: [],
        triggerLabels: [],
      });
    }
  }

  async function sendDigest() {
    const approved = window.confirm("Send this notification email now? Dispatch Spot will record this send attempt.");
    if (!approved) return;

    setStatus("sending");
    setSendResult(null);
    setTriggerCheck(null);
    try {
      const response = await apiPost<SendResponse>("/api/app-notifications/email-digest", { action: "SEND" });
      setSendResult(response.result);
      setStatus(response.result.ok && response.result.status === "SENT" ? "sent" : "error");
      await loadHistory();
    } catch (error: any) {
      setStatus("error");
      setSendResult({
        ok: false,
        status: "FAILED",
        message: error?.message ?? "Notification email could not be sent.",
        itemCount: 0,
        urgentCount: 0,
        watchCount: 0,
      });
      await loadHistory();
    }
  }

  async function checkDigestTriggers() {
    setStatus("preparing");
    setTriggerCheck(null);
    setSendResult(null);
    try {
      const response = await apiPost<TriggerCheckResponse>("/api/app-notifications/email-digest", { action: "CHECK_TRIGGERS" });
      setTriggerCheck(response.result);
      setStatus(response.result.status === "SENT" ? "sent" : response.result.ok ? "ready" : "error");
      await loadHistory();
    } catch (error: any) {
      setStatus("error");
      setTriggerCheck({
        ok: false,
        status: "FAILED",
        message: error?.message ?? "Digest trigger check could not run.",
        itemCount: 0,
        urgentCount: 0,
        watchCount: 0,
        schedulePlan: history?.schedulePlan ?? {
          status: "LOCKED",
          statusLabel: "Unavailable",
          message: "Digest trigger plan could not be loaded.",
          automationEnabled: false,
          manualApprovalRequired: true,
          nextWindowLabel: "Preview manually before sending.",
          guardrails: [],
          blockers: ["Refresh digest history, then try again."],
          rules: [],
          generatedAt: new Date().toISOString(),
        },
      });
    }
  }

  const readiness = snapshot.deliveryReadiness.email;
  const schedulePlan = history?.schedulePlan ?? triggerCheck?.schedulePlan ?? null;
  const latest = sendResult ?? triggerCheck ?? preview;
  const latestHistory = history?.records[0] ?? null;
  const schedulerHealth = history?.schedulerHealth ?? null;
  const schedulerRuns = history?.schedulerRuns ?? [];

  return (
    <section className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
      <div className="flex flex-col justify-between gap-3 sm:flex-row sm:items-start">
        <div>
          <h2 className="text-lg font-semibold text-slate-950">Email digest and triggers</h2>
          <p className="mt-1 text-sm leading-6 text-slate-500">
            Review the email Dispatch Spot would send from active alerts, then approve it when company email is ready.
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Link href="/company/integrations" className="rounded-2xl border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50">
            Open integrations
          </Link>
          <button
            type="button"
            onClick={loadHistory}
            disabled={historyLoading || status === "sending" || status === "preparing"}
            className="rounded-2xl border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:cursor-wait disabled:bg-slate-100"
          >
            {historyLoading ? "Refreshing..." : "Refresh history"}
          </button>
          <button
            type="button"
            onClick={prepareDigest}
            disabled={status === "preparing" || status === "sending"}
            className="rounded-2xl bg-slate-950 px-4 py-2 text-sm font-semibold text-white disabled:cursor-wait disabled:bg-slate-400"
          >
            {status === "preparing" ? "Preparing..." : "Preview email"}
          </button>
          <button
            type="button"
            onClick={checkDigestTriggers}
            disabled={status === "preparing" || status === "sending"}
            className="rounded-2xl border border-slate-900 px-4 py-2 text-sm font-semibold text-slate-900 hover:bg-slate-50 disabled:cursor-wait disabled:border-slate-300 disabled:text-slate-400"
          >
            Check trigger rules
          </button>
        </div>
      </div>

      <div className="mt-5 grid gap-3 md:grid-cols-5">
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">Email choices</div>
          <div className="mt-2 text-2xl font-semibold text-slate-950">{emailChoiceCount}</div>
          <p className="mt-1 text-xs leading-5 text-slate-500">Active choices in My alert settings.</p>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">Active alerts</div>
          <div className="mt-2 text-2xl font-semibold text-slate-950">{snapshot.itemCount}</div>
          <p className="mt-1 text-xs leading-5 text-slate-500">Alerts available for digest checks.</p>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">Needs attention</div>
          <div className="mt-2 text-2xl font-semibold text-rose-700">{snapshot.attentionCount}</div>
          <p className="mt-1 text-xs leading-5 text-slate-500">Urgent and watch alerts.</p>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">Email delivery</div>
          <div className="mt-2 text-sm font-semibold text-slate-950">{readinessLabel(readiness.status)}</div>
          <p className="mt-1 text-xs leading-5 text-slate-500">{readinessMessage(readiness.status)}</p>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">Last digest</div>
          <div className="mt-2 text-sm font-semibold text-slate-950">{historyError ? "Unavailable" : history?.summary.lastStatusLabel ?? "Loading..."}</div>
          <p className="mt-1 text-xs leading-5 text-slate-500">{history?.summary.lastAttemptedAt ? formatDate(history.summary.lastAttemptedAt) : "No digest has been sent yet."}</p>
        </div>
      </div>

      {schedulePlan ? (
        <div className="mt-5 rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <div className="text-sm font-semibold text-slate-950">Scheduled digest plan</div>
              <p className="mt-1 text-xs leading-5 text-slate-500">{schedulePlan.message}</p>
              <p className="mt-2 text-xs leading-5 text-slate-500">Next window: {schedulePlan.nextWindowLabel}</p>
            </div>
            <div className="flex flex-wrap gap-2 text-xs font-semibold">
              <span className={`rounded-full border px-3 py-1 ${schedulePlan.status === "READY" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : schedulePlan.status === "LOCKED" ? "border-sky-200 bg-sky-50 text-sky-700" : "border-amber-200 bg-amber-50 text-amber-700"}`}>{schedulePlan.statusLabel}</span>
              <span className="rounded-full border border-white bg-white px-3 py-1 text-slate-600">{schedulePlan.manualApprovalRequired ? "Manual approval first" : "Guarded automatic checks"}</span>
              <span className="rounded-full border border-white bg-white px-3 py-1 text-slate-600">{schedulePlan.webhookConfigured ? "Webhook protected" : "Webhook not configured"}</span>
            </div>
          </div>

          <div className="mt-4 grid gap-3 lg:grid-cols-2">
            <div className="rounded-2xl border border-slate-200 bg-white p-4">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Trigger rules</div>
              <div className="mt-3 space-y-2">
                {schedulePlan.rules.map((rule) => (
                  <div key={rule.key} className="rounded-xl border border-slate-100 bg-slate-50 p-3">
                    <div className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between">
                      <div className="text-sm font-semibold text-slate-900">{rule.label}</div>
                      <span className={`w-fit rounded-full px-2 py-1 text-[11px] font-semibold ${rule.status === "ACTIVE" ? "bg-emerald-100 text-emerald-700" : rule.status === "LOCKED" ? "bg-sky-100 text-sky-700" : rule.status === "PLANNED" ? "bg-blue-100 text-blue-700" : "bg-slate-100 text-slate-500"}`}>{rule.status}</span>
                    </div>
                    <p className="mt-1 text-xs leading-5 text-slate-500">{rule.cadence}</p>
                    <p className="mt-1 text-xs leading-5 text-slate-500">Guard: {rule.guardrail}</p>
                  </div>
                ))}
              </div>
            </div>

            <div className="rounded-2xl border border-slate-200 bg-white p-4">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Guardrails</div>
              <ul className="mt-3 space-y-2 text-xs leading-5 text-slate-600">
                {schedulePlan.guardrails.map((guardrail) => <li key={guardrail}>• {guardrail}</li>)}
              </ul>
              {schedulePlan.blockers.length ? (
                <div className="mt-4 rounded-xl border border-amber-200 bg-amber-50 p-3 text-xs leading-5 text-amber-800">
                  <div className="font-semibold">Before automation can run</div>
                  <ul className="mt-2 space-y-1">
                    {schedulePlan.blockers.map((blocker) => <li key={blocker}>• {blocker}</li>)}
                  </ul>
                </div>
              ) : null}
            </div>
          </div>
        </div>
      ) : null}

      {schedulerHealth ? (
        <div className="mt-5 rounded-2xl border border-slate-200 bg-white p-4">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <div className="text-sm font-semibold text-slate-950">Scheduler health</div>
              <p className="mt-1 text-xs leading-5 text-slate-500">{schedulerHealth.message}</p>
              <p className="mt-2 text-xs leading-5 text-slate-500">
                Last run: {schedulerHealth.lastRunAt ? formatDate(schedulerHealth.lastRunAt) : "No protected scheduler run recorded yet."}
              </p>
            </div>
            <div className="flex flex-wrap gap-2 text-xs font-semibold">
              <span className={`rounded-full border px-3 py-1 ${statusClass(schedulerHealth.status)}`}>{schedulerHealth.statusLabel}</span>
              <span className="rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-slate-600">
                {schedulerHealth.automationEnabled ? "Automation enabled" : "Automation locked"}
              </span>
              <span className="rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-slate-600">
                {schedulerHealth.webhookConfigured ? "Webhook configured" : "Webhook not configured"}
              </span>
            </div>
          </div>

          <div className="mt-4 grid gap-3 sm:grid-cols-3">
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-3">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Recent runs</div>
              <div className="mt-2 text-xl font-semibold text-slate-950">{schedulerHealth.recentRunCount}</div>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-3">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Needs attention</div>
              <div className="mt-2 text-xl font-semibold text-amber-700">{schedulerHealth.failedRunCount}</div>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-3">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Last status</div>
              <div className="mt-2 text-sm font-semibold text-slate-950">{schedulerHealth.lastRunStatusLabel ?? "No runs yet"}</div>
            </div>
          </div>

          {schedulerRuns.length ? (
            <div className="mt-4 space-y-3">
              {schedulerRuns.map((run) => (
                <div key={`${run.createdAt}-${run.status}`} className="rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm">
                  <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                    <div>
                      <div className="font-semibold text-slate-950">Scheduler check</div>
                      <div className="mt-1 text-xs leading-5 text-slate-500">
                        Started {formatDate(run.createdAt)}{run.completedAt ? ` · Completed ${formatDate(run.completedAt)}` : ""}
                      </div>
                    </div>
                    <span className={`w-fit rounded-full border px-3 py-1 text-xs font-semibold ${statusClass(run.status)}`}>{run.statusLabel}</span>
                  </div>
                  <p className="mt-2 text-xs leading-5 text-slate-600">{run.message}</p>
                  <div className="mt-3 flex flex-wrap gap-2 text-xs text-slate-500">
                    <span>{run.dryRun ? "Dry run" : "Live check"}</span>
                    <span>{run.usersChecked} user{run.usersChecked === 1 ? "" : "s"} checked</span>
                    <span>{run.sent} sent</span>
                    <span>{run.readyForApproval} ready</span>
                    <span>{run.skipped} skipped</span>
                    <span>{run.failed} failed</span>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="mt-4 rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-4 text-sm text-slate-500">
              No protected scheduler runs have been recorded for this workspace yet. Manual digest preview and approval still work.
            </div>
          )}
        </div>
      ) : null}

      {latest ? (
        <div className={`mt-5 rounded-2xl border p-4 text-sm leading-6 ${statusClass(latest.status)}`}>
          <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
            <div>
              <div className="font-semibold">{statusLabel(latest.status)}</div>
              <p className="mt-1">{latest.message}</p>
            </div>
            {latest.itemCount ? (
              <span className="rounded-full border border-white/70 bg-white/80 px-3 py-1 text-xs font-semibold text-slate-700">
                {latest.itemCount} item{latest.itemCount === 1 ? "" : "s"}
              </span>
            ) : null}
          </div>

          {"subject" in latest && latest.subject ? <div className="mt-3 text-xs font-semibold text-slate-600">Subject: {latest.subject}</div> : null}
          {preview?.triggerLabels.length ? <div className="mt-2 text-xs text-slate-600">Triggers: {preview.triggerLabels.join(", ")}</div> : null}
          {preview?.previewLines.length ? (
            <div className="mt-3 rounded-2xl border border-white/70 bg-white p-3 text-slate-700">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Preview</div>
              <ol className="mt-2 list-decimal space-y-1 pl-5 text-xs leading-5">
                {preview.previewLines.map((line) => <li key={line}>{line.replace(/^\d+\.\s*/, "")}</li>)}
              </ol>
            </div>
          ) : null}

          {preview?.status === "READY" && !sendResult ? (
            <button
              type="button"
              onClick={sendDigest}
              disabled={status === "sending" || status === "sent"}
              className="mt-4 rounded-2xl bg-slate-950 px-4 py-2 text-sm font-semibold text-white disabled:cursor-wait disabled:bg-slate-400"
            >
              {status === "sending" ? "Sending..." : "Send email now"}
            </button>
          ) : null}
          {sendResult?.logId ? <p className="mt-3 text-xs leading-5">Send record saved. Refresh history if the latest status does not update right away.</p> : null}
        </div>
      ) : null}

      <div className="mt-5 rounded-2xl border border-slate-200 bg-slate-50 p-4">
        <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
          <div>
            <div className="text-sm font-semibold text-slate-950">Digest send history</div>
            <p className="mt-1 text-xs leading-5 text-slate-500">
              {history?.summary.retryGuidance ?? "Loading recent digest history..."}
            </p>
          </div>
          {history ? (
            <div className="flex flex-wrap gap-2 text-xs font-semibold">
              <span className="rounded-full bg-white px-3 py-1 text-emerald-700">Sent {history.summary.sentCount}</span>
              <span className="rounded-full bg-white px-3 py-1 text-amber-700">Needs attention {history.summary.failedCount}</span>
              <span className="rounded-full bg-white px-3 py-1 text-sky-700">Waiting {history.summary.pendingCount}</span>
            </div>
          ) : null}
        </div>

        {historyError ? <div className="mt-3 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-700">{historyError}</div> : null}

        {latestHistory ? (
          <div className="mt-4 space-y-3">
            {history?.records.map((record) => (
              <div key={`${record.createdAt}-${record.subject}`} className="rounded-2xl border border-slate-200 bg-white p-4 text-sm">
                <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                  <div>
                    <div className="font-semibold text-slate-950">{record.subject}</div>
                    <div className="mt-1 text-xs leading-5 text-slate-500">To {record.recipient} · {formatDate(record.createdAt)}</div>
                  </div>
                  <span className={`w-fit rounded-full border px-3 py-1 text-xs font-semibold ${statusClass(record.status)}`}>{record.statusLabel}</span>
                </div>
                <p className="mt-2 text-xs leading-5 text-slate-600">{record.message}</p>
                <div className="mt-3 flex flex-wrap gap-2 text-xs text-slate-500">
                  <span>{record.itemCount} item{record.itemCount === 1 ? "" : "s"}</span>
                  <span>{record.urgentCount} urgent</span>
                  <span>{record.watchCount} watch</span>
                  {record.sentAt ? <span>Sent {formatDate(record.sentAt)}</span> : null}
                  {record.triggerLabels.length ? <span>Triggers: {record.triggerLabels.join(", ")}</span> : null}
                </div>
              </div>
            ))}
          </div>
        ) : !historyLoading ? (
          <div className="mt-4 rounded-2xl border border-dashed border-slate-300 bg-white p-4 text-sm text-slate-500">
            No digest sends have been recorded yet. Preview the digest, then send only when the preview looks useful.
          </div>
        ) : null}
      </div>
    </section>
  );
}
