"use client";

import { useEffect } from "react";
import { useAtom } from "jotai";
import { Button } from "@heroui/react";
import { useLocale } from "next-intl";
import { Link } from "@/i18n/navigation";
import { useSessionActions } from "@/auth/session-provider";
import { BaseModal } from "@/components/modal";
import { archivedAccountModalOpenAtom } from "@/components/state/archivedAccountAtom";
import { resetArchivedAccountHandling } from "@/lib/handle-archived-account";

/**
 * Shown when Laravel returns 403 + is_archived (CheckArchivedUser middleware).
 * Session cookie is cleared in handleArchivedAccount; React session is cleared when the modal opens.
 */
export default function ArchivedAccountModalHost() {
  const [open, setOpen] = useAtom(archivedAccountModalOpenAtom);
  const { clearSession } = useSessionActions();
  const locale = useLocale();
  const isAr = (locale || "ar").toLowerCase().startsWith("ar");

  useEffect(() => {
    if (open) clearSession();
  }, [open, clearSession]);

  const onOpenChange = (next: boolean) => {
    setOpen(next);
    if (!next) resetArchivedAccountHandling();
  };

  const title = isAr ? "حساب متوقف" : "Account suspended";
  const bodyAr =
    "ان حسابك متوقف اذا كان هناك خطأ ما يمكنك التواصل مع مشرفي الموقع";
  const bodyEn =
    "Your account has been suspended. If you believe this is a mistake, please contact the site administrators.";
  const contactLabel = isAr ? "تواصل معنا" : "Contact us";
  const cancelLabel = isAr ? "إغلاق" : "Close";

  return (
    <BaseModal
      isOpen={open}
      onOpenChange={onOpenChange}
      title={title}
      isDismissable={false}
      footer={
        <div className="flex flex-col sm:flex-row gap-2 w-full justify-end">
          <Button
            variant="bordered"
            className="border-slate-300"
            onPress={() => onOpenChange(false)}
          >
            {cancelLabel}
          </Button>
          <Link
            href="/contact"
            onClick={() => onOpenChange(false)}
            className="inline-flex items-center justify-center min-h-10 px-4 rounded-lg bg-[#0f5132] text-white font-semibold text-sm hover:bg-[#0d4429] transition"
          >
            {contactLabel}
          </Link>
        </div>
      }
    >
      <p className="text-slate-700 leading-7 text-sm sm:text-base">
        {isAr ? bodyAr : bodyEn}
      </p>
    </BaseModal>
  );
}
