"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { motion, AnimatePresence } from "framer-motion";
import useAxios from "@/hooks/useAxios";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import BoldIcon from "@/components/ui/BoldIcon";
import { useTranslation } from "react-i18next";

export type ProfileUserListItem = {
  _id: string;
  user_name: string;
  first_name: string;
  last_name: string;
  profile_image?: string;
};

type ListKind = "followers" | "following" | "blocked";

interface ProfileUserListModalProps {
  open: boolean;
  kind: ListKind | null;
  userId: string;
  title: string;
  onClose: () => void;
}

export default function ProfileUserListModal({
  open,
  kind,
  userId,
  title,
  onClose,
}: ProfileUserListModalProps) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [users, setUsers] = useState<ProfileUserListItem[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!open || !kind) return;
    setLoading(true);
    const endpoint =
      kind === "followers"
        ? `/users/follow/followers?userId=${userId}&limit=50`
        : kind === "following"
          ? `/users/follow/following?userId=${userId}&limit=50`
          : "/users/blocked/list";

    request<{ users: ProfileUserListItem[] }>("GET", endpoint, null, {
      noToast: true,
    })
      .then((res) => setUsers(res?.users || []))
      .catch(() => setUsers([]))
      .finally(() => setLoading(false));
  }, [open, kind, userId, request]);

  return (
    <AnimatePresence>
      {open && kind && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="glass-modal-overlay fixed inset-0 z-[250] flex items-end justify-center sm:items-center"
          onClick={onClose}
        >
          <motion.div
            initial={{ y: 40, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            exit={{ y: 40, opacity: 0 }}
            className="glass-modal-panel max-h-[70vh] w-full max-w-md overflow-hidden rounded-t-3xl sm:rounded-3xl"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between border-b border-neutral-200 px-4 py-3 dark:border-neutral-800">
              <h3 className="text-sm font-bold">{title}</h3>
              <button type="button" onClick={onClose} aria-label={t("posts.close")}>
                <BoldIcon name="close-circle" size={22} className="dark:invert" />
              </button>
            </div>
            <div className="max-h-[calc(70vh-3rem)] overflow-y-auto p-2">
              {loading ? (
                <p className="py-8 text-center text-sm text-neutral-500">
                  {t("common.loading")}
                </p>
              ) : users.length === 0 ? (
                <p className="py-8 text-center text-sm text-neutral-500">
                  {t("models.nothingFound")}
                </p>
              ) : (
                <ul className="space-y-1">
                  {users.map((u) => {
                    const name =
                      [u.first_name, u.last_name].filter(Boolean).join(" ") ||
                      u.user_name;
                    return (
                      <li key={u._id}>
                        <Link
                          href={`/users/${u.user_name}`}
                          className="flex items-center gap-3 rounded-xl px-2 py-2 hover:bg-neutral-100 dark:hover:bg-neutral-800"
                          onClick={onClose}
                        >
                          <div className="relative h-10 w-10 overflow-hidden rounded-full bg-neutral-200">
                            <Image
                              src={
                                u.profile_image
                                  ? buildStorageUrl(u.profile_image)
                                  : "/images/fake-avatar.png"
                              }
                              alt=""
                              fill
                              className="object-cover"
                              unoptimized
                            />
                          </div>
                          <div className="min-w-0">
                            <p className="truncate text-sm font-semibold">{name}</p>
                            <p className="truncate text-xs text-neutral-500">
                              @{u.user_name}
                            </p>
                          </div>
                        </Link>
                      </li>
                    );
                  })}
                </ul>
              )}
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
