"use client";

import React, { useEffect, useState, useCallback } from "react";
import dynamic from "next/dynamic";
import RoundedDiv from "@/components/elements/RoundedDiv";
import { User } from "@/types/types";
import ModelContentPosts from "./ModelContentPosts";
import ModelContentProjects from "./ModelContentProjects";
import ModelDetailModal from "../ModelDetailModal";
import ModelServiceModal from "../ModelServiceModal";
import Link from "next/link";
import Cookies from "js-cookie";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import { debounce } from "lodash";
import { useRequireAuth } from "@/lib/auth/useRequireAuth";
import ProfileUserListModal from "./ProfileUserListModal";
import { isModelExpertise } from "@/lib/isModelExpertise";
import useAxios from "@/hooks/useAxios";
import { cn } from "@/lib/utils";
import { profileActionBtnClass } from "@/lib/ui/buttonStyles";
import { useTranslation } from "react-i18next";
import ShareProfileModal from "@/components/profile/ShareProfileModal";
import { formatFullName } from "@/lib/formatFullName";


const LocationModal = dynamic(() => import("./LocationModal"), {
  ssr: false,
});

interface ModelContentProps {
  user: User | undefined;
  searchParams: {
    expertise?: string;
    province?: string;
    city?: string;
    userLevel?: string;
    rateFilter?: string;
  };
}

interface Filters {
  expertise?: string;
  province?: string;
  city?: string;
  userLevel?: string;
  rateFilter?: string;
}

