"use client";
import React, { useMemo, useState, useEffect, useRef } from "react";
import { BaseModal } from "@/components/modal";
import DynamicButton from "@/components/button";
import {
  InputOtp,
  Form,
  Spinner,
  Input,
  Popover,
  PopoverTrigger,
  PopoverContent,
} from "@heroui/react";
import CompleteProfileModal from "./completeModal";
import { phonelogin, phoneloginOtp } from "@/actions/auth/login";
import handleSuccessfulLogin from "@/utlis/handle-successful-login";
import { getOrRequestFcmToken } from "@/lib/firebase/messaging";

import {
  LoginContextProvider,
  useLoginContext,
} from "@/(pages)/login/login-context";
import useLastSession from "@/auth/use-last-session";
import { useSessionActions } from "@/auth/session-provider";
import { useAppToast } from "@/app/[lang]/providers";
import { useRouter } from "next/navigation";
import { useLocale, useTranslations } from "next-intl";
import {
  defaultCountries,
  FlagImage,
  parseCountry,
} from "react-international-phone";
import { arabicCountries, arabicCountryLabels } from "@/config/arabCountries";
import { handleArchivedAccount } from "@/lib/handle-archived-account";

type CountryCodeOption = {
  iso2: string;
  dialCode: string;
  name: string;
  searchText: string;
};

const englishCountryNameByIso = new Map(
  defaultCountries.map((country) => {
    const parsed = parseCountry(country);
    return [parsed.iso2, parsed.name];
  }),
);

const normalizeCountrySearch = (value: string) =>
  value
    .trim()
    .toLowerCase()
    .replace(/[٠-٩]/g, (digit) => String("٠١٢٣٤٥٦٧٨٩".indexOf(digit)))
    .replace(/[۰-۹]/g, (digit) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(digit)))
    .replace(/\+/g, "")
    .replace(/\s+/g, "");

