"use client";

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

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

type Props = {
  selected: ChatRoomMember[];
  onChange: (users: ChatRoomMember[]) => void;
  max?: number;
};

function avatarSrc(profileImage?: string) {
  if (!profileImage) return null;
  return profileImage.startsWith("http")
    ? profileImage
    : buildStorageUrl(profileImage);
}

function displayName(user: ChatRoomMember) {
  return (
    [user.first_name, user.last_name].filter(Boolean).join(" ") || user.user_name
  );
}

export default function ChatRoomMemberPicker({
  selected,
  onChange,
  max = 20,
}: Props) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<ChatRoomMember[]>([]);
  const [searching, setSearching] = useState(false);

  useEffect(() => {
    if (query.trim().length < 2) {
      setResults([]);
      return;
    }

    const timer = window.setTimeout(async () => {
      setSearching(true);
      try {
        const res = await request<{ result?: ChatRoomMember[] }>(
          "GET",
          `/search-web?search=${encodeURIComponent(query.trim())}&type=user&limit=20`,
          null,
          { noToast: true }
        );
        const list = res?.result || [];
        setResults(list.filter((u) => !selected.some((s) => s._id === u._id)));
      } catch {
        setResults([]);
      } finally {
        setSearching(false);
      }
    }, 300);

    return () => window.clearTimeout(timer);
  }, [query, request, selected]);

  const addUser = (user: ChatRoomMember) => {
    if (selected.some((item) => item._id === user._id)) return;
    if (selected.length >= max) {
      toast.error(t("chats.toast.maxUsers", { max }));
      return;
    }
    onChange([...selected, user]);
    setQuery("");
    setResults([]);
  };

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

  return (
    <div className="w-full">
      <div className="relative">
        <BoldIcon
          name="search-normal"
          size={18}
          className="absolute top-1/2 -translate-y-1/2 opacity-60 ltr:left-3 rtl:right-3 dark:brightness-0 dark:invert"
        />
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder={t("chats.placeholder.searchUsername")}
          className="w-full rounded-full border border-neutral-200 bg-white py-2.5 text-sm ltr:pl-10 ltr:pr-4 rtl:pl-4 rtl:pr-10 dark:border-neutral-700 dark:bg-neutral-900"
        />
      </div>

      {searching ? (
        <p className="mt-2 text-center text-xs text-neutral-400">{t("chats.searching")}</p>
      ) : null}

      {results.length > 0 ? (
        <ul className="mt-2 max-h-40 overflow-y-auto rounded-xl border border-neutral-200 dark:border-neutral-700">
          {results.map((user) => (
            <li key={user._id}>
              <button
                type="button"
                onClick={() => addUser(user)}
                className="flex w-full items-center gap-2 px-3 py-2 text-right hover:bg-neutral-50 dark:hover:bg-neutral-800"
              >
                {avatarSrc(user.profile_image) ? (
                  <Image
                    src={avatarSrc(user.profile_image)!}
                    alt=""
                    width={32}
                    height={32}
                    className="h-8 w-8 rounded-full object-cover"
                  />
                ) : (
                  <span className="flex h-8 w-8 items-center justify-center rounded-full bg-neutral-200 text-xs dark:bg-neutral-700">
                    {user.user_name?.[0]?.toUpperCase() || "?"}
                  </span>
                )}
                <span className="min-w-0 flex-1 truncate text-sm">
                  {displayName(user)}
                  <span className="block text-[11px] text-neutral-500" dir="ltr">
                    {user.user_name}
                  </span>
                </span>
              </button>
            </li>
          ))}
        </ul>
      ) : null}

      {selected.length > 0 ? (
        <div className="mt-3 flex flex-wrap gap-2">
          {selected.map((user) => (
            <span
              key={user._id}
              className="inline-flex items-center gap-1 rounded-full bg-[#0095f6]/10 px-2.5 py-1 text-xs text-[#0095f6]"
            >
              @{user.user_name}
              <button
                type="button"
                onClick={() => removeUser(user._id)}
                className="rounded-full px-1 hover:bg-[#0095f6]/20"
                aria-label={t("chats.actions.remove")}
              >
                ×
              </button>
            </span>
          ))}
        </div>
      ) : null}
    </div>
  );
}
