"use client";

import React, { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import RoundedDiv from "@/components/elements/RoundedDiv";
import { User } from "@/types/types";
import RoundedButton from "@/components/elements/RoundedButton";
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";


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 [showProjects] = useState<boolean>(false);
  const [showModelDetailModal, setShowModelDetailModal] = useState<boolean>(false);
  const [showLocationModal, setShowLocationModal] = useState<boolean>(false);
  const [usertype, setUsertype] = useState<string | null>(null);

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

  const router = useRouter();
  const requireAuth = useRequireAuth();
  const sendMsgHandler = () => {
    if (!requireAuth()) return;
    if (user?.offer_status) {
      if (usertype) {
        router.push(`/settings/chats/${user?.user_name}/${user?._id}`);
      } else {
        notRegister();
      }
    } else {
      offerNeed();
    }
  };

  const notRegister = () => {
    toast.error("لطفا از بخش تنظیمات، ثبت نام خود را کامل کنید.");
  };

  const offerNeed = () => {
    toast.error(
      "برای ارسال پیام باید یک درخواست همکاری برای کاربر ثبت کرده باشید."
    );
  };

  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);
  };

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

  return (
    <div className="px-4 py-2 w-full text-xs md:text-sm font-semibold">
         
    
      {showModelDetailModal &&
        (user?.expertise == "مدلینگ" ? (
          <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,
          }}
        />
      )}
      {user?.user_type == "user" ? (
        <div className="grid grid-cols-4 gap-1 md:gap-4 ">
          <RoundedDiv className="text-[12px] md:text-sm h-7 md:h-8 max-sm:text-[8px]">
            سایز: {user?.size || "نامشخص"}
          </RoundedDiv>
          <RoundedDiv className="text-[12px] md:text-sm h-7 md:h-8 max-sm:text-[8px]">
            وزن: {user?.weight || "نامشخص"}
          </RoundedDiv>
          <RoundedDiv className="text-[12px] md:text-sm h-7 md:h-8 max-sm:text-[8px]">
            قد: {user?.height || "نامشخص"}
          </RoundedDiv>
          <RoundedButton
            onClick={() => setShowModelDetailModal(!showModelDetailModal)}
            className="text-[9px] md:text-sm h-7 md:h-8 max-sm:text-[8px]"
          >
            {user?.expertise == "مدلینگ" ? "مشخصات ظاهری" : "لیست خدمات"}
          </RoundedButton>
        </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 ">
            تاریخ آخرین بازدید: <span className="mr-1">{user?.created_at || "نامشخص"}</span>
          </RoundedDiv>
          <RoundedDiv className="!text-[11px] md:text-sm h-7 md:h-8">
            تاریخ ورود: <span className="mr-1">{user?.last_online || "نامشخص"}</span>
          </RoundedDiv>
        </div>
      )}

      {user?.is_self !== false && user?.is_self !== "false" ? (
        <div className={`grid gap-1 md:gap-4 mt-2 md:mt-4 ${!user?.show_location? "grid-cols-2" : "grid-cols-3"}`}>
          <Link
            className="w-full md:h-8 max-w-full"
            href={"/settings/profile/info"}
          >
            <RoundedButton className="text-xs h-7 md:h-8 max-w-full w-full max-sm:text-[8px]">
              پروفایل
            </RoundedButton>
          </Link>
          <Link className="w-full md:h-8 max-w-full" href={"/settings/chats"}>
            <RoundedButton className="text-xs h-7 md:h-8 max-w-full w-full max-sm:text-[8px]">
              پیامها
            </RoundedButton>
          </Link>
          <RoundedButton
            onClick={openLocationModal}
            className={`text-xs max-sm:text-[8px] ${!user?.show_location ? "hidden" : ""} h-7 md:h-8 max-w-full w-full`}
            disabled={!user?.show_location}
          >
            لوکیشن
          </RoundedButton>
        </div>
      ) : user?.user_type == "user" ? (
        <div className={`grid gap-1 md:gap-4 mt-2 md:mt-4 ${!user?.show_location? "grid-cols-2" : "grid-cols-3"}`}>
          <RoundedButton
            onClick={openCollaboration}
            className="text-xs h-7 md:h-8 max-w-full max-sm:text-[8px]"
          >
            درخواست همکاری
          </RoundedButton>
          <RoundedButton
            onClick={sendMsgHandler}
            className="text-xs h-7 md:h-8 max-w-full max-sm:text-[8px]"
          >
            ارسال پیام
          </RoundedButton>
          <RoundedButton
            onClick={openLocationModal}
            className={`text-xs max-sm:text-[8px] ${!user?.show_location ? "hidden" : ""} h-7 md:h-8 max-w-full`}
            disabled={!user?.show_location}
          >
            لوکیشن
          </RoundedButton>
        </div>
      ) : (
        <div className="grid grid-cols-2 gap-1 md:gap-2 mt-2 mx-auto justify-center max-w-xl">
          <RoundedButton
            onClick={openCollaboration}
            className="text-xs h-7 md:h-8 max-w-full max-sm:text-[8px]"
          >
            دعوت به همکاری
          </RoundedButton>
          <RoundedButton
            onClick={sendMsgHandler}
            className="text-xs h-7 md:h-8 max-w-full max-sm:text-[8px]"
          >
            ارسال پیام
          </RoundedButton>
        </div>
      )}

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

export default ModelContent;