"use client";

import { useState } from "react";
import Link from "next/link";
import { apiPost } from "@/lib/api";
import type { NotificationDeliveryReadiness, UrgentTextPreviewResult, UrgentTextSendResult } from "@/types";

type TestResult = { ok: boolean; status: string; message: string; logId?: string };
type TestResponse = { result: TestResult };
type TextPreviewResponse = { result: UrgentTextPreviewResult };
type TextSendResponse = { result: UrgentTextSendResult };

function statusClass(status: string) {
  if (status === "CONNECTED") return "border-emerald-200 bg-emerald-50 text-emerald-700";
  if (status === "READY_SOON") return "border-blue-200 bg-blue-50 text-blue-700";
  if (status === "OFF") return "border-slate-200 bg-slate-50 text-slate-500";
  return "border-amber-200 bg-amber-50 text-amber-700";
}

function readableStatus(status: string) {
  if (status === "CONNECTED") return "Ready";
  if (status === "READY_SOON") return "Ready to prepare";
  if (status === "OFF") return "Off";
  return "Needs setup";
}

export function NotificationDeliveryPanel({ readiness }: { readiness: NotificationDeliveryReadiness }) {
  const [testStatus, setTestStatus] = useState<"idle" | "sending" | "sent" | "error">("idle");
  const [message, setMessage] = useState<string | null>(null);
  const [textStatus, setTextStatus] = useState<"idle" | "preparing" | "ready" | "sending" | "sent" | "error">("idle");
  const [textPreview, setTextPreview] = useState<UrgentTextPreviewResult | null>(null);
  const [textSend, setTextSend] = useState<UrgentTextSendResult | null>(null);

  async function sendTestEmail() {
    setTestStatus("sending");
    setMessage("Sending a test alert to your email...");
    try {
      const response = await apiPost<TestResponse>("/api/app-notifications/test-email", {});
      setTestStatus(response.result.ok ? "sent" : "error");
      setMessage(response.result.message);
    } catch (error: any) {
      setTestStatus("error");
      setMessage(error?.message ?? "Test alert could not be sent.");
    }
  }

  async function prepareUrgentText() {
    setTextStatus("preparing");
    setTextPreview(null);
    setTextSend(null);
    try {
      const response = await apiPost<TextPreviewResponse>("/api/app-notifications/urgent-text-preview", {});
      setTextPreview(response.result);
      setTextStatus(response.result.ok ? "ready" : "error");
    } catch (error: any) {
      setTextStatus("error");
      setTextPreview({ ok: false, status: "SETUP_NEEDED", message: error?.message ?? "Urgent text preview could not be prepared." });
    }
  }

  async function sendUrgentText() {
    if (!textPreview?.body) return;
    const approved = window.confirm("Send this urgent text now? Dispatch Spot will record this send attempt.");
    if (!approved) return;

    setTextStatus("sending");
    setTextSend(null);
    try {
      const response = await apiPost<TextSendResponse>("/api/app-notifications/send-urgent-text", {});
      setTextSend(response.result);
      setTextStatus(response.result.ok && response.result.status === "SENT" ? "sent" : "error");
    } catch (error: any) {
      setTextStatus("error");
      setTextSend({ ok: false, status: "FAILED", message: error?.message ?? "Urgent text could not be sent." });
    }
  }

  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">Delivery status</h2>
          <p className="mt-1 text-sm leading-6 text-slate-500">This shows whether alerts can leave Dispatch Spot. Delivery choices stay here; provider setup stays in Integrations.</p>
        </div>
        <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>
      </div>

      <div className="mt-5 grid gap-3 md:grid-cols-2">
        {[readiness.email, readiness.text].map((channel) => {
          const isText = channel.label === "Text alerts";
          return (
            <div key={channel.label} className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <h3 className="text-sm font-semibold text-slate-950">{channel.label}</h3>
                  {channel.connectedLabel ? <p className="mt-1 text-xs font-medium text-slate-500">{channel.connectedLabel}</p> : null}
                </div>
                <span className={`rounded-full border px-2.5 py-1 text-[11px] font-semibold ${statusClass(channel.status)}`}>{readableStatus(channel.status)}</span>
              </div>
              <p className="mt-3 text-sm leading-6 text-slate-600">{channel.body}</p>
              {channel.canSendTest ? (
                <button type="button" onClick={sendTestEmail} disabled={testStatus === "sending"} 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">
                  {testStatus === "sending" ? "Sending..." : "Send test email"}
                </button>
              ) : null}
              {isText && channel.status !== "OFF" ? (
                <button type="button" onClick={prepareUrgentText} disabled={textStatus === "preparing" || textStatus === "sending"} className="mt-4 rounded-2xl border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 disabled:cursor-wait disabled:text-slate-400">
                  {textStatus === "preparing" ? "Preparing..." : "Preview urgent text"}
                </button>
              ) : null}
            </div>
          );
        })}
      </div>

      {message ? (
        <div className={`mt-4 rounded-2xl border p-4 text-sm leading-6 ${testStatus === "sent" ? "border-emerald-200 bg-emerald-50 text-emerald-800" : testStatus === "error" ? "border-rose-200 bg-rose-50 text-rose-800" : "border-slate-200 bg-slate-50 text-slate-700"}`}>{message}</div>
      ) : null}

      {textPreview ? (
        <div className={`mt-4 rounded-2xl border p-4 text-sm leading-6 ${textStatus === "ready" || textStatus === "sending" || textStatus === "sent" ? "border-blue-200 bg-blue-50 text-blue-800" : "border-amber-200 bg-amber-50 text-amber-800"}`}>
          <div className="font-semibold">{textPreview.message}</div>
          {textPreview.toPhoneNumber ? <div className="mt-1 text-xs">To: {textPreview.toPhoneNumber}</div> : null}
          {textPreview.body ? <div className="mt-3 rounded-2xl border border-white/70 bg-white p-3 text-slate-700">{textPreview.body}</div> : null}
          {textPreview.status === "READY" && textPreview.body ? (
            <button
              type="button"
              onClick={sendUrgentText}
              disabled={textStatus === "sending" || textStatus === "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"
            >
              {textStatus === "sending" ? "Sending..." : textStatus === "sent" ? "Sent" : "Send urgent text"}
            </button>
          ) : null}
          <p className="mt-3 text-xs leading-5">Dispatch Spot will only send after you preview and approve the urgent text.</p>
        </div>
      ) : null}

      {textSend ? (
        <div className={`mt-4 rounded-2xl border p-4 text-sm leading-6 ${textSend.status === "SENT" ? "border-emerald-200 bg-emerald-50 text-emerald-800" : "border-rose-200 bg-rose-50 text-rose-800"}`}>
          <div className="font-semibold">{textSend.message}</div>
          {textSend.logId ? <div className="mt-1 text-xs">Send record saved.</div> : null}
        </div>
      ) : null}
    </section>
  );
}
