"use client";

import { btnPrimary } from "@/lib/ui/buttonStyles";
import { cn } from "@/lib/utils";

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

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

interface SendStoryModalProps {
  open: boolean;
  onClose: () => void;
  storyId: string;
  previewPath?: string;
  mediaType?: "image" | "video";
  currentUserId: string;
}

export default function SendStoryModal({
  open,
  onClose,
  storyId,
  previewPath,
  mediaType = "image",
  currentUserId,
}: SendStoryModalProps) {
  const { t } = useTranslation("common");
  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 && Boolean(u.user_name)
        )
      );
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (open) {
      void loadUsers();
      setSelected(new Set());
    }
    // 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(t("posts.maxUsers"));
      return next;
    });
  };

  const send = async () => {
    if (selected.size === 0) return;
    setSending(true);
    try {
      const res = await request<{ sentCount?: number }>(
        "POST",
        "/stories/send",
        {
          storyId,
          receiverIds: Array.from(selected),
        },
        { noToast: true }
      );
      toast.success(
        t("stories.sentToCount", { count: res?.sentCount ?? selected.size })
      );
      onClose();
      setSelected(new Set());
    } catch {
      toast.error(t("stories.sendStoryError"));
    } finally {
      setSending(false);
    }
  };

  const preview = previewPath ? buildStorageUrl(previewPath) : null;

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="glass-modal-overlay fixed inset-0 z-[200] 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 w-full max-w-md rounded-t-3xl p-4 sm:rounded-3xl"
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className="mb-3 text-center text-sm font-bold">
              {t("stories.sendStory")}
            </h3>

            <div className="mb-4 flex items-center gap-3 rounded-xl bg-neutral-100 p-2 dark:bg-neutral-800">
              {preview && (
                <div className="relative h-12 w-12 shrink-0 overflow-hidden rounded-lg">
                  {mediaType === "video" ? (
                    <video
                      src={preview}
                      className="h-full w-full object-cover"
                      muted
                      playsInline
                    />
                  ) : (
                    <Image
                      src={preview}
                      alt=""
                      fill
                      className="object-cover"
                      unoptimized
                    />
                  )}
                </div>
              )}
              <p className="line-clamp-2 text-xs text-neutral-600 dark:text-neutral-300">
                {t("stories.sendStoryHint")}
              </p>
            </div>

            {loading ? (
              <div className="flex justify-center py-8">
                <IOSSpinner />
              </div>
            ) : users.length === 0 ? (
              <p className="py-8 text-center text-sm text-neutral-500">
                {t("posts.noChatUsers")}
              </p>
            ) : (
              <ul className="max-h-64 space-y-1 overflow-y-auto">
                {users.map((u) => {
                  const checked = selected.has(u._id);
                  return (
                    <li key={u._id}>
                      <button
                        type="button"
                        onClick={() => toggle(u._id)}
                        className={cn(
                          "flex w-full items-center gap-3 rounded-xl px-2 py-2 text-right",
                          checked
                            ? "bg-[#FF107D]/10"
                            : "hover:bg-neutral-100 dark:hover:bg-neutral-800"
                        )}
                      >
                        <div className="relative h-10 w-10 overflow-hidden rounded-full bg-neutral-200">
                          {u.profile_image ? (
                            <Image
                              src={buildStorageUrl(u.profile_image)}
                              alt=""
                              fill
                              className="object-cover"
                              unoptimized
                            />
                          ) : null}
                        </div>
                        <div className="min-w-0 flex-1">
                          <p className="truncate text-sm font-semibold">
                            {u.first_name} {u.last_name}
                          </p>
                          <p className="truncate text-xs text-neutral-500">
                            @{u.user_name}
                          </p>
                        </div>
                        <span
                          className={cn(
                            "flex h-5 w-5 items-center justify-center rounded-full border text-[10px]",
                            checked
                              ? "border-[#FF107D] bg-[#FF107D] text-white"
                              : "border-neutral-300"
                          )}
                        >
                          {checked ? "✓" : ""}
                        </span>
                      </button>
                    </li>
                  );
                })}
              </ul>
            )}

            <button
              type="button"
              disabled={selected.size === 0 || sending}
              onClick={() => void send()}
              className={cn(btnPrimary, "mt-4 w-full disabled:opacity-40")}
            >
              {sending
                ? t("posts.sending")
                : t("posts.sendWithCount", { count: selected.size })}
            </button>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