function ModelContent({ user, searchParams }: ModelContentProps) {
  const { t } = useTranslation("common");
  const [showProjects] = useState<boolean>(false);
  const [showModelDetailModal, setShowModelDetailModal] = useState<boolean>(false);
  const [showLocationModal, setShowLocationModal] = useState<boolean>(false);
  const [showShareProfile, setShowShareProfile] = useState(false);
  const [usertype, setUsertype] = useState<string | null>(null);
  const [userListKind, setUserListKind] = useState<
    "following" | "followers" | "blocked" | null
  >(null);
  const [isFollowing, setIsFollowing] = useState(Boolean(user?.is_following));
  const [isBlocked, setIsBlocked] = useState(Boolean(user?.is_blocked));

  const isModel = isModelExpertise(user?.expertise);
  const isOwnProfile =
    user?.is_self === true || user?.is_self === "true";

  const { request, loading } = useAxios();

  useEffect(() => {
    setIsFollowing(Boolean(user?.is_following));
    setIsBlocked(Boolean(user?.is_blocked));
  }, [user?.is_following, user?.is_blocked, user?._id]);

  useEffect(() => {
    if (isOwnProfile || !user?._id) return;
    const token = Cookies.get("token");
    if (!token) return;

    let cancelled = false;

    const query = user.user_name
      ? `user_name=${encodeURIComponent(user.user_name)}`
      : `user_id=${encodeURIComponent(String(user._id))}`;

    void request<{ user?: User }>(
      "GET",
      `/users/get/web?${query}`,
      null,
      { noToast: true }
    )
      .then((response) => {
        if (cancelled || !response?.user) return;
        setIsFollowing(Boolean(response.user.is_following));
        setIsBlocked(Boolean(response.user.is_blocked));
      })
      .catch(() => {});

    return () => {
      cancelled = true;
    };
  }, [isOwnProfile, user?._id, user?.user_name, request]);

  useEffect(() => {
    if (typeof window !== "undefined") {
      setUsertype(localStorage.getItem("usertype"));
    }
  }, []);

  const router = useRouter();
  const requireAuth = useRequireAuth();
  const goToGift = () => {
    if (isOwnProfile) {
      router.push("/settings/gifts");
      return;
    }
    if (!requireAuth()) return;
    if (!user?._id) return;
    router.push(`/gift/${user._id}`);
  };
  const sendMsgHandler = async () => {
    if (!requireAuth()) return;
    if (!user?.user_name) return;

    try {
      const response = await request<{ user: User }>(
        "GET",
        `/users/get/web?user_name=${user.user_name}&_t=${Date.now()}`,
        null,
        { noToast: true }
      );
      if (response?.user?.offer_status) {
        if (usertype) {
          router.push(`/settings/chats/${user.user_name}/${user._id}`);
        } else {
          notRegister();
        }
        return;
      }
    } catch {
      /* fall through */
    }

    if (user?.offer_status) {
      router.push(`/settings/chats/${user.user_name}/${user._id}`);
    } else {
      offerNeed();
    }
  };

  const notRegister = () => {
    toast.error(t("models.actions.completeRegistration"));
  };

  const offerNeed = () => {
    toast.error(t("models.actions.messageRequiresOffer"));
  };

  const [filters, setFilters] = useState<Filters>({});
  const [token, setToken] = useState<string>("");

  useEffect(() => {
    const fetchData = async () => {
      const search = await searchParams;
      setFilters(search);
      const t = Cookies.get("token") || "";
      setToken(t);
    };
    fetchData();
  }, [searchParams]);

  const openCollaboration = () => {
    if (!requireAuth()) return;
    setShowModelDetailModal((prev) => !prev);
  };

  const handleCollaborationOrBooking = () => {
    if (user?.has_active_booking) {
      if (!requireAuth()) return;
      router.push(`/booking/${user._id}`);
      return;
    }
    openCollaboration();
  };

  const toggleFollow = useCallback(async () => {
    if (!requireAuth() || !user?._id || isOwnProfile || loading) return;

    const nextFollowing = !isFollowing;
    setIsFollowing(nextFollowing);

    try {
      const response = await request<{ is_following?: boolean; message?: string }>(
        "POST",
        "/posts/follow",
        { userId: user._id },
        { noToast: true }
      );
      const confirmed = response?.is_following ?? nextFollowing;
      setIsFollowing(confirmed);
      toast.success(
        confirmed ? t("models.actions.followSuccess") : t("models.actions.unfollowSuccess")
      );
    } catch {
      setIsFollowing(!nextFollowing);
      toast.error(t("models.actions.followError"));
    }
  }, [requireAuth, user?._id, isOwnProfile, loading, isFollowing, request, t]);

  const toggleBlock = useCallback(async () => {
    if (!requireAuth() || !user?._id || isOwnProfile || loading) return;

    const nextBlocked = !isBlocked;
    setIsBlocked(nextBlocked);

    try {
      if (nextBlocked) {
        await request("POST", "/users/block", { user_to_block: user._id });
        toast.success(t("models.actions.blockSuccess"));
      } else {
        await request("POST", "/users/unblock", { user_to_unblock: user._id });
        toast.success(t("models.actions.unblockSuccess"));
      }
    } catch {
      setIsBlocked(!nextBlocked);
      toast.error(nextBlocked ? t("models.actions.blockError") : t("models.actions.unblockError"));
    }
  }, [requireAuth, user?._id, isOwnProfile, loading, isBlocked, request, t]);

  // Debounce برای جلوگیری از باز شدن سریع مودال
  const openLocationModal = debounce(() => {
    if (user?.show_location) {
      setShowLocationModal(true);
    }
  }, 300);

  return (
    <div className="w-full py-2 text-xs font-semibold md:text-sm">
      <ProfileUserListModal
        open={userListKind !== null}
        kind={userListKind}
        userId={user?._id || ""}
        title={
          userListKind === "following"
            ? t("models.following")
            : userListKind === "followers"
              ? t("models.followers")
              : t("models.blocked")
        }
        onClose={() => setUserListKind(null)}
      />
         
    
      {showModelDetailModal &&
        (isModel ? (
          <ModelDetailModal
            hairColor={user?.hair_color}
            eyeColor={user?.eye_color}
            height={user?.height}
            size={user?.size}
            weight={user?.weight}
            isOpen={showModelDetailModal}
            onClose={() => setShowModelDetailModal(false)}
            userId={user?._id}
            isMain
          />
        ) : (
          user && (
            <ModelServiceModal
              services={user?.services}
              isOpen={showModelDetailModal}
              onClose={() => setShowModelDetailModal(false)}
              userId={user?._id}
            />
          )
        ))}
      {showLocationModal && user?.show_location && (
        <LocationModal
          isOpen={showLocationModal}
          onClose={() => setShowLocationModal(false)}
          location={{
            address: user?.address,
            lat: user?.lat,
            lng: user?.lng,
            city: user?.city,
            province: user?.province,
          }}
        />
      )}
      <ShareProfileModal
        open={showShareProfile}
        onClose={() => setShowShareProfile(false)}
        userName={user?.user_name}
        displayName={formatFullName(user?.first_name, user?.last_name)}
        profileImage={user?.profile_image}
      />
      {user?.user_type == "user" ? (
        <div className="grid grid-cols-4 gap-1 md:gap-4">
          {isOwnProfile ? (
            <>
              <button
                type="button"
                onClick={() => setUserListKind("following")}
                className={profileActionBtnClass}
              >
                {t("models.actions.followingCount", { count: user?.followingCount ?? 0 })}
              </button>
              <button
                type="button"
                onClick={() => setUserListKind("blocked")}
                className={profileActionBtnClass}
              >
                {t("models.actions.blockedCount", { count: user?.blockedCount ?? 0 })}
              </button>
            </>
          ) : (
            <>
              <button
                type="button"
                onClick={() => void toggleFollow()}
                disabled={loading}
                className={profileActionBtnClass}
              >
                {isFollowing ? t("models.actions.unfollow") : t("models.actions.follow")}
              </button>
              <button
                type="button"
                onClick={() => void toggleBlock()}
                disabled={loading}
                className={profileActionBtnClass}
              >
                {isBlocked ? t("models.actions.unblock") : t("models.actions.block")}
              </button>
            </>
          )}
          <button
            type="button"
            onClick={goToGift}
            className={profileActionBtnClass}
          >
            {t("models.actions.specialGift")}
          </button>
          <button
            type="button"
            onClick={() => setShowModelDetailModal(!showModelDetailModal)}
            className={profileActionBtnClass}
          >
            {isModel ? t("models.actions.appearance") : t("models.actions.services")}
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-2 gap-1 md:gap-2 mx-auto justify-center max-w-xl">
          <RoundedDiv className="!text-[11px] md:text-sm h-7 md:h-8 ">
            {t("models.actions.lastVisit")}{" "}
            <span className="mr-1">{user?.created_at || t("models.actions.unknown")}</span>
          </RoundedDiv>
          <RoundedDiv className="!text-[11px] md:text-sm h-7 md:h-8">
            {t("models.actions.loginDate")}{" "}
            <span className="mr-1">{user?.last_online || t("models.actions.unknown")}</span>
          </RoundedDiv>
        </div>
      )}

      {user?.is_self !== false && user?.is_self !== "false" ? (
        <div
          className={cn(
            "mt-2 grid gap-1 md:mt-4 md:gap-4",
            [user?.show_location, user?.has_active_booking].filter(Boolean).length === 2
              ? "grid-cols-4"
              : user?.show_location || user?.has_active_booking
                ? "grid-cols-3"
                : "grid-cols-2"
          )}
        >
          <Link href="/settings/profile/info" className={profileActionBtnClass}>
            {t("models.actions.profile")}
          </Link>
          <Link href="/settings/chats" className={profileActionBtnClass}>
            {t("models.actions.messages")}
          </Link>
          {user?.has_active_booking && (
            <Link
              href="/settings/booking/reservations"
              className={profileActionBtnClass}
            >
              {t("booking.myBookings")}
            </Link>
          )}
          <button
            type="button"
            onClick={openLocationModal}
            className={cn(
              profileActionBtnClass,
              !user?.show_location && "hidden"
            )}
            disabled={!user?.show_location}
          >
            {t("models.actions.location")}
          </button>
        </div>
      ) : user?.user_type == "user" ? (
        <div
          className={cn(
            "mt-2 grid gap-1 md:mt-4 md:gap-4",
            user?.show_location ? "grid-cols-2" : "grid-cols-3"
          )}
        >
          <button
            type="button"
            onClick={handleCollaborationOrBooking}
            className={profileActionBtnClass}
          >
            {user?.has_active_booking
              ? t("booking.bookOnline")
              : t("models.actions.collaboration")}
          </button>
          <button
            type="button"
            onClick={sendMsgHandler}
            className={profileActionBtnClass}
          >
            {t("models.actions.sendMessage")}
          </button>
          <button
            type="button"
            onClick={() => setShowShareProfile(true)}
            className={profileActionBtnClass}
          >
            {t("models.actions.shareProfile")}
          </button>
          <button
            type="button"
            onClick={openLocationModal}
            className={cn(
              profileActionBtnClass,
              !user?.show_location && "hidden"
            )}
            disabled={!user?.show_location}
          >
            {t("models.actions.location")}
          </button>
        </div>
      ) : (
        <div className="mx-auto mt-2 grid max-w-xl grid-cols-3 justify-center gap-1 md:gap-2">
          <button
            type="button"
            onClick={handleCollaborationOrBooking}
            className={profileActionBtnClass}
          >
            {user?.has_active_booking
              ? t("booking.bookOnline")
              : t("models.actions.inviteCollaboration")}
          </button>
          <button
            type="button"
            onClick={sendMsgHandler}
            className={profileActionBtnClass}
          >
            {t("models.actions.sendMessage")}
          </button>
          <button
            type="button"
            onClick={() => setShowShareProfile(true)}
            className={profileActionBtnClass}
          >
            {t("models.actions.shareProfile")}
          </button>
        </div>
      )}

      {user &&
        (showProjects ? (
          <ModelContentProjects userId={user?._id} />
        ) : (
          <ModelContentPosts
            filters={filters}
            _id={user?._id}
            token={token}
            privateLocked={Boolean(user?.private_content_locked)}
          />
        ))}
    </div>
  );
}

export default ModelContent;