// src/pages/MyAccount.jsx
import React, { useEffect, useMemo, useState, useCallback } from "react";
import { Axiosinstance } from "../services/auth/Axiosinstance";
import { useToast } from "../components/ToastProvider";
import { Button, PageShell, PageActions, Grid2, cn } from "../components/ui";
import { LuRefreshCcw } from "react-icons/lu";

import useCooldownAction from "../hooks/useCooldownAction";
import useCountdownTimer from "../hooks/useCountdownTimer";

import ProfileFormCard from "../components/account/ProfileFormCard";
import AccountChecklistCard from "../components/account/AccountChecklistCard";
import VerifyCodeModal from "../components/account/VerifyCodeModal";

import { getErrMsg, mapVerifyType, maskEmail, maskPhone } from "../utils/account";

function MyAccount() {
  const { success, error: toastError, info, warning } = useToast();

  const [me, setMe] = useState(null);

  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [saving, setSaving] = useState(false);

  // form fields
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [fullName, setFullName] = useState("");
  const [nationalId, setNationalId] = useState("");

  // verify modal
  const [verifyOpen, setVerifyOpen] = useState(false);
  const [verifyType, setVerifyType] = useState(null); // "email" | "phone" | null
  const [code, setCode] = useState("");
  const [sendingCode, setSendingCode] = useState(false);
  const [verifyingCode, setVerifyingCode] = useState(false);

  const { timer, start: startTimer, reset: resetTimer } = useCountdownTimer();

  const PURPOSE = "signup";

  const isEmailVerified = !!me?.is_email_verified;
  const isPhoneVerified = !!me?.is_phone_verified;

  const is2FAEnabled = !!me?.two_factor_enabled;
  const twoFAChannel = me?.two_factor_channel || "";

  // identity locks
  const fullNameLocked = !!String(me?.full_name || "").trim();
  const nationalIdLocked = !!String(me?.national_id || "").trim();

  const canEditFullName = !fullNameLocked;
  const canEditNationalId = !nationalIdLocked;

  const showSaveButton = useMemo(
    () => !loading && (!fullNameLocked || !nationalIdLocked),
    [loading, fullNameLocked, nationalIdLocked]
  );

  const hasIdentity = useMemo(
    () => !!String(fullName || "").trim() && !!String(nationalId || "").trim(),
    [fullName, nationalId]
  );

  const fetchMe = useCallback(
    async ({ silent = false, mode = "init" } = {}) => {
      if (mode === "refresh") setRefreshing(true);
      else setLoading(true);

      try {
        const res = await Axiosinstance.get("accounts/me/");
        const data = res?.data || null;
        setMe(data);

        setUsername(data?.username || "");
        setEmail(data?.email || "");
        setPhone(data?.phone || "");
        setFullName(data?.full_name || "");
        setNationalId(data?.national_id || "");

        if (!silent) info("اطلاعات حساب بروزرسانی شد.", { title: "پروفایل" });
      } catch (e) {
        toastError(getErrMsg(e, "خطا در دریافت اطلاعات حساب"), { title: "پروفایل" });
      } finally {
        if (mode === "refresh") setRefreshing(false);
        else setLoading(false);
      }
    },
    [info, toastError]
  );

  useEffect(() => {
    fetchMe({ silent: true, mode: "init" });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const closeVerifyModal = () => {
    setVerifyOpen(false);
    setVerifyType(null);
    setCode("");
    resetTimer();
  };

  const getTargetByType = (type) => {
    if (type === "email") return (email || "").trim();
    return (phone || "").trim();
  };

  const sendCode = useCallback(
    async (type, opts = { resetTimer: true }) => {
      if (!type) return false;

      const normalized = type === "email" ? "email" : "phone";
      const { channel, label } = mapVerifyType(normalized);
      const target = getTargetByType(normalized);

      if (!target) {
        warning(`لطفاً ${label} را وارد کنید.`, { title: "کد تایید" });
        return false;
      }

      setSendingCode(true);
      try {
        await Axiosinstance.post("accounts/request-code/", {
          channel,
          target,
          purpose: PURPOSE,
        });

        success(`کد تایید به ${label} ارسال شد ✅`, { title: "کد تایید" });

        if (opts.resetTimer) startTimer(120);
        return true;
      } catch (e) {
        toastError(getErrMsg(e, "خطا در ارسال کد تایید"), { title: "کد تایید" });
        return false;
      } finally {
        setSendingCode(false);
      }
    },
    [PURPOSE, startTimer, success, toastError, warning, email, phone]
  );

  const openVerifyModal = async (type) => {
    const normalized = type === "email" ? "email" : "phone";
    setVerifyType(normalized);
    setVerifyOpen(true);
    setCode("");

    const ok = await sendCode(normalized, { resetTimer: true });
    if (!ok) resetTimer();
  };

  const confirmCode = async () => {
    if (!verifyType) return;

    const c = String(code || "").trim();
    if (!c) {
      warning("کد را وارد کنید.", { title: "تایید کد" });
      return;
    }

    const normalized = verifyType === "email" ? "email" : "phone";
    const { channel, label } = mapVerifyType(normalized);
    const target = getTargetByType(normalized);

    if (!target) {
      warning(`لطفاً ${label} را وارد کنید.`, { title: "تایید کد" });
      return;
    }

    setVerifyingCode(true);
    try {
      await Axiosinstance.post("accounts/verify-code/", {
        channel,
        target,
        code: c,
        purpose: PURPOSE,
      });

      success(`${label} با موفقیت تایید شد ✅`, { title: "تایید کد" });
      closeVerifyModal();

      await fetchMe({ silent: true, mode: "refresh" });
    } catch (e) {
      toastError(getErrMsg(e, "کد وارد شده صحیح نیست یا منقضی شده است"), { title: "تایید کد" });
    } finally {
      setVerifyingCode(false);
    }
  };

  const saveProfile = async () => {
    if (fullNameLocked && nationalIdLocked) return;

    if (!fullNameLocked && !String(fullName || "").trim()) {
      warning("لطفاً نام و نام خانوادگی را وارد کنید.", { title: "پروفایل" });
      return;
    }
    if (!nationalIdLocked && !String(nationalId || "").trim()) {
      warning("لطفاً کد ملی را وارد کنید.", { title: "پروفایل" });
      return;
    }

    setSaving(true);
    try {
      const payload = {};
      if (!fullNameLocked) payload.full_name = String(fullName || "").trim();
      if (!nationalIdLocked) payload.national_id = String(nationalId || "").trim();

      await Axiosinstance.patch("accounts/profile/", payload);

      success("اطلاعات هویتی با موفقیت ثبت شد ✅", { title: "پروفایل" });
      await fetchMe({ silent: true, mode: "refresh" });
    } catch (e) {
      toastError(getErrMsg(e, "خطا در ثبت اطلاعات"), { title: "پروفایل" });
    } finally {
      setSaving(false);
    }
  };

  const isBusyAny =
    loading || refreshing || saving || sendingCode || verifyingCode;

  const refreshAction = useCooldownAction({
    cooldownMs: 3000,
    title: "پروفایل",
    isBusy: isBusyAny,
    busyMessage: "در حال بروزرسانی...",
    busyToast: info,
    onRun: async () => fetchMe({ silent: false, mode: "refresh" }),
  });

  const saveAction = useCooldownAction({
    cooldownMs: 3000,
    title: "ثبت اطلاعات",
    isBusy: isBusyAny,
    busyMessage: "در حال ثبت اطلاعات...",
    busyToast: info,
    onRun: saveProfile,
  });

  return (
    <PageShell
      title="پروفایل من"
      subtitle="تغییر و مدیریت اطلاعات حساب کاربری"
      actions={
        <PageActions>
          <Button
            variant="outline"
            onClick={refreshAction.run}
            disabled={refreshAction.disabled}
            title={
              refreshAction.leftMs > 0
                ? `تا ${Math.ceil(refreshAction.leftMs / 1000)} ثانیه دیگر`
                : "به‌روزرسانی"
            }
            leftIcon={
              <LuRefreshCcw
                className={cn(
                  "w-4 h-4 text-[#43BEFF] dark:text-white",
                  refreshing ? "animate-spin" : ""
                )}
              />
            }
          >
            {refreshing ? "به‌روزرسانی..." : "به‌روزرسانی"}
          </Button>
        </PageActions>
      }
    >
      <Grid2>
        <ProfileFormCard
          loading={loading}
          username={username}
          email={email}
          phone={phone}
          fullName={fullName}
          nationalId={nationalId}
          isEmailVerified={isEmailVerified}
          isPhoneVerified={isPhoneVerified}
          canEditFullName={canEditFullName}
          canEditNationalId={canEditNationalId}
          setFullName={setFullName}
          setNationalId={setNationalId}
          onVerifyEmail={() => openVerifyModal("email")}
          onVerifyPhone={() => openVerifyModal("phone")}
          showSaveButton={showSaveButton}
          onSave={saveAction.run}
          saveDisabled={saveAction.disabled}
          saving={saving}
          saveLeftMs={saveAction.leftMs}
        />

        <AccountChecklistCard
          isEmailVerified={isEmailVerified}
          isPhoneVerified={isPhoneVerified}
          hasIdentity={hasIdentity}
          emailSubtitle={me?.email ? maskEmail(me.email) : ""}
          phoneSubtitle={me?.phone ? maskPhone(me.phone) : ""}
          onVerifyEmail={() => openVerifyModal("email")}
          onVerifyPhone={() => openVerifyModal("phone")}
          showSaveHint={!hasIdentity && showSaveButton}
          is2FAEnabled={is2FAEnabled}
          twoFAChannel={twoFAChannel}
          userId={me?.id}
        />
      </Grid2>

      <VerifyCodeModal
        open={verifyOpen}
        onClose={closeVerifyModal}
        verifyType={verifyType}
        email={email}
        phone={phone}
        code={code}
        setCode={setCode}
        timer={timer}
        sendingCode={sendingCode}
        verifyingCode={verifyingCode}
        onResend={() => sendCode(verifyType, { resetTimer: true })}
        onConfirm={confirmCode}
      />
    </PageShell>
  );
}

export default MyAccount;
