"use client";
import React, { useEffect, useRef, useState } from "react";

import Image from "next/image";
import ProgressGlowBar from "../components/Header/ProgressGlowBar";
import { InternalButton } from "../components/ui/Button";
import { OverviewContent } from "../components/profile/OverviewContent";

import HistoryPanel from "../components/profile/History";
import AffiliatePanel from "../components/profile/Affliate";
import "./style.css";

type TabId =
  | "overview"
  | "trade-listings"
  | "settings"
  | "history"
  | "affiliate";

type TabItem = {
  id: TabId;
  label: string;
  component: React.ReactNode;
};

import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import {
  getHomePage,
  getRefCode,
  setUserName,
  uploadUserImage,
} from "../lib/api/profile";
import { updateUser } from "../store/authSlice";
import { useAppDispatch } from "../lib/hooks";
import { updateSession } from "../lib/api/inventory";
import { redirect } from "next/navigation";
import Link from "next/link";
import NotAvailable from "../components/ui/NotAvailable";
import AlertModal from "../components/ui/AlertModal";

interface AuthState {
  user: unknown; // adjust type as needed
  status: string;
}

export const formatNumber = (num: any) => {
  if (!num) return 0;

  if (num >= 1_000_000) {
    return (num / 1_000_000).toFixed(1).replace(/\.0$/, "") + "M";
  }

  if (num >= 1_000) {
    return (num / 1_000).toFixed(1).replace(/\.0$/, "") + "K";
  }

  return num;
};

