"use client";

import React, { useCallback, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { AnimatePresence, motion, PanInfo } from "framer-motion";
import Modal from "@/components/elements/Modal";
import FilterModal from "@/components/models/FilterModal";
import BoldIcon from "@/components/ui/BoldIcon";
import useAxios from "@/hooks/useAxios";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import { cn } from "@/lib/utils";
import { useTranslation } from "react-i18next";
import type { SuggestedFollowUser } from "@/components/posts/FollowingSuggestionsCarousel";
import { Post } from "@/types/types";
import { validateMinMaxPairs } from "@/lib/rangeValidation";
import toast from "react-hot-toast";

const SWIPE_THRESHOLD = 72;

const slideVariants = {
  enter: (direction: number) => ({
    x: direction > 0 ? "105%" : "-105%",
    opacity: 0.35,
    scale: 0.9,
  }),
  center: { x: 0, opacity: 1, scale: 1 },
  exit: (direction: number) => ({
    x: direction > 0 ? "-105%" : "105%",
    opacity: 0.35,
    scale: 0.9,
  }),
};

function getDisplayName(user: SuggestedFollowUser, fallback: string) {
  return (
    [user.first_name, user.last_name].filter(Boolean).join(" ") ||
    user.user_name ||
    fallback
  );
}

function SpecialistCard({
  user,
  variant,
  onSkip,
  userFallback,
  viewProfileLabel,
}: {
  user: SuggestedFollowUser;
  variant: "main" | "peek";
  onSkip?: () => void;
  userFallback: string;
  viewProfileLabel: string;
}) {
  const displayName = getDisplayName(user, userFallback);
  const previewPath = user.previewPost?.files?.[0]?.path;
  const previewUrl = previewPath ? buildStorageUrl(previewPath) : null;
  const profileUrl = user.profile_image
    ? buildStorageUrl(user.profile_image)
    : null;
  const isMain = variant === "main";
  const profileHref = user.user_name ? `/users/${user.user_name}` : "#";

  return (
    <div className="relative h-full w-full overflow-hidden rounded-3xl bg-neutral-900 shadow-2xl">
      {previewUrl ? (
        user.previewPost?.type === "video" ? (
          <video
            src={previewUrl}
            className="h-full w-full object-cover"
            muted
            playsInline
            autoPlay={isMain}
            loop
            preload={isMain ? "auto" : "metadata"}
          />
        ) : (
          <Image
            src={previewUrl}
            alt=""
            fill
            className="object-cover"
            sizes={isMain ? "280px" : "120px"}
            unoptimized
          />
        )
      ) : (
        <div className="h-full w-full bg-neutral-800" />
      )}

      <div
        className={cn(
          "absolute inset-0 bg-gradient-to-t from-black/85 via-black/20 to-black/30",
          !isMain && "from-black/70"
        )}
      />

      {isMain && onSkip ? (
        <button
          type="button"
          onClick={(e) => {
            e.stopPropagation();
            onSkip();
          }}
          className="absolute left-3 top-3 flex h-8 w-8 items-center justify-center rounded-full bg-black/40 text-white backdrop-blur-sm"
          aria-label="skip"
        >
          <BoldIcon name="close-circle" size={18} tinted className="text-white" />
        </button>
      ) : null}

      <div
        className={cn(
          "absolute inset-x-0 bottom-0 flex flex-col items-center pt-6",
          isMain ? "px-4 pb-5" : "px-2 pb-3"
        )}
      >
        <div
          className={cn(
            "relative mb-2 overflow-hidden rounded-full ring-2 ring-white/90",
            isMain ? "h-16 w-16" : "h-9 w-9"
          )}
        >
          {profileUrl ? (
            <Image
              src={profileUrl}
              alt=""
              fill
              className="object-cover"
              sizes={isMain ? "64px" : "36px"}
              unoptimized
            />
          ) : (
            <div className="flex h-full w-full items-center justify-center bg-neutral-700 text-white">
              {displayName.charAt(0)}
            </div>
          )}
        </div>

        {isMain ? (
          <>
            <Link href={profileHref} className="text-center">
              <p className="text-base font-bold text-white">{displayName}</p>
              {user.user_name ? (
                <p className="text-xs text-white/70">@{user.user_name}</p>
              ) : null}
            </Link>
            {user.expertise ? (
              <p className="mt-1 text-xs text-white/55">{user.expertise}</p>
            ) : null}
            <Link
              href={profileHref}
              className="mt-4 w-full max-w-[200px] rounded-full bg-[#fe2c55] py-2.5 text-center text-sm font-bold text-white transition active:scale-95"
            >
              {viewProfileLabel}
            </Link>
          </>
        ) : (
          <p className="line-clamp-1 text-center text-[10px] font-semibold text-white">
            {displayName}
          </p>
        )}
      </div>
    </div>
  );
}

interface SpecialistsSearchModalProps {
  isOpen: boolean;
  onClose: () => void;
}

function SpecialistsSearchModal({ isOpen, onClose }: SpecialistsSearchModalProps) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [showFilter, setShowFilter] = useState(true);
  const [showResults, setShowResults] = useState(false);
  const applyingFilterRef = useRef(false);
  const [users, setUsers] = useState<SuggestedFollowUser[]>([]);
  const [loading, setLoading] = useState(false);
  const [[index, direction], setSlide] = useState<[number, number]>([0, 0]);

  const [stateId, setStateId] = useState("");
  const [cityId, setCityId] = useState("");
  const [rateFilter, setRateFilter] = useState("");
  const [userLevel, setUserLevel] = useState("");
  const [selectedExpertise, setSelectedExpertise] = useState("");
  const [heightMin, setHeightMin] = useState("");
  const [heightMax, setHeightMax] = useState("");
  const [weightMin, setWeightMin] = useState("");
  const [weightMax, setWeightMax] = useState("");
  const [sizeMin, setSizeMin] = useState("");
  const [sizeMax, setSizeMax] = useState("");
  const [hairColor, setHairColor] = useState("");
  const [eyeColor, setEyeColor] = useState("");

  const resetAndClose = () => {
    setShowFilter(true);
    setShowResults(false);
    setUsers([]);
    setSlide([0, 0]);
    onClose();
  };

  const clearFilters = () => {
    setStateId("");
    setCityId("");
    setRateFilter("");
    setUserLevel("");
    setSelectedExpertise("");
    setHeightMin("");
    setHeightMax("");
    setWeightMin("");
    setWeightMax("");
    setSizeMin("");
    setSizeMax("");
    setHairColor("");
    setEyeColor("");
  };

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    try {
      const qs = new URLSearchParams({ page: "1", limit: "20" });
      if (selectedExpertise) qs.set("expertise", selectedExpertise);
      if (stateId) qs.set("province", stateId);
      if (cityId) qs.set("city", cityId);
      if (userLevel) qs.set("userLevel", userLevel);
      if (rateFilter) qs.set("rateFilter", rateFilter);
      if (heightMin) qs.set("heightMin", heightMin);
      if (heightMax) qs.set("heightMax", heightMax);
      if (weightMin) qs.set("weightMin", weightMin);
      if (weightMax) qs.set("weightMax", weightMax);
      if (sizeMin) qs.set("sizeMin", sizeMin);
      if (sizeMax) qs.set("sizeMax", sizeMax);
      if (hairColor) qs.set("hair_color", hairColor);
      if (eyeColor) qs.set("eye_color", eyeColor);

      const response = await request<{
        posts?: Post[];
        feedMeta?: { suggestedUsers?: SuggestedFollowUser[] };
      }>("GET", `/users/web?${qs.toString()}`, null, { noToast: true });

      const suggested = response?.feedMeta?.suggestedUsers;
      if (Array.isArray(suggested) && suggested.length) {
        setUsers(suggested);
      } else {
        const posts = response?.posts || [];
        const map = new Map<string, SuggestedFollowUser>();
        posts.forEach((post) => {
          const id = String(post.userId || post.user_id || "");
          if (!id || map.has(id)) return;
          map.set(id, {
            _id: id,
            user_name: post.user_name,
            first_name: post.first_name,
            last_name: post.last_name,
            expertise: post.expertise,
            profile_image: post.profile_image,
            previewPost: {
              _id: post._id,
              type: post.type,
              files: post.files,
              caption: post.caption,
            },
            is_following: post.is_following,
          });
        });
        setUsers(Array.from(map.values()));
      }
      setSlide([0, 0]);
    } catch {
      setUsers([]);
    } finally {
      setLoading(false);
    }
  }, [
    request,
    selectedExpertise,
    stateId,
    cityId,
    userLevel,
    rateFilter,
    heightMin,
    heightMax,
    weightMin,
    weightMax,
    sizeMin,
    sizeMax,
    hairColor,
    eyeColor,
  ]);

  const handleFilterChange = () => {
    const invalid = validateMinMaxPairs([
      { min: heightMin, max: heightMax },
      { min: weightMin, max: weightMax },
      { min: sizeMin, max: sizeMax },
    ]);
    if (invalid) {
      toast.error(t("filters.maxMustBeGreater"));
      return;
    }
    applyingFilterRef.current = true;
    setShowResults(true);
    setShowFilter(false);
    void fetchUsers();
  };

  const current = users[index];
  const paginate = useCallback(
    (step: number) => {
      if (users.length <= 1) return;
      setSlide(([i]) => [
        (i + step + users.length) % users.length,
        step > 0 ? 1 : -1,
      ]);
    },
    [users.length]
  );

  const handleDragEnd = (_: unknown, info: PanInfo) => {
    if (info.offset.x < -SWIPE_THRESHOLD) paginate(1);
    else if (info.offset.x > SWIPE_THRESHOLD) paginate(-1);
  };

  const prevUser =
    users.length > 1
      ? users[(index - 1 + users.length) % users.length]
      : null;
  const nextUser =
    users.length > 1 ? users[(index + 1) % users.length] : null;

  if (!isOpen) return null;

  return (
    <>
      {showFilter ? (
        <FilterModal
          setShowFilterModal={(open) => {
            if (open) {
              setShowFilter(true);
              return;
            }
            setShowFilter(false);
            // بعد از «اعمال فیلتر» فقط فیلتر بسته شود، نه کل فلوی متخصصان
            if (applyingFilterRef.current) {
              applyingFilterRef.current = false;
              return;
            }
            resetAndClose();
          }}
          showFilterModal={showFilter}
          setStateId={setStateId}
          setCityId={setCityId}
          setRateFilter={setRateFilter}
          setUserLevel={setUserLevel}
          selectedExpertise={selectedExpertise}
          setSelectedExpertise={setSelectedExpertise}
          heightMin={heightMin}
          setHeightMin={setHeightMin}
          heightMax={heightMax}
          setHeightMax={setHeightMax}
          weightMin={weightMin}
          setWeightMin={setWeightMin}
          weightMax={weightMax}
          setWeightMax={setWeightMax}
          sizeMin={sizeMin}
          setSizeMin={setSizeMin}
          sizeMax={sizeMax}
          setSizeMax={setSizeMax}
          hairColor={hairColor}
          setHairColor={setHairColor}
          eyeColor={eyeColor}
          setEyeColor={setEyeColor}
          stateId={stateId}
          cityId={cityId}
          rateFilter={rateFilter}
          userLevel={userLevel}
          handleFilterChange={handleFilterChange}
          clearFilters={clearFilters}
        />
      ) : null}

      {showResults ? (
        <Modal
          isOpen={showResults}
          onClose={resetAndClose}
          height="fit"
          elevated
          panelClassName="max-h-[92vh] overflow-y-auto !bg-black text-white"
        >
          <div className="flex w-full flex-col items-center pb-4">
            <div className="relative mb-4 w-full text-center">
              <button
                type="button"
                onClick={resetAndClose}
                className="absolute left-0 top-0 flex h-9 w-9 items-center justify-center rounded-full bg-white/10"
                aria-label={t("projects.specialists.close")}
              >
                <BoldIcon
                  name="close-circle"
                  size={20}
                  tinted
                  className="text-white"
                />
              </button>
              <h3 className="text-base font-bold text-white">
                {t("projects.specialists.title")}
              </h3>
              <p className="mt-1 text-xs text-white/60">
                {t("projects.specialists.resultsHint")}
              </p>
              <button
                type="button"
                className="mt-2 text-xs text-[#fe2c55]"
                onClick={() => {
                  setShowResults(false);
                  setShowFilter(true);
                }}
              >
                {t("projects.specialists.editFilter")}
              </button>
            </div>

            {loading ? (
              <p className="py-10 text-sm text-white/60">
                {t("projects.specialists.loading")}
              </p>
            ) : !users.length || !current ? (
              <p className="py-10 text-sm text-white/60">
                {t("projects.specialists.empty")}
              </p>
            ) : (
              <div
                dir="ltr"
                className="relative mx-auto h-[min(52dvh,420px)] w-full max-w-[420px] overflow-hidden"
              >
                {prevUser ? (
                  <button
                    type="button"
                    onClick={() => paginate(-1)}
                    className="absolute left-1 top-1/2 z-10 h-[88%] w-[22%] -translate-y-1/2 overflow-hidden rounded-2xl opacity-55"
                  >
                    <SpecialistCard
                      user={prevUser}
                      variant="peek"
                      userFallback={t("common.user")}
                      viewProfileLabel={t("projects.specialists.viewProfile")}
                    />
                  </button>
                ) : null}

                {nextUser ? (
                  <button
                    type="button"
                    onClick={() => paginate(1)}
                    className="absolute right-1 top-1/2 z-10 h-[88%] w-[22%] -translate-y-1/2 overflow-hidden rounded-2xl opacity-55"
                  >
                    <SpecialistCard
                      user={nextUser}
                      variant="peek"
                      userFallback={t("common.user")}
                      viewProfileLabel={t("projects.specialists.viewProfile")}
                    />
                  </button>
                ) : null}

                <AnimatePresence initial={false} custom={direction} mode="popLayout">
                  <motion.div
                    key={current._id}
                    custom={direction}
                    variants={slideVariants}
                    initial="enter"
                    animate="center"
                    exit="exit"
                    transition={{ type: "spring", stiffness: 320, damping: 30 }}
                    drag="x"
                    dragConstraints={{ left: 0, right: 0 }}
                    dragElastic={0.18}
                    onDragEnd={handleDragEnd}
                    className="absolute left-1/2 top-0 z-20 h-full w-[62%] -translate-x-1/2"
                  >
                    <SpecialistCard
                      user={current}
                      variant="main"
                      onSkip={() => paginate(1)}
                      userFallback={t("common.user")}
                      viewProfileLabel={t("projects.specialists.viewProfile")}
                    />
                  </motion.div>
                </AnimatePresence>
              </div>
            )}
          </div>
        </Modal>
      ) : null}
    </>
  );
}

export default SpecialistsSearchModal;
