"use client";

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

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

interface TagUsersPickerProps {
  selected: TaggedUser[];
  onChange: (users: TaggedUser[]) => void;
  max?: number;
}

export default function TagUsersPicker({
  selected,
  onChange,
  max = 50,
}: TagUsersPickerProps) {
  const { request } = useAxios();
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<TaggedUser[]>([]);

  useEffect(() => {
    if (!open || query.length < 2) {
      setResults([]);
      return;
    }
    const t = setTimeout(async () => {
      try {
        const res = await request<{ users?: TaggedUser[]; data?: TaggedUser[] }>(
          "GET",
          `/search-web?q=${encodeURIComponent(query)}&limit=20`,
          null,
          { noToast: true }
        );
        const list = res?.users || res?.data || [];
        setResults(list.filter((u) => !selected.some((s) => s._id === u._id)));
      } catch {
        setResults([]);
      }
    }, 300);
    return () => clearTimeout(t);
  }, [query, open, request, selected]);

  const addUser = (u: TaggedUser) => {
    if (selected.length >= max) {
      toast.error(`حداکثر ${max} نفر`);
      return;
    }
    onChange([...selected, u]);
    setQuery("");
  };

  const removeUser = (id: string) => {
    onChange(selected.filter((u) => u._id !== id));
  };

  return (
    <div className="w-full max-w-md">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="glass-chat-input gentle-transition flex w-full items-center justify-center gap-2 rounded-full py-2.5 text-sm font-medium active:scale-[0.98]"
      >
        <BoldIcon name="user-add" size={20} tinted className="text-current" />
        تگ کردن افراد ({selected.length}/{max})
      </button>

      {selected.length > 0 && (
        <div className="mt-2 flex flex-wrap gap-2">
          {selected.map((u) => (
            <span
              key={u._id}
              className="glass-panel flex items-center gap-1 rounded-full px-2 py-1 text-xs"
            >
              @{u.user_name}
              <button type="button" onClick={() => removeUser(u._id)}>
                <BoldIcon name="close-circle" size={14} tinted className="text-current" />
              </button>
            </span>
          ))}
        </div>
      )}

      {open && (
        <div className="glass-panel-strong mt-2 rounded-2xl p-3">
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="جستجوی نام کاربری…"
            className="glass-chat-input w-full rounded-full px-3 py-2 text-sm outline-none"
          />
          <ul className="mt-2 max-h-40 overflow-y-auto">
            {results.map((u) => (
              <li key={u._id}>
                <button
                  type="button"
                  onClick={() => addUser(u)}
                  className="gentle-transition flex w-full items-center gap-2 rounded-lg px-2 py-2 hover:bg-black/5 dark:hover:bg-white/10"
                >
                  {u.profile_image ? (
                    <Image
                      src={buildStorageUrl(u.profile_image)}
                      alt=""
                      width={32}
                      height={32}
                      className="rounded-full"
                    />
                  ) : (
                    <div className="h-8 w-8 rounded-full bg-neutral-200" />
                  )}
                  <span className="text-sm">@{u.user_name}</span>
                </button>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}
