"use client";

import { useEffect, useMemo, useState } from "react";
import { EMOJI_CATEGORIES, searchEmojis, type EmojiCategory } from "@/lib/emoji-data";
import { loadRecentEmojis, pushRecentEmoji } from "@/lib/recent-emojis";

function EmojiGrid({
  emojis,
  onPick,
}: {
  emojis: Array<{ char: string }>;
  onPick: (char: string) => void;
}) {
  if (!emojis.length) {
    return <div className="px-3 py-6 text-center text-xs text-slate-400">ایموجی‌ای یافت نشد</div>;
  }
  return (
    <div className="grid grid-cols-8 gap-0.5 px-2 sm:grid-cols-9">
      {emojis.map((item) => (
        <button
          key={item.char}
          type="button"
          className="flex h-9 w-9 items-center justify-center rounded-lg text-xl transition hover:bg-slate-100 active:scale-95 sm:h-10 sm:w-10"
          onClick={() => onPick(item.char)}
          aria-label={item.char}
        >
          {item.char}
        </button>
      ))}
    </div>
  );
}

function PickerBody({
  categoryId,
  onCategoryChange,
  search,
  onSearchChange,
  recent,
  onPick,
  onBackspace,
}: {
  categoryId: string;
  onCategoryChange: (id: string) => void;
  search: string;
  onSearchChange: (v: string) => void;
  recent: string[];
  onPick: (char: string) => void;
  onBackspace?: () => void;
}) {
  const searchResults = useMemo(() => (search.trim() ? searchEmojis(search) : []), [search]);
  const activeCategory = EMOJI_CATEGORIES.find((c) => c.id === categoryId) ?? EMOJI_CATEGORIES[0];

  const sections: Array<{ id: string; label: string; emojis: Array<{ char: string }> }> = [];

  if (search.trim()) {
    sections.push({ id: "search", label: "نتایج جستجو", emojis: searchResults });
  } else if (categoryId === "recent") {
    sections.push({
      id: "recent",
      label: "اموجی‌های اخیر",
      emojis: recent.map((char) => ({ char })),
    });
    if (recent.length) {
      sections.push({
        id: "smileys-fallback",
        label: EMOJI_CATEGORIES[0].label,
        emojis: EMOJI_CATEGORIES[0].emojis.slice(0, 32),
      });
    }
  } else {
    sections.push({ id: activeCategory.id, label: activeCategory.label, emojis: activeCategory.emojis });
  }

  const tabs: Array<{ id: string; tab: string }> = [
    { id: "recent", tab: "🕐" },
    ...EMOJI_CATEGORIES.map((c: EmojiCategory) => ({ id: c.id, tab: c.tab })),
  ];

  return (
    <>
      <div className="flex items-center gap-1 overflow-x-auto border-b border-slate-100 px-2 py-2">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            type="button"
            onClick={() => {
              onCategoryChange(tab.id);
              onSearchChange("");
            }}
            className={`relative flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-lg transition ${
              !search && categoryId === tab.id ? "bg-teal-50" : "hover:bg-slate-50"
            }`}
            aria-label={tab.id}
          >
            {tab.tab}
            {!search && categoryId === tab.id ? (
              <span className="absolute inset-x-1 bottom-0 h-0.5 rounded-full bg-teal-600" />
            ) : null}
          </button>
        ))}
      </div>

      <div className="border-b border-slate-100 px-3 py-2">
        <div className="flex items-center gap-2 rounded-xl bg-slate-100/90 px-3 py-2">
          <svg viewBox="0 0 24 24" className="h-4 w-4 shrink-0 text-slate-400" fill="currentColor" aria-hidden>
            <path d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" />
          </svg>
          <input
            value={search}
            onChange={(e) => onSearchChange(e.target.value)}
            placeholder="جستجو"
            className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-slate-400"
          />
          {search ? (
            <button type="button" className="text-slate-400 hover:text-slate-600" onClick={() => onSearchChange("")}>
              ×
            </button>
          ) : null}
        </div>
      </div>

      <div className="max-h-[min(280px,42vh)] overflow-y-auto py-2">
        {sections.map((section) => (
          <section key={section.id} className="mb-2">
            <div className="px-3 pb-1 text-xs font-semibold text-slate-500">{section.label}</div>
            <EmojiGrid emojis={section.emojis} onPick={onPick} />
          </section>
        ))}
      </div>

      {onBackspace ? (
        <div className="flex justify-end border-t border-slate-100 px-3 py-2">
          <button
            type="button"
            onClick={onBackspace}
            className="flex h-9 w-9 items-center justify-center rounded-lg text-slate-500 hover:bg-slate-100"
            aria-label="حذف آخرین کاراکتر"
          >
            <svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden>
              <path d="M9 5H21v14H9L3 12l6-7z" strokeLinejoin="round" />
              <path d="M14 10l-4 4M10 10l4 4" strokeLinecap="round" />
            </svg>
          </button>
        </div>
      ) : null}
    </>
  );
}

export function SocialEmojiPicker({
  open,
  onClose,
  onPick,
  onBackspace,
  variant = "sheet",
}: {
  open: boolean;
  onClose: () => void;
  onPick: (emoji: string) => void;
  onBackspace?: () => void;
  variant?: "sheet" | "popover";
}) {
  const [categoryId, setCategoryId] = useState("recent");
  const [search, setSearch] = useState("");
  const [recent, setRecent] = useState<string[]>([]);

  useEffect(() => {
    if (open) setRecent(loadRecentEmojis());
  }, [open]);

  const handlePick = (char: string) => {
    const next = pushRecentEmoji(char) ?? loadRecentEmojis();
    setRecent(next);
    onPick(char);
  };

  if (!open) return null;

  const body = (
    <PickerBody
      categoryId={categoryId}
      onCategoryChange={setCategoryId}
      search={search}
      onSearchChange={setSearch}
      recent={recent}
      onPick={handlePick}
      onBackspace={onBackspace}
    />
  );

  if (variant === "popover") {
    return (
      <>
        <div className="fixed inset-0 z-[55]" onClick={onClose} aria-hidden />
        <div className="absolute bottom-full left-0 z-[60] mb-2 w-[min(360px,calc(100vw-1.5rem))] overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-xl shadow-slate-300/30">
          {body}
        </div>
      </>
    );
  }

  return (
    <div className="fixed inset-0 z-[60] flex items-end bg-black/35" onClick={onClose}>
      <div
        className="w-full rounded-t-3xl bg-white pb-[env(safe-area-inset-bottom)] shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="mx-auto mt-2 h-1 w-10 rounded-full bg-slate-200" />
        <div className="flex items-center justify-between border-b border-slate-100 px-4 py-2.5">
          <div className="text-sm font-bold text-slate-800">ایموجی</div>
          <button
            type="button"
            className="flex h-8 w-8 items-center justify-center rounded-full bg-slate-100 text-lg text-slate-500"
            onClick={onClose}
          >
            ×
          </button>
        </div>
        {body}
      </div>
    </div>
  );
}
