"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 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;
}

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

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

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

  useEffect(() => {
    if (!open || query.trim().length < 2) {
      setResults([]);
      return;
    }
    const t = setTimeout(async () => {
      setSearching(true);
      try {
        const res = await request<{ result?: TaggedUser[] }>(
          "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 () => clearTimeout(t);
  }, [query, open, request, selected]);

  const addUser = (u: TaggedUser) => {
    if (selected.some((s) => s._id === u._id)) return;
    if (selected.length >= max) {
      toast.error(t("posts.maxTagged", { max }));
      return;
    }
    onChange([...selected, u]);
    setQuery("");
  };

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

  return (
    <div className="w-full">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="flex w-full items-center justify-center gap-2 rounded-full border border-neutral-200 py-2.5 text-sm font-medium transition active:scale-[0.98] dark:border-neutral-700"
      >
        <BoldIcon name="user-add" size={20} tinted className="text-current" />
        {t("posts.tagPeople", { count: selected.length, max })}
      </button>

      {selected.length > 0 && (
        <div className="mt-3 flex flex-wrap gap-2">
          {selected.map((u) => {
            const src = avatarSrc(u.profile_image);
            return (
              <span
                key={u._id}
                className="flex items-center gap-2 rounded-full bg-neutral-100 py-1 pe-2 ps-1 dark:bg-neutral-800"
              >
                <div className="relative h-7 w-7 shrink-0 overflow-hidden rounded-full bg-neutral-200">
                  {src ? (
                    <Image
                      src={src}
                      alt=""
                      fill
                      className="object-cover"
                      unoptimized
                    />
                  ) : null}
                </div>
                <span className="text-xs font-medium">
                  {displayName(u)}
                  <span className="mx-1 text-neutral-400">·</span>
                  @{u.user_name}
                </span>
                <button
                  type="button"
                  onClick={() => removeUser(u._id)}
                  aria-label={t("posts.remove")}
                >
                  <BoldIcon
                    name="close-circle"
                    size={16}
                    tinted
                    className="text-neutral-400"
                  />
                </button>
              </span>
            );
          })}
        </div>
      )}

      {open && (
        <div className="mt-3 rounded-2xl border border-neutral-200 p-3 dark:border-neutral-700">
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder={t("posts.searchUsersPlaceholder")}
            className="w-full rounded-full bg-neutral-100 px-4 py-2.5 text-sm outline-none dark:bg-neutral-800"
            autoFocus
          />
          {searching && (
            <p className="mt-2 text-center text-xs text-neutral-400">
              {t("posts.searching")}
            </p>
          )}
          {!searching && query.trim().length >= 2 && results.length === 0 && (
            <p className="mt-2 text-center text-xs text-neutral-400">
              {t("posts.noUsersFound")}
            </p>
          )}
          <ul className="mt-2 max-h-52 space-y-1 overflow-y-auto">
            {results.map((u) => {
              const src = avatarSrc(u.profile_image);
              const name = displayName(u);
              return (
                <li key={u._id}>
                  <button
                    type="button"
                    onClick={() => addUser(u)}
                    className="flex w-full items-center gap-3 rounded-xl px-2 py-2 text-right transition hover:bg-neutral-100 dark:hover:bg-neutral-800"
                  >
                    <div className="relative h-10 w-10 shrink-0 overflow-hidden rounded-full bg-neutral-200">
                      {src ? (
                        <Image
                          src={src}
                          alt=""
                          fill
                          className="object-cover"
                          unoptimized
                        />
                      ) : null}
                    </div>
                    <div className="min-w-0 flex-1 text-right">
                      <p className="truncate text-sm font-medium">{name}</p>
                      <p className="truncate text-xs text-neutral-500">
                        @{u.user_name}
                      </p>
                    </div>
                  </button>
                </li>
              );
            })}
          </ul>
        </div>
      )}
    </div>
  );
}
