"use client";

import { useEffect, useState, type FormEvent } from "react";
import type { NotificationChannel, NotificationLog, NotificationTemplate } from "@/lib/notifications";
import { csrfFetch } from "@/lib/client-csrf";

const demoValues: Record<string, string> = {
  name: "Aparna",
  bookingType: "class",
  item: "Hatha Yoga Flow",
  date: "2026-07-21",
  mode: "Studio",
  amount: "3999",
  paymentStatus: "paid",
  receiptId: "HWA-2026-DEMO",
  message: "Please arrive 15 minutes early.",
  packageName: "8 Class Yoga Pass",
  remainingCredits: "7",
  expiresAt: "2026-12-31",
};

function previewTemplate(body: string) {
  return body.replaceAll(/\{\{(\w+)\}\}/g, (_match, key: string) => demoValues[key] ?? `{{${key}}}`);
}

type ReminderCandidate = {
  bookingId: string;
  name: string;
  phone: string;
  item: string;
  date: string;
  mode: string;
  alreadyLogged: boolean;
};

type MembershipReminder = {
  passId: string;
  kind: "payment" | "renewal";
  name: string;
  phone: string;
  packageName: string;
  expiresAt: string;
  amountDue: number;
  alreadyLogged: boolean;
};

export function AdminNotifications() {
  const [templates, setTemplates] = useState<NotificationTemplate[]>([]);
  const [logs, setLogs] = useState<NotificationLog[]>([]);
  const [reminders, setReminders] = useState<ReminderCandidate[]>([]);
  const [membershipReminders, setMembershipReminders] = useState<MembershipReminder[]>([]);
  const [selectedId, setSelectedId] = useState("");
  const [recipient, setRecipient] = useState("member@example.com");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  const selectedTemplate = templates.find((template) => template.id === selectedId) ?? templates[0];

  async function loadNotifications() {
    setLoading(true);
    const [response, reminderResponse] = await Promise.all([
      fetch("/api/notifications/templates", { cache: "no-store" }),
      fetch("/api/notifications/reminders", { cache: "no-store" }),
    ]);
    const data = (await response.json()) as { templates: NotificationTemplate[]; logs: NotificationLog[] };
    const reminderData = (await reminderResponse.json()) as {
      reminders: ReminderCandidate[];
      membershipReminders?: MembershipReminder[];
    };
    setTemplates(data.templates);
    setLogs(data.logs);
    setReminders(reminderData.reminders);
    setMembershipReminders(reminderData.membershipReminders ?? []);
    setSelectedId((current) => current || data.templates[0]?.id || "");
    setLoading(false);
  }

  useEffect(() => {
    let active = true;

    async function loadInitialNotifications() {
      const [response, reminderResponse] = await Promise.all([
        fetch("/api/notifications/templates", { cache: "no-store" }),
        fetch("/api/notifications/reminders", { cache: "no-store" }),
      ]);
      const data = (await response.json()) as { templates: NotificationTemplate[]; logs: NotificationLog[] };
      const reminderData = (await reminderResponse.json()) as {
        reminders: ReminderCandidate[];
        membershipReminders?: MembershipReminder[];
      };

      if (active) {
        setTemplates(data.templates);
        setLogs(data.logs);
        setReminders(reminderData.reminders);
        setMembershipReminders(reminderData.membershipReminders ?? []);
        setSelectedId(data.templates[0]?.id || "");
        setLoading(false);
      }
    }

    void loadInitialNotifications();

    return () => {
      active = false;
    };
  }, []);

  async function saveTemplate(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();

    if (!selectedTemplate) return;

    setSaving(true);
    await csrfFetch(`/api/notifications/templates/${selectedTemplate.id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(selectedTemplate),
    });
    await loadNotifications();
    setSaving(false);
  }

  async function simulateSend() {
    if (!selectedTemplate) return;

    setSaving(true);
    await csrfFetch("/api/notifications/send", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ templateId: selectedTemplate.id, recipient }),
    });
    await loadNotifications();
    setSaving(false);
  }

  async function sendReminder(bookingId: string) {
    setSaving(true);
    await csrfFetch("/api/notifications/reminders", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ bookingId }),
    });
    await loadNotifications();
    setSaving(false);
  }

  function updateSelectedTemplate(updates: Partial<NotificationTemplate>) {
    setTemplates((current) =>
      current.map((template) => (template.id === selectedTemplate?.id ? { ...template, ...updates } : template)),
    );
  }

  const fieldClass =
    "mt-2 w-full rounded-lg border border-[#cfc4b2] bg-[#f7f3ea] px-4 py-3 text-[#17211c] outline-none transition focus:border-[#274739] focus:ring-2 focus:ring-[#274739]/15";

  return (
    <div className="mt-8 rounded-lg border border-[#d9d0bf] bg-white p-6 shadow-sm">
      <div className="flex flex-col justify-between gap-3 border-b border-[#d9d0bf] pb-5 sm:flex-row sm:items-center">
        <div>
          <h2 className="text-2xl font-semibold text-[#274739]">Notification templates</h2>
          <p className="mt-1 text-sm text-[#5e675f]">
            Email and WhatsApp delivery for confirmations, receipts, reminders, and balance alerts.
          </p>
        </div>
        <button
          type="button"
          onClick={() => void loadNotifications()}
          className="rounded-full bg-[#274739] px-4 py-2 text-sm font-semibold text-white"
        >
          {loading ? "Loading..." : "Refresh"}
        </button>
      </div>

      {selectedTemplate ? (
        <div className="mt-6 grid gap-6 lg:grid-cols-[0.9fr_1.1fr]">
          <aside className="grid gap-2">
            {templates.map((template) => (
              <button
                key={template.id}
                type="button"
                onClick={() => setSelectedId(template.id)}
                className={`rounded-lg border px-4 py-3 text-left text-sm font-semibold transition ${
                  selectedTemplate.id === template.id
                    ? "border-[#274739] bg-[#274739] text-white"
                    : "border-[#d9d0bf] bg-[#f7f3ea] text-[#274739]"
                }`}
              >
                <span className="block">{template.name}</span>
                <span className="mt-1 block text-xs uppercase tracking-[0.14em] opacity-75">{template.channel}</span>
              </button>
            ))}
          </aside>

          <div>
            <form onSubmit={saveTemplate} className="grid gap-4 rounded-lg bg-[#eee6d7] p-5">
              <label className="text-sm font-semibold text-[#274739]">
                Name
                <input
                  className={fieldClass}
                  value={selectedTemplate.name}
                  onChange={(event) => updateSelectedTemplate({ name: event.target.value })}
                />
              </label>
              <label className="text-sm font-semibold text-[#274739]">
                Channel
                <select
                  className={fieldClass}
                  value={selectedTemplate.channel}
                  onChange={(event) =>
                    updateSelectedTemplate({ channel: event.target.value as NotificationChannel })
                  }
                >
                  <option value="email">Email</option>
                  <option value="whatsapp">WhatsApp</option>
                </select>
              </label>
              <label className="text-sm font-semibold text-[#274739]">
                Subject
                <input
                  className={fieldClass}
                  value={selectedTemplate.subject}
                  onChange={(event) => updateSelectedTemplate({ subject: event.target.value })}
                />
              </label>
              <label className="text-sm font-semibold text-[#274739]">
                Body
                <textarea
                  className={`${fieldClass} min-h-36`}
                  value={selectedTemplate.body}
                  onChange={(event) => updateSelectedTemplate({ body: event.target.value })}
                />
              </label>
              <div className="rounded-lg bg-white p-4">
                <p className="text-xs font-bold uppercase tracking-[0.16em] text-[#9a6b2d]">Preview</p>
                <p className="mt-2 text-sm leading-6 text-[#5e675f]">{previewTemplate(selectedTemplate.body)}</p>
              </div>
              <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
                <button
                  type="submit"
                  disabled={saving}
                  className="rounded-full bg-[#274739] px-5 py-3 text-sm font-bold text-white disabled:opacity-60"
                >
                  {saving ? "Saving..." : "Save template"}
                </button>
                <input
                  className="rounded-full border border-[#cfc4b2] bg-white px-4 py-3 text-sm text-[#17211c]"
                  value={recipient}
                  onChange={(event) => setRecipient(event.target.value)}
                />
                <button
                  type="button"
                  disabled={saving}
                  onClick={() => void simulateSend()}
                  className="rounded-full border border-[#cfc4b2] px-5 py-3 text-sm font-bold text-[#274739] disabled:opacity-60"
                >
                  Send test
                </button>
              </div>
            </form>
          </div>
        </div>
      ) : (
        <p className="py-6 text-sm text-[#5e675f]">No templates available.</p>
      )}

      <div className="mt-6 rounded-lg border border-[#d9d0bf] bg-white p-5">
        <h3 className="text-xl font-semibold text-[#274739]">Upcoming reminders</h3>
        <p className="mt-1 text-sm text-[#5e675f]">Confirmed bookings in the next two days.</p>
        {reminders.length === 0 ? (
          <p className="mt-4 text-sm text-[#5e675f]">No upcoming confirmed booking reminders found.</p>
        ) : (
          <div className="admin-table-wrap !mt-4">
            <div className="admin-table admin-table--reminders" role="table">
              <div className="admin-table-head" role="row">
                <div role="columnheader" className="lg:text-center">
                  Item
                </div>
                <div role="columnheader" className="lg:text-center">
                  Customer
                </div>
                <div role="columnheader" className="lg:text-center">
                  When
                </div>
                <div role="columnheader" className="lg:text-center">
                  Actions
                </div>
              </div>
              <div className="admin-table-body">
                {reminders.slice(0, 5).map((reminder, index) => (
                  <div
                    key={reminder.bookingId}
                    className={`admin-table-row border-l-[#d9d0bf] ${index % 2 === 1 ? "admin-table-row--zebra" : ""}`}
                    role="row"
                  >
                    <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                      <p className="min-w-0 truncate text-sm font-semibold text-[#274739]" title={reminder.item}>
                        {reminder.item}
                      </p>
                    </div>
                    <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                      <p className="min-w-0 truncate text-sm font-medium text-[#274739]" title={reminder.name}>
                        <span className="admin-table-mobile-label">Customer</span>
                        {reminder.name}
                      </p>
                      <p className="min-w-0 truncate text-xs text-[#5e675f]" title={reminder.phone}>
                        {reminder.phone}
                      </p>
                    </div>
                    <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                      <p className="min-w-0 truncate text-sm text-[#274739]" title={reminder.date}>
                        <span className="admin-table-mobile-label">When</span>
                        {reminder.date}
                      </p>
                      <p className="min-w-0 truncate text-xs text-[#5e675f]">{reminder.mode}</p>
                    </div>
                    <div className="admin-table-cell admin-table-cell--actions lg:justify-center" role="cell">
                      <button
                        type="button"
                        disabled={saving}
                        onClick={() => void sendReminder(reminder.bookingId)}
                        className="inline-flex min-h-10 items-center justify-center rounded-md border border-[#cfc4b2] px-2.5 py-2 text-xs font-semibold text-[#274739] disabled:opacity-60 lg:min-h-8 lg:px-2 lg:py-1 lg:text-[11px]"
                      >
                        {reminder.alreadyLogged ? "Send again" : "Send reminder"}
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>

      <div className="mt-6 rounded-lg border border-[#d9d0bf] bg-white p-5">
        <h3 className="text-xl font-semibold text-[#274739]">Payment and renewal messages</h3>
        <p className="mt-1 text-sm text-[#5e675f]">
          WhatsApp goes out once a day for the last 3 days before a package expires. If a balance is still due, both messages continue each day until it is paid.
        </p>
        {membershipReminders.length === 0 ? (
          <p className="mt-4 text-sm text-[#5e675f]">No payment or renewal messages are due today.</p>
        ) : (
          <ul className="mt-4 grid gap-2">
            {membershipReminders.map((reminder) => (
              <li key={`${reminder.kind}-${reminder.passId}`} className="rounded-lg bg-[#f7f3ea] px-3 py-2 text-sm text-[#274739]">
                <span className="font-semibold">{reminder.kind === "payment" ? "Payment" : "Renewal"}</span>
                {" · "}
                {reminder.name} · {reminder.packageName} · expires {reminder.expiresAt}
                {reminder.kind === "payment" ? ` · Rs. ${reminder.amountDue} due` : ""}
                {reminder.alreadyLogged ? " · sent" : ""}
              </li>
            ))}
          </ul>
        )}
      </div>

      <div className="mt-6 rounded-lg border border-[#d9d0bf] bg-white p-5">
        <h3 className="text-xl font-semibold text-[#274739]">Notification log</h3>
        {logs.length === 0 ? (
          <p className="mt-4 text-sm text-[#5e675f]">No notifications yet.</p>
        ) : (
          <div className="admin-table-wrap !mt-4">
            <div className="admin-table admin-table--logs" role="table">
              <div className="admin-table-head" role="row">
                <div role="columnheader" className="lg:text-center">
                  Template
                </div>
                <div role="columnheader" className="lg:text-center">
                  Channel
                </div>
                <div role="columnheader" className="lg:text-center">
                  Status
                </div>
                <div role="columnheader" className="lg:text-center">
                  Recipient
                </div>
                <div role="columnheader" className="lg:text-center">
                  Preview
                </div>
              </div>
              <div className="admin-table-body">
                {logs.slice(0, 5).map((log, index) => (
                  <div
                    key={log.id}
                    className={`admin-table-row border-l-[#d9d0bf] ${index % 2 === 1 ? "admin-table-row--zebra" : ""}`}
                    role="row"
                  >
                    <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                      <p className="min-w-0 truncate text-sm font-semibold text-[#274739]" title={log.templateName}>
                        {log.templateName}
                      </p>
                      {log.error ? (
                        <p className="min-w-0 truncate text-xs font-semibold text-[#7a2e36]" title={log.error}>
                          {log.error}
                        </p>
                      ) : null}
                    </div>
                    <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                      <p className="min-w-0 truncate text-sm uppercase text-[#274739]">
                        <span className="admin-table-mobile-label">Channel</span>
                        {log.channel}
                      </p>
                    </div>
                    <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                      <p className="min-w-0 truncate text-sm capitalize text-[#274739]">
                        <span className="admin-table-mobile-label">Status</span>
                        {log.status}
                      </p>
                    </div>
                    <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                      <p className="min-w-0 truncate text-sm text-[#274739]" title={log.recipient}>
                        <span className="admin-table-mobile-label">To</span>
                        {log.recipient}
                      </p>
                      <p className="min-w-0 truncate text-xs text-[#5e675f]" title={log.provider}>
                        {log.provider}
                        {log.providerId ? ` / ${log.providerId}` : ""}
                      </p>
                    </div>
                    <div className="admin-table-cell min-w-0 lg:text-center" role="cell">
                      <p className="min-w-0 truncate text-sm text-[#5e675f]" title={log.preview}>
                        <span className="admin-table-mobile-label">Preview</span>
                        {log.preview}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