function LoginModalContent({ onClose }: { onClose: () => void }) {
  const t = useTranslations("AUTH");
  const locale = useLocale();
  const router = useRouter();
  const { setSession } = useSessionActions();
  const [otp, setOtp] = useState("");
  const [loadingType, setLoadingType] = useState<"sms" | "whatsapp" | null>(
    null,
  );
  const [resendSeconds, setResendSeconds] = useState(0);
  const [tempToken, setTempToken] = useState<string | null>(null);
  const [tempUser, setTempUser] = useState<any>(null);
  const [loadingCodeOtp, setLoadingCodeOtp] = useState(false);
  const [showCompleteModal, setShowCompleteModal] = useState(false);
  const [selectedCountryIso, setSelectedCountryIso] = useState("sa");
  const [countrySearchValue, setCountrySearchValue] = useState("");
  const [isCountryCodeOpen, setIsCountryCodeOpen] = useState(false);
  const [localPhone, setLocalPhone] = useState("");
  const otpInputRef = useRef<HTMLInputElement>(null);
  const countrySearchInputRef = useRef<HTMLInputElement>(null);
  const toast = useAppToast();
  const isArabic = locale === "ar";
  const phoneInputDir: "rtl" | "ltr" = localPhone
    ? "ltr"
    : isArabic
      ? "rtl"
      : "ltr";
  const phoneInputAlignClass = localPhone
    ? "text-left"
    : isArabic
      ? "text-right"
      : "text-left";

  const { path, setPath, phoneNumber, setPhoneNumber } = useLoginContext();

  const countryCodeOptions: CountryCodeOption[] = useMemo(
    () =>
      (locale === "ar" ? arabicCountries : defaultCountries)
        .map((country) => {
          const parsed = parseCountry(country);
          const englishName = englishCountryNameByIso.get(parsed.iso2) || "";
          const arabicName = arabicCountryLabels[parsed.iso2] || "";
          return {
            iso2: parsed.iso2,
            dialCode: parsed.dialCode,
            name: parsed.name,
            searchText: `${parsed.name} ${englishName} ${arabicName} ${parsed.dialCode} +${parsed.dialCode} ${parsed.iso2}`,
          };
        })
        .sort((a, b) => a.name.localeCompare(b.name, locale || "en")),
    [locale],
  );

  const getDialCodeByIso = (iso2: string) =>
    countryCodeOptions.find((option) => option.iso2 === iso2)?.dialCode ||
    "966";

  const selectedCountryOption = useMemo(
    () =>
      countryCodeOptions.find((option) => option.iso2 === selectedCountryIso) ||
      null,
    [countryCodeOptions, selectedCountryIso],
  );
  const filteredCountryCodeOptions = useMemo(() => {
    const normalizedSearch = normalizeCountrySearch(countrySearchValue);
    if (!normalizedSearch) return countryCodeOptions;

    return countryCodeOptions.filter((option) =>
      normalizeCountrySearch(option.searchText).includes(normalizedSearch),
    );
  }, [countryCodeOptions, countrySearchValue]);
  const sharedPhoneFieldWrapperClass =
    "h-12 rounded-xl border border-slate-200 bg-white shadow-none transition-colors data-[hover=true]:border-slate-300 data-[focus=true]:border-[#0f5132] group-data-[focus=true]:border-[#0f5132] group-data-[focus=true]:bg-white";
  const countryCodeTriggerClass = `flex h-12 w-full items-center justify-between rounded-xl border border-slate-200 bg-white px-3 text-sm shadow-none transition-colors hover:border-slate-300 focus:outline-none focus:ring-2 focus:ring-[#0f5132]/15 ${isCountryCodeOpen ? "border-[#0f5132]" : ""}`;
  const countrySearchEmptyLabel = isArabic
    ? "لا توجد نتائج"
    : "No results found";

  useEffect(() => {
    const digits = (phoneNumber || "").replace(/\D/g, "");
    if (!digits) {
      setSelectedCountryIso("sa");
      setLocalPhone("");
      return;
    }

    const sortedOptions = [...countryCodeOptions].sort(
      (a, b) => b.dialCode.length - a.dialCode.length,
    );
    const matched = sortedOptions.find((opt) =>
      digits.startsWith(opt.dialCode),
    );

    if (matched) {
      setSelectedCountryIso(matched.iso2);
      setLocalPhone(digits.slice(matched.dialCode.length));
    } else {
      setLocalPhone(digits);
    }
  }, [countryCodeOptions, phoneNumber]);

  const handleCountryCodeChange = (key: React.Key | null) => {
    const selected = typeof key === "string" ? key : "sa";
    setSelectedCountryIso(selected);
    setIsCountryCodeOpen(false);
    setCountrySearchValue("");
    const dialCode = getDialCodeByIso(selected);
    const cleaned = localPhone.replace(/\D/g, "");
    setPhoneNumber(`${dialCode}${cleaned}`);
  };

  const handleLocalPhoneChange = (value: string) => {
    const cleaned = value.replace(/\D/g, "");
    setLocalPhone(cleaned);
    const dialCode = getDialCodeByIso(selectedCountryIso);
    setPhoneNumber(`${dialCode}${cleaned}`);
  };

  const handlePhoneSubmit = async (type_message: "sms" | "whatsapp") => {
    if (resendSeconds > 0) return;
    const cleaned = phoneNumber?.replace(/\D/g, "");
    if (!cleaned || cleaned.length < 9) {
      return toast.warning(t("enter_valid_phone"));
    }
    const isSaudi = cleaned.startsWith("966");
    if (type_message === "sms" && !isSaudi) {
      return toast.warning(t("sms_saudi_only"));
    }

    try {
      setLoadingType(type_message);
      const formData = new FormData();
      formData.append(
        "phone",
        phoneNumber.startsWith("+") ? phoneNumber : `+${phoneNumber}`,
      );
      formData.append("type_message", type_message);
      const res = await phonelogin(formData);
      if (res?.success) {
        toast.success(t("code_sent"));
        setResendSeconds(60);
        setPath("phoneVerification");
      } else if (
        (res?.data as { is_archived?: boolean } | null)?.is_archived
      ) {
        void handleArchivedAccount();
        onClose();
      } else {
        toast.error(res?.message || t("send_failed"));
      }
    } catch (err: any) {
      console.error("Login error:", err);
      toast.error(t("send_failed"));
    } finally {
      setLoadingType(null);
    }
  };

  const handleOtpSubmit = async (e?: React.FormEvent<HTMLFormElement>) => {
    if (e) e.preventDefault();
    try {
      setLoadingCodeOtp(true);
      const formData = new FormData();
      formData.append("user_type", "user");
      formData.append(
        "phone",
        phoneNumber.startsWith("+") ? phoneNumber : `+${phoneNumber}`,
      );
      formData.append("code", otp);

      const { token: fcmToken, reason: fcmReason } =
        await getOrRequestFcmToken();
      if (fcmToken) {
        formData.append("fcm_token", fcmToken);
      }
      console.log(
        "[loginModal] FCM token for OTP:",
        fcmToken ? "PRESENT" : "MISSING",
        fcmReason,
      );

      const res = await phoneloginOtp(formData);
      if (res?.success) {
        localStorage.setItem("ataya_logged_in", "true");

        await handleSuccessfulLogin(res);

        const accessToken =
          (res?.data as any)?.access_token ?? (res?.data as any)?.token;
        if (res?.data?.user?.profile_complete === false) {
          setShowCompleteModal(true);
          setTempToken(accessToken ?? null);
          setTempUser(res.data.user);
        } else {
          const user = res.data?.user;
          if (user && accessToken) {
            setSession({
              ...user,
              access_token: accessToken,
              token_type: res.data?.token_type ?? "Bearer",
              expires_in: res.data?.expires_in ?? 0,
            });
          }
          toast.success(t("login_success"));
          onClose();
          router.refresh();
        }
      } else if (
        (res?.data as { is_archived?: boolean } | null)?.is_archived
      ) {
        void handleArchivedAccount();
        onClose();
      } else {
        toast.error(res?.message || t("invalid_code"));
      }
    } catch (err: any) {
      console.error("OTP error:", err);
      toast.error(t("verify_failed"));
    } finally {
      setLoadingCodeOtp(false);
    }
  };

  useEffect(() => {
    if (path === "phoneVerification" && otpInputRef.current) {
      setTimeout(() => otpInputRef.current?.focus(), 300);
    }
  }, [path]);

  useEffect(() => {
    if (resendSeconds <= 0) return;
    const id = window.setInterval(() => {
      setResendSeconds((s) => (s > 0 ? s - 1 : 0));
    }, 1000);
    return () => window.clearInterval(id);
  }, [resendSeconds]);

  useEffect(() => {
    if (otp.length === 4) {
      handleOtpSubmit();
    }
  }, [otp]);

  useEffect(() => {
    if (!isCountryCodeOpen) return;
    const timer = window.setTimeout(() => {
      countrySearchInputRef.current?.focus();
    }, 50);

    return () => window.clearTimeout(timer);
  }, [isCountryCodeOpen]);

  return (
    <>
      <BaseModal
        isOpen
        onClose={onClose}
        title={path === "phoneLogin" ? t("login_title") : t("otp_title")}
        placement="center"
        contentClassName="w-full max-w-[450px] !py-0 rounded-xl space-y-1 text-primary"
      >
        {path === "phoneLogin" ? (
          <div className="space-y-4 text-start">
            <p className="text-sm text-gray-600">{t("login_description")}</p>

            <div className="space-y-2">
              <label className="text-sm font-medium text-slate-700">
                {t("phone_number")}
              </label>
              <div
                className="grid grid-cols-[168px_minmax(0,1fr)] items-start gap-2 sm:grid-cols-[180px_minmax(0,1fr)]"
                dir="ltr"
              >
                <div className="min-w-0">
                  <Popover
                    placement="bottom"
                    isOpen={isCountryCodeOpen}
                    onOpenChange={(open) => {
                      setIsCountryCodeOpen(open);
                      if (!open) {
                        setCountrySearchValue("");
                      }
                    }}
                  >
                    <PopoverTrigger>
                      <button
                        type="button"
                        className={countryCodeTriggerClass}
                        aria-label={t("country_code")}
                      >
                        {selectedCountryOption ? (
                          <div className="flex min-w-0 items-center gap-2">
                            <FlagImage
                              iso2={selectedCountryOption.iso2}
                              size={16}
                              className="shrink-0 rounded-sm"
                            />
                            <span
                              dir="ltr"
                              className="shrink-0 font-semibold text-slate-700"
                            >
                              +{selectedCountryOption.dialCode}
                            </span>
                          </div>
                        ) : (
                          <span className="truncate text-slate-400">
                            {t("country_code")}
                          </span>
                        )}
                        <svg
                          className={`h-4 w-4 shrink-0 text-slate-500 transition-transform ${isCountryCodeOpen ? "rotate-180" : ""}`}
                          viewBox="0 0 20 20"
                          fill="currentColor"
                          aria-hidden="true"
                        >
                          <path
                            fillRule="evenodd"
                            d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.51a.75.75 0 0 1-1.08 0l-4.25-4.51a.75.75 0 0 1 .02-1.06Z"
                            clipRule="evenodd"
                          />
                        </svg>
                      </button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[320px] max-w-[calc(100vw-3rem)] rounded-xl border border-slate-200 bg-white p-2 shadow-lg">
                      <div className="w-full space-y-2">
                        <Input
                          ref={countrySearchInputRef}
                          aria-label={t("country_code")}
                          placeholder={t("country_code")}
                          value={countrySearchValue}
                          onValueChange={setCountrySearchValue}
                          variant="bordered"
                          size="sm"
                          autoComplete="off"
                          classNames={{
                            inputWrapper:
                              "h-10 rounded-lg border border-slate-200 bg-white shadow-none data-[hover=true]:border-slate-300 data-[focus=true]:border-[#0f5132]",
                            input:
                              "text-sm text-slate-800 placeholder:text-slate-400",
                          }}
                        />
                        <div className="max-h-72 overflow-y-auto">
                          {filteredCountryCodeOptions.length ? (
                            <div className="space-y-1">
                              {filteredCountryCodeOptions.map((item) => {
                                const isSelected =
                                  item.iso2 === selectedCountryIso;

                                return (
                                  <button
                                    key={item.iso2}
                                    type="button"
                                    onClick={() =>
                                      handleCountryCodeChange(item.iso2)
                                    }
                                    className={`flex w-full items-center gap-2 rounded-lg px-3 py-2 text-start transition-colors ${isSelected ? "bg-[#0f5132]/10" : "hover:bg-slate-100"}`}
                                  >
                                    <FlagImage
                                      iso2={item.iso2}
                                      size={16}
                                      className="shrink-0 rounded-sm"
                                    />
                                    <span className="min-w-0 flex-1 truncate text-sm font-semibold text-slate-800">
                                      {item.name}
                                    </span>
                                    <span
                                      dir="ltr"
                                      className="shrink-0 text-xs font-medium text-slate-500"
                                    >
                                      +{item.dialCode}
                                    </span>
                                  </button>
                                );
                              })}
                            </div>
                          ) : (
                            <div className="px-3 py-6 text-center text-sm text-slate-500">
                              {countrySearchEmptyLabel}
                            </div>
                          )}
                        </div>
                      </div>
                    </PopoverContent>
                  </Popover>
                </div>
                <Input
                  type="tel"
                  inputMode="numeric"
                  aria-label={t("phone_number")}
                  placeholder={t("phone_number")}
                  value={localPhone}
                  onValueChange={handleLocalPhoneChange}
                  variant="bordered"
                  size="sm"
                  dir={phoneInputDir}
                  className="min-w-0 text-start"
                  classNames={{
                    inputWrapper: sharedPhoneFieldWrapperClass,
                    input: `text-sm text-start text-slate-800 [unicode-bidi:plaintext] ${phoneInputAlignClass}`,
                  }}
                />
              </div>
            </div>

            <div className="flex flex-row gap-3 w-full">
              <DynamicButton
                fullWidth
                isDisabled={loadingType !== null || resendSeconds > 0}
                onClick={() => handlePhoneSubmit("whatsapp")}
                className={`py-2 rounded-lg px-4 flex items-center justify-center ${
                  loadingType === "whatsapp"
                    ? "bg-green-500/70 cursor-not-allowed"
                    : "bg-green-600 hover:bg-green-700"
                } text-white transition`}
              >
                {loadingType === "whatsapp" ? (
                  <>
                    <Spinner color="white" size="sm" />
                    <span className="ml-2">{t("sending")}...</span>
                  </>
                ) : resendSeconds > 0 ? (
                  `${t("via_whatsapp")} (${resendSeconds}s)`
                ) : (
                  t("via_whatsapp")
                )}
              </DynamicButton>

              {phoneNumber.replace(/\D/g, "").startsWith("966") && (
                <DynamicButton
                  fullWidth
                  isDisabled={loadingType !== null || resendSeconds > 0}
                  onClick={() => handlePhoneSubmit("sms")}
                  className={`py-2 rounded-lg px-4 flex items-center justify-center ${
                    loadingType === "sms"
                      ? "bg-primary/70 cursor-not-allowed"
                      : "bg-primary hover:bg-primary/80"
                  } text-white transition`}
                >
                  {loadingType === "sms" ? (
                    <>
                      <Spinner color="white" size="sm" />
                      <span className="ml-2">{t("sending")}...</span>
                    </>
                  ) : resendSeconds > 0 ? (
                    `${t("via_sms")} (${resendSeconds}s)`
                  ) : (
                    t("via_sms")
                  )}
                </DynamicButton>
              )}
            </div>
          </div>
        ) : (
          <Form
            className="flex w-full flex-col items-center gap-4 text-right"
            onSubmit={handleOtpSubmit}
          >
            <p className="text-sm">
              {t("otp_sent_to")}{" "}
              <strong dir="ltr">
                {phoneNumber.startsWith("+") ? phoneNumber : `+${phoneNumber}`}
              </strong>
            </p>

            <InputOtp
              isRequired
              name="otp"
              aria-label="OTP input field"
              length={4}
              dir="ltr"
              ref={otpInputRef}
              value={otp}
              onValueChange={setOtp}
              placeholder="-"
            />

            <div className="flex flex-col gap-3 w-full">
              <div className="flex flex-row gap-3 w-full">
                <DynamicButton
                  fullWidth
                  onClick={handleOtpSubmit}
                  isDisabled={loadingCodeOtp}
                  className={`py-2 rounded-lg px-4 flex items-center justify-center ${
                    loadingCodeOtp
                      ? "bg-primary/70 cursor-not-allowed"
                      : "bg-primary hover:bg-primary/80"
                  } text-white transition`}
                >
                  {loadingCodeOtp ? (
                    <>
                      <Spinner color="white" size="sm" />
                      <span className="ml-2">{t("verifying")}...</span>
                    </>
                  ) : (
                    t("otp_next")
                  )}
                </DynamicButton>

                <DynamicButton
                  fullWidth
                  onClick={() => handlePhoneSubmit("sms")}
                  isDisabled={resendSeconds > 0 || loadingType !== null}
                  className="bg-slate-200 text-gray-600 py-2 px-4 rounded-lg"
                >
                  {resendSeconds > 0
                    ? `${t("otp_resend")} (${resendSeconds}s)`
                    : t("otp_resend")}
                </DynamicButton>
              </div>
              <DynamicButton
                fullWidth
                variant="bordered"
                onClick={() => setPath("phoneLogin")}
                isDisabled={loadingCodeOtp}
                className="border-slate-300 text-slate-600 py-2 px-4 rounded-lg hover:bg-slate-100"
              >
                {t("back_to_login")}
              </DynamicButton>
            </div>
          </Form>
        )}
      </BaseModal>

      {showCompleteModal && (
        <CompleteProfileModal
          isOpen={showCompleteModal}
          token={tempToken}
          user={tempUser}
          onClose={(updatedUser?: any) => {
            setShowCompleteModal(false);
            const token = tempToken;
            const user = updatedUser || tempUser;
            if (user && token) {
              setSession({
                ...user,
                access_token: token,
                token_type: "Bearer",
                expires_in: 0,
                profile_complete: true,
              });
            }
            toast.success(t("login_success"));
            onClose();
            router.refresh();
          }}
        />
      )}
    </>
  );
}

export default function LoginModal({
  open,
  onClose,
}: {
  open: boolean;
  onClose: () => void;
}) {
  const lastSession = useLastSession();

  if (!open) return null;

  return (
    <LoginContextProvider lastSession={lastSession}>
      <LoginModalContent onClose={onClose} />
    </LoginContextProvider>
  );
}
