"use client";

import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { X } from "@phosphor-icons/react";
import type { CustomerPayload } from "@/lib/customerAuth";

interface Toast { id: number; text: string; color: string; }

function ToastBanner({ toasts, onDismiss }: { toasts: Toast[]; onDismiss: (id: number) => void }) {
  if (!toasts.length) return null;
  return createPortal(
    <div className="fixed top-4 left-1/2 -translate-x-1/2 z-[9998] flex flex-col gap-2 w-[calc(100%-2rem)] max-w-sm">
      {toasts.map(t => (
        <div key={t.id} className={`flex items-center justify-between gap-3 px-4 py-3 rounded-2xl shadow-xl text-white text-sm font-semibold ${t.color}`}>
          <span>{t.text}</span>
          <button onClick={() => onDismiss(t.id)} className="flex-shrink-0 opacity-70 hover:opacity-100">
            <X size={14} weight="bold" />
          </button>
        </div>
      ))}
    </div>,
    document.body
  );
}

const STATUS_LABELS: Record<string, string> = {
  payment_review: "Vérification paiement",
  pending:        "En attente",
  confirmed:      "Confirmée",
  delivered:      "Livrée",
};

const STATUS_COLORS: Record<string, string> = {
  payment_review: "bg-orange-400",
  pending:        "bg-yellow-400",
  confirmed:      "bg-blue-500",
  delivered:      "bg-green-400",
};

export default function OrderStatusPoller({ customer }: { customer: CustomerPayload | null }) {
  const statusMap   = useRef<Map<number, string>>(new Map());
  const initialized = useRef(false);
  const [toasts, setToasts] = useState<Toast[]>([]);

  const addToast = (text: string, color: string) => {
    const id = Date.now();
    setToasts(t => [...t, { id, text, color }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 6000);
  };

  useEffect(() => {
    if (!customer) return;

    // Ask for browser notification permission
    if ("Notification" in window && Notification.permission === "default") {
      Notification.requestPermission();
    }

    // Restore status map from sessionStorage so navigation doesn't lose history
    const STORAGE_KEY = "asli_order_statuses";
    try {
      const stored = sessionStorage.getItem(STORAGE_KEY);
      if (stored) {
        const parsed = JSON.parse(stored) as Record<string, string>;
        Object.entries(parsed).forEach(([id, status]) => {
          statusMap.current.set(Number(id), status);
        });
        initialized.current = true;
      }
    } catch { /* ignore */ }

    const persist = () => {
      const obj: Record<string, string> = {};
      statusMap.current.forEach((v, k) => { obj[String(k)] = v; });
      try { sessionStorage.setItem(STORAGE_KEY, JSON.stringify(obj)); } catch { /* ignore */ }
    };

    const poll = async () => {
      const h = new Date().getHours();
      if (h < 8) return;
      if (document.visibilityState !== "visible") return;

      try {
        const res = await fetch("/api/orders");
        if (!res.ok) return;
        const fresh: { id: number; status: string }[] = await res.json();

        // First run (no sessionStorage): seed map silently
        if (!initialized.current) {
          fresh.forEach(o => statusMap.current.set(o.id, o.status));
          initialized.current = true;
          persist();
          return;
        }

        fresh.forEach(o => {
          const prev = statusMap.current.get(o.id);
          if (prev !== undefined && prev !== o.status) {
            const label = STATUS_LABELS[o.status] ?? o.status;
            const color = STATUS_COLORS[o.status] ?? "bg-brand-dark";
            const msg   = `Commande #${String(o.id).padStart(4, "0")} — ${label}`;

            if ("Notification" in window && Notification.permission === "granted") {
              new Notification("Asli Food", { body: msg, icon: "/logo.png" });
            }

            addToast(msg, color);

            window.dispatchEvent(new CustomEvent("order-status-change", {
              detail: { orderId: o.id, newStatus: o.status, label, color, msg },
            }));
          }
          statusMap.current.set(o.id, o.status);
        });

        persist();
      } catch { /* ignore network errors */ }
    };

    poll();
    const interval = setInterval(poll, 30_000);
    document.addEventListener("visibilitychange", poll);

    return () => {
      clearInterval(interval);
      document.removeEventListener("visibilitychange", poll);
      initialized.current = false;
      statusMap.current.clear();
    };
  }, [customer]);

  return (
    <ToastBanner toasts={toasts} onDismiss={id => setToasts(t => t.filter(x => x.id !== id))} />
  );
}