const ProfilePage: React.FC = () => {
  const [activeTab, setActiveTab] = useState<TabId>("overview");
  const [copied, setCopied] = useState(false);
  const [historySubTab, setHistorySubTab] = useState<
    | "balance"
    | "shipping"
    | "packs"
    | "games record"
    | "sportsbook record"
    | null
  >("balance");
  const user = useSelector((state: any) => state.auth.user) as User | null;
  if (!user) {
    redirect("/");
  }
  const status = useSelector(
    (state: { auth: AuthState }) => state?.auth?.status,
  );
  const inputRef = useRef<HTMLInputElement | null>(null);
  const [uploading, setUploading] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [editing, setEditing] = useState(false);
  const [name, setName] = useState(user?.name);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [homeData, setHomeData] = useState<any>(null);
  const [loadingProfileData, setLoadingProfileData] = useState(false);
  const [errorProfileLoad, setErrorProfileLaod] = useState<string | null>(null);
  const [deposit, setDeposit] = useState(0);
  const [withdraw, setWithdraw] = useState(0);
  const [refCode, setRefCode] = useState<string | null>(null);
  const [refUrl, setRefUrl] = useState<string | null>(null);
  const [referralCode, setReferralCode] = useState<string | null>(null);
  const [referralUrl, setReferralUrl] = useState<string | null>(null);
  const [loadingRef, setLoadingRef] = useState(false);

  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"success" | "error">("success");
  const [modalMsg, setModalMsg] = useState("");
  const chatOpen = useSelector((state: any) => state.ui.chatOpen);

  const dispatch = useAppDispatch();

  // const handleCopy = (text: any) => {
  //   navigator.clipboard.writeText(text);
  //   setCopied(true);
  //   setTimeout(() => setCopied(false), 1500);
  // };

  const handleCopy = (url: any) => {
    if (!url) return;

    // Replace the domain with localhost
    const newUrl = url.replace(
      "https://dev.tcgwin.com",
      "http://localhost:3000",
    );

    navigator.clipboard.writeText(url);
    setCopied(true);
  };

  const onRefData = (code: string | null, url: string | null) => {
    console.log("code", code, "url from affliate api", url);
    setRefCode(code);
    setRefUrl(url);
  };

  const TABS: TabItem[] = [
    {
      id: "overview",
      label: "Overview",
      component: (
        <OverviewContent
          user={user}
          homeData={homeData}
          loadingProfileData={loadingProfileData}
          errorProfileLoad={errorProfileLoad}
        />
      ),
    },
    // {
    //   id: "trade-listings",
    //   label: "Trade Listings",
    //   component: <TradeListings user={user} />,
    // },
    // { id: "settings", label: "Settings", component: <SettingsPanel /> },
    {
      id: "history",
      label: "History",
      component: (
        <HistoryPanel
          historySubTab={historySubTab}
          onSubTabChange={setHistorySubTab}
          onTotals={(d: any, w: any) => {
            setDeposit(d);
            setWithdraw(w);
          }}
        />
      ),
    },
    {
      id: "affiliate",
      label: "Affiliate",
      component: <AffiliatePanel onRefData={onRefData} />,
    },
  ];

  async function logout() {
    await fetch("/api/auth/logout", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ f: 1 }),
    }).then(() => {
      window.location.href = "/";
    });
  }

  //Check Session

  const handleGenerateRef = async () => {
    if (!user?.userId || !user?.token) return;

    try {
      setLoadingRef(true);
      const res = await getRefCode(user.userId, user.token);

      setReferralCode(res.ref);
      setReferralUrl(res.url);
    } catch (e) {
      console.log(e);
    } finally {
      setLoadingRef(false);
    }
  };

  const onFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !user) return;

    // optional: simple validation
    if (!file.type.startsWith("image/")) {
      setErrorMessage("Please select an image file.");
      return;
    }

    setUploading(true);
    setErrorMessage("");

    try {
      const res = await uploadUserImage(user?.userId, file, user.token);
      console.log("res", res);
      if (res.error || !res.path) {
        setErrorMessage(res.message || "Upload failed");
        setModalType("error"); // or "login" if you have a custom type
        setModalMsg(res.message);
        setModalOpen(true);
        return;
      }
      if (res.resp === "success") {
        setModalType("success"); // or "login" if you have a custom type
        setModalMsg(res.message);
        setModalOpen(true);
        updateSession({ image: res.path });
        dispatch(updateUser({ image: res.path }));
      }
    } catch (err: any) {
      setErrorMessage(err?.message || "Upload failed");
    } finally {
      setUploading(false);

      // ✅ important: reset input so selecting same file again triggers change
      e.target.value = "";
    }
  };

  const saveName = async () => {
    if (!user) return;
    if (!name?.trim() || name === user?.name) {
      setEditing(false);
      setError("");
      return;
    }

    setLoading(true);
    setError("");

    const res = await setUserName(user?.userId, name.trim(), user?.token);

    if (res.resp === "error") {
      setModalType("error"); // or "login" if you have a custom type
      setModalMsg(res.msg);
      setModalOpen(true);
      setLoading(false);
      return;
    }
    if (res.resp === "success") {
      setModalType("success"); // or "login" if you have a custom type
      setModalMsg(res.msg || "Name upated successfully");
      setModalOpen(true);
      // updateName();
      updateSession({ name: name });
      dispatch(updateUser({ name: name }));
      setEditing(false);
      setLoading(false);
    }
  };

  const onPick = () => inputRef.current?.click();

  useEffect(() => {
    if (!user?.userId || !user?.token) return;
    (async () => {
      setLoadingProfileData(true);
      try {
        const res = await getHomePage(user.userId, user.token);
        const data = res.data;
        if (res.resp === "success") {
          setHomeData(data);
          setLoadingProfileData(false);

          const updatedLevel = {
            lavel: data.level?.lavel ?? 0,
            xp: String(data.level?.xp ?? 0),
            next: data.level?.next ?? 0,
          };

          // ✅ session update (level update)
          updateSession({
            level: updatedLevel,
          });

          // ✅ redux update (level update)
          dispatch(
            updateUser({
              level: updatedLevel,
            }),
          );
        }
      } catch (e: any) {
        console.log("homepage error", e);
        setLoadingProfileData(false);
        setErrorProfileLaod(e.message);
      }
    })();
  }, [user?.userId, user?.token]);

  if (!user) return;

  return (
    <main className="min-h-screen mt-3 text-white">
      {user?.activeMode === "gems" ? (
        <NotAvailable />
      ) : (
        <>
          {/* Top bar with back + title */}
          <div className="container mx-auto ">
            <div
              className={`
    mx-auto
    flex
    flex-col
    gap-2 md:gap-4
    lg:px-0 lg:pt-6
    ${chatOpen ? "2xl:flex-row" : "xl:flex-row 2xl:"}
  `}
            >
              {/* LEFT COLUMN – profile + balance */}
              <aside
                className={`${chatOpen ? "w-full 2xl:w-85 " : "2xl:w-85"} space-y-4 relative rounded-lg transition-all
    duration-300
    ease-in-out `}
              >
                <div className="flex items-center mb-4 md:mb-10 mt-3 md:mt-0 2xl:mb-10 gap-4">
                  <button
                    // onClick={() => setIsOpenCardModal(true)}
                    className="cursor-pointer text-xs md:text-sm p-2 px-4 font-extrabold text-white bg-(--color-gray) hover:text-white italic font-sofia transition"
                  >
                    &lt; BACK
                  </button>
                  <h1 className="text-sm md:text-2xl font-extrabold italic ">
                    PROFILE
                  </h1>
                </div>

                {/* Profile card */}
                <section className="p-3 bg-(--color-naviBlue)">
                  {loadingProfileData ? (
                    <div className="flex w-full h-14 items-center justify-center">
                      <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
                    </div>
                  ) : (
                    <div className="flex items-center gap-3">
                      {!editing && (
                        <div className="relative h-16 w-16 overflow-hidden rounded-full">
                          <div className="flex flex-col items-start gap-2">
                            <button
                              type="button"
                              onClick={onPick}
                              className="relative cursor-pointer h-16 w-16 overflow-hidden rounded-full border border-white/10 hover:opacity-90"
                              aria-label="Change profile image"
                              disabled={uploading}
                            >
                              <Image
                                src={user.image || "/images/profile/img.svg"}
                                alt="Avatar"
                                fill
                                className="object-cover"
                                unoptimized // ✅ use if backend image host isn't in next.config yet
                              />

                              {uploading && (
                                <div className="absolute inset-0 grid place-items-center bg-black/60 text-xs font-semibold text-white">
                                  Uploading...
                                </div>
                              )}
                            </button>

                            <input
                              ref={inputRef}
                              type="file"
                              accept="image/*"
                              className="hidden"
                              onChange={onFileChange}
                            />

                            {errorMessage && (
                              <p className="text-xs text-red-400">
                                {errorMessage}
                              </p>
                            )}
                          </div>
                        </div>
                      )}

                      <div className="flex flex-1 items-center justify-between gap-3">
                        <div>
                          {!editing ? (
                            <p
                              onClick={() => setEditing(true)}
                              className="cursor-pointer text-sm duration-300 md:text-xl 2xl:text-3xl font-sofia font-semibold hover:opacity-80"
                              title="Click to edit name"
                            >
                              {user?.name}
                            </p>
                          ) : (
                            <div className="flex items-center gap-2">
                              <input
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                                autoFocus
                                className="  border border-(--color-gray) px-2 py-1 text-sm md:text-xl font-sofia text-white outline-none"
                                onKeyDown={(e) => {
                                  if (e.key === "Enter") saveName();
                                  if (e.key === "Escape") {
                                    setEditing(false);
                                    setName(user.name);
                                  }
                                }}
                              />

                              <button
                                onClick={saveName}
                                disabled={loading}
                                className="text-xs md:text-sm px-3 py-1  border border-transparent duration-300 bg-[var(--color-blue)] hover:bg-[var(--color-naviBlue)] hover:bg-blue-700 disabled:opacity-50"
                              >
                                {loading ? "Saving..." : "Save"}
                              </button>

                              <button
                                onClick={() => {
                                  setEditing(false);
                                  setName(user.name);
                                }}
                                className="text-xs md:text-sm px-3 py-1  border border-transparent duration-300 bg-[var(--color-gray)] hover:bg-transparent hover:border-[var(--color-gray)] "
                              >
                                Cancel
                              </button>
                            </div>
                          )}

                          {error && (
                            <p className="text-xs text-red-400 mt-1">{error}</p>
                          )}
                        </div>
                        {!editing && (
                          <div className="flex pt-1 items-center justify-center rounded-full border border-[var(--color-blue)] px-2 py-0.5 font-sofia text-xs font-semibold">
                            {formatNumber(homeData?.level?.xp ?? 0)} XP
                          </div>
                        )}
                      </div>
                    </div>
                  )}

                  {/* XP bar */}
                  <div className="mt-5 space-y-1">
                    <ProgressGlowBar
                      value={Number(homeData?.level?.xp ?? 0)} // current XP
                      max={homeData?.level?.next ?? 0} // XP needed for next level
                      showLabel
                      label={`${formatNumber(homeData?.level?.xp ?? 0)} XP`}
                      user={user}
                    />

                    <div className="flex items-center justify-between text-[11px]">
                      <div className="flex items-center gap-1">
                        <span className="font-bold text-xs font-sofia uppercase md:text-sm 2xl:text-base text-white">
                          {`Level ${homeData?.level?.lavel ?? 0}`}
                        </span>
                      </div>
                      <div className="flex items-center gap-1 text-[11px]">
                        <span className=" font-bold text-xs font-sofia uppercase md:text-sm 2xl:text-base text-white">
                          {`Level ${(homeData?.level?.lavel ?? 0) + 1}`}
                          {/* {`Level ${formatNumber(homeData?.level?.next ?? 0)}`} */}
                        </span>
                        {homeData?.level?.lavel !== "100" && (
                          <span className="text-xs md:text-sm 2xl:text-base text-(--color-naturalGray) font-sofia italic">
                            {` ${formatNumber(homeData?.level?.next ?? 0)} XP`}

                            {/* {`${homeData?.level?.xp ?? 0} XP`} */}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                </section>

                {/* { historySubTab !== "shipping" && <> */}

                <section className="p-3 space-y-1 bg-(--color-naviBlue)">
                  {activeTab === "history" && historySubTab === "balance" && (
                    <>
                      <div className="flex p-3 items-center font-sofia bg-(--color-darkBlue) justify-between">
                        <p className="text-xs md:text-lg font-semibold uppercase tracking-wide">
                          Total Deposit
                        </p>
                        <p className="text-lg flex items-center gap-1 md:text-xl font-bold text-white">
                          <>
                            {user?.activeMode === "coins" ? (
                              <img
                                src="/images/header/win.svg"
                                alt=""
                                className="h-4 w-4"
                              />
                            ) : (
                              <img
                                src="/images/header/star.svg"
                                alt=""
                                className="h-4 w-4"
                              />
                            )}
                          </>

                          {deposit.toLocaleString()}
                        </p>
                      </div>
                      <div className="flex p-3 items-center font-sofia bg-(--color-darkBlue) justify-between">
                        <p className="text-xs md:text-lg font-semibold uppercase tracking-wide">
                          Total Withdraw
                        </p>
                        <p className="text-lg flex items-center gap-1 md:text-xl font-bold text-white">
                          <>
                            {user?.activeMode === "coins" ? (
                              <img
                                src="/images/header/win.svg"
                                alt=""
                                className="h-4 w-4"
                              />
                            ) : (
                              <img
                                src="/images/header/star.svg"
                                alt=""
                                className="h-4 w-4"
                              />
                            )}
                          </>

                          {withdraw.toLocaleString()}
                        </p>
                      </div>
                    </>
                  )}
                  {activeTab === "affiliate" ? (
                    <>
                      <div className="flex p-3 items-center font-sofia bg-black justify-between">
                        <p className="text-(--color-naturalGray) text-xs md:text-lg font-semibold uppercase tracking-wide">
                          affiliate code
                        </p>
                        <p className="text-lg uppercase md:text-xl font-bold text-white">
                          {refCode ? (
                            refCode
                          ) : (
                            <>
                              {referralCode ? (
                                referralCode
                              ) : (
                                <button
                                  onClick={handleGenerateRef}
                                  disabled={loadingRef}
                                  className="cursor-pointer hover:underline disabled:opacity-50"
                                >
                                  {loadingRef
                                    ? "Generating..."
                                    : "Generate Code"}
                                </button>
                              )}
                            </>
                          )}
                        </p>
                      </div>
                      {refCode ? (
                        <div className="relative flex p-3 items-center font-sofia bg-black justify-between">
                          <p className="text-(--color-naturalGray) text-xs md:text-lg font-semibold uppercase tracking-wide">
                            <span className="flex items-center gap-2">
                              <img src="/images/profile/link.svg" alt="" />
                              {refUrl ? refUrl : referralUrl}
                            </span>
                          </p>

                          <button
                            onClick={() =>
                              handleCopy(refUrl ? refUrl : referralUrl)
                            }
                            className="hover:scale-115 cursor-pointer text-lg md:text-xl font-bold text-white"
                          >
                            <img src="/images/profile/copy.svg" alt="copy" />
                          </button>

                          {copied && (
                            <span className="absolute -bottom-4 right-3 text-[10px] text-green-400">
                              Copied!
                            </span>
                          )}
                        </div>
                      ) : (
                        <>
                          {referralCode && (
                            <div className="relative flex p-3 items-center font-sofia bg-[var(--color-black)] justify-between">
                              <p className="text-(--color-naturalGray) text-xs md:text-lg font-semibold uppercase tracking-wide">
                                <span className="flex items-center gap-2">
                                  <img src="/images/profile/link.svg" alt="" />
                                  {referralUrl}
                                </span>
                              </p>

                              <button
                                onClick={() => handleCopy(referralUrl)}
                                className="hover:scale-115 cursor-pointer text-lg md:text-xl font-bold text-white"
                              >
                                <img
                                  src="/images/profile/copy.svg"
                                  alt="copy"
                                />
                              </button>

                              {copied && (
                                <span className="absolute -bottom-4 right-3 text-[10px] text-green-400">
                                  Copied!
                                </span>
                              )}
                            </div>
                          )}
                        </>
                      )}
                    </>
                  ) : (
                    <>
                      <div className="flex p-3 items-center font-sofia bg-black justify-between">
                        <p className="text-xs md:text-lg font-semibold uppercase tracking-wide">
                          Credit Balance
                        </p>
                        <p className="text-lg flex items-center gap-1 md:text-xl font-bold text-white">
                          {!user ? (
                            <img
                              src="/images/header/win.svg"
                              alt=""
                              className="h-4 w-4"
                            />
                          ) : (
                            <>
                              {user?.activeMode === "coins" ? (
                                <img
                                  src="/images/header/win.svg"
                                  alt=""
                                  className="h-4 w-4"
                                />
                              ) : (
                                <img
                                  src="/images/header/star.svg"
                                  alt=""
                                  className="h-4 w-4"
                                />
                              )}
                            </>
                          )}
                          {user?.coins}
                        </p>
                      </div>

                      <div className="mt-4 grid grid-cols-2 gap-3">
                        <Link href="/wallet">
                          <InternalButton className="w-full">
                            Deposit
                          </InternalButton>
                        </Link>
                        <Link href="/withdraw">
                          <InternalButton className="w-full" variant="outline">
                            Withdraw
                          </InternalButton>
                        </Link>
                      </div>
                    </>
                  )}
                </section>

                {/* Joined + UID */}
                {activeTab !== "affiliate" && (
                  <section className="flex gap-3 p-4 text-xs">
                    <div className="bg-(--color-gray) uppercase font-sofia p-3 px-5 flex items-center gap-3">
                      <p className="text-[10px] uppercase tracking-wide text-[#858383]">
                        Joined
                      </p>
                      <p className="font-bold">{user.join_date}</p>
                    </div>
                    <div className="bg-(--color-gray) uppercase font-sofia p-3 px-5 flex items-center gap-3">
                      <p className="text-[10px] uppercase tracking-wide text-[#858383]">
                        UID
                      </p>
                      <p className="font-bold">{user.uuid}</p>
                    </div>
                  </section>
                )}
                {/* </>} */}

                {/* Logout */}
                <InternalButton
                  variant="outline"
                  onClick={() => logout()}
                  className="w-full mt-3 font-onest md:mt-5 !text-[var(--color-blue)] !border-[var(--color-blue)]"
                >
                  Log Out
                </InternalButton>
              </aside>

              {/* RIGHT COLUMN – tabs + content */}
              <section className="flex-1 ">
                {/* Tabs */}
                <div className="flex flex-wrap mb-4 md:mb-10 2xl:mb-10 items-center justify-center px-1 sm:px-4">
                  <nav className="flex flex-wrap gap-1 sm:gap-4">
                    {TABS.map((tab) => (
                      <button
                        key={tab.id}
                        onClick={() => {
                          setActiveTab(tab.id);
                          // STEP 2: if user clicked "history", reset sub tab
                          if (tab.id === "history") {
                            setHistorySubTab("balance");
                          } else {
                            setHistorySubTab(null);
                          }
                        }}
                        className={`font-sofia px-3 py-1.5 text-xs md:text-base 2xl:text-xl font-semibold uppercase tracking-wide ${
                          activeTab === tab.id
                            ? "bg-(--color-blue) text-white"
                            : "hover:bg-[#141728] cursor-pointer hover:text-white"
                        }`}
                      >
                        {tab.label}
                      </button>
                    ))}
                  </nav>
                </div>

                {/* Tab content */}
                <div className="">
                  {TABS.find((t) => t.id === activeTab)?.component}
                </div>
              </section>
            </div>
          </div>
        </>
      )}
      <AlertModal
        open={modalOpen}
        type={modalType}
        message={modalMsg}
        onClose={() => setModalOpen(false)}
      />
    </main>
  );
};

export default ProfilePage;
