"use client";

import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Image from "next/image";
import { IMAGE_BASE_URL, buildStorageUrl } from "@/components/main/BaseUrl";
import useAxios from "@/hooks/useAxios";
import toast from "react-hot-toast";
import IOSSpinner from "@/components/ui/IOSSpinner";

export interface ChatUserItem {
  _id: string;
  user_name: string;
  first_name: string;
  last_name: string;
  profile_image?: string;
}

interface ForwardMessageModalProps {
  open: boolean;
  onClose: () => void;
  message: {
    content: string;
    file?: string;
    fileType?: string;
    forwardedFrom?: {
      userId: string;
      userName: string;
      displayName: string;
    };
  };
  currentUserId: string;
  /** جلوگیری از دوباره‌نمایش در چت فعلی هنگام فوروارد به گیرندهٔ همین مکالمه */
  currentReceiverId?: string;
}

export default function ForwardMessageModal({
  open,
  onClose,
  message,
  currentUserId,
  currentReceiverId,
}: ForwardMessageModalProps) {
  const { request } = useAxios();
  const [users, setUsers] = useState<ChatUserItem[]>([]);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [loading, setLoading] = useState(false);
  const [sending, setSending] = useState(false);

  const loadUsers = async () => {
    setLoading(true);
    try {
      const res = await request<{ filteredUsersData: ChatUserItem[] }>(
        "GET",
        "/messages?limit=100",
        null,
        { noToast: true }
      );
      setUsers(
        (res?.filteredUsersData || []).filter((u) => u._id !== currentUserId)
      );
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (open) loadUsers();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  const toggle = (id: string) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else if (next.size < 50) next.add(id);
      else toast.error("حداکثر ۵۰ کاربر");
      return next;
    });
  };

  const forward = async () => {
    if (selected.size === 0) return;
    setSending(true);
    const fwdMeta = message.forwardedFrom
      ? JSON.stringify({ forwardedFrom: message.forwardedFrom })
      : "";
    const content =
      (fwdMeta ? fwdMeta + "\n" : "") + (message.content || "پیام فوروارد");

    try {
      const targets = Array.from(selected);
      await Promise.all(
        targets.map((receiverId) =>
          request("POST", "/chat", {
            content,
            receiverId,
            senderId: currentUserId,
            forwardedFrom: message.forwardedFrom,
          })
        )
      );
      toast.success(`پیام به ${selected.size} نفر ارسال شد`);
      onClose();
      setSelected(new Set());
    } catch {
      toast.error("خطا در فوروارد");
    } finally {
      setSending(false);
    }
  };

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-[200] flex items-end justify-center bg-black/50 backdrop-blur-sm sm:items-center"
          onClick={onClose}
        >
          <motion.div
            initial={{ y: 40 }}
            animate={{ y: 0 }}
            exit={{ y: 40 }}
            onClick={(e) => e.stopPropagation()}
            className="glass-panel max-h-[70vh] w-full max-w-md overflow-hidden rounded-t-3xl sm:rounded-3xl"
          >
            <div className="border-b border-white/20 p-4 text-center font-semibold">
              فوروارد به ({selected.size}/50)
            </div>
            <div className="max-h-[50vh] overflow-y-auto p-2">
              {loading ? (
                <div className="flex justify-center py-8">
                  <IOSSpinner size={24} />
                </div>
              ) : (
                users.map((u) => (
                  <button
                    key={u._id}
                    type="button"
                    onClick={() => toggle(u._id)}
                    className={`gentle-transition mb-1 flex w-full items-center gap-3 rounded-xl p-3 ${
                      selected.has(u._id) ? "bg-[#0095f6]/15 ring-1 ring-[#0095f6]/40" : "hover:bg-black/5"
                    }`}
                  >
                    {u.profile_image ? (
                      <Image
                        src={buildStorageUrl(u.profile_image)}
                        width={40}
                        height={40}
                        alt=""
                        className="rounded-full"
                      />
                    ) : (
                      <div className="h-10 w-10 rounded-full bg-neutral-200" />
                    )}
                    <span className="text-sm">
                      {u.first_name} {u.last_name}
                    </span>
                  </button>
                ))
              )}
            </div>
            <div className="flex gap-2 border-t border-white/20 p-4">
              <button
                type="button"
                onClick={onClose}
                className="flex-1 rounded-full py-2.5 text-sm text-neutral-500"
              >
                انصراف
              </button>
              <button
                type="button"
                disabled={selected.size === 0 || sending}
                onClick={forward}
                className="ig-dm-send-btn flex-1 rounded-full py-2.5 text-sm text-white disabled:opacity-50"
              >
                {sending ? "در حال ارسال…" : "ارسال"}
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
