"use client";

import { FormEvent, useEffect, useRef, useState } from "react";
import type { SocialPost } from "@/components/social/SocialMessageBubble";

export type SearchHit = SocialPost & {
  space_id?: number;
  space_title?: string;
};

function toFaDigits(n: number) {
  return n.toLocaleString("fa-IR");
}

function formatHitDate(iso?: string | null) {
  if (!iso) return "";
  try {
    const d = new Date(iso);
    const now = new Date();
    const sameDay =
      d.getFullYear() === now.getFullYear() &&
      d.getMonth() === now.getMonth() &&
      d.getDate() === now.getDate();
    if (sameDay) {
      return d.toLocaleTimeString("fa-IR", {
        hour: "2-digit",
        minute: "2-digit",
        hour12: false,
        hourCycle: "h23",
      });
    }
    return d.toLocaleDateString("fa-IR", { month: "numeric", day: "numeric" });
  } catch {
    return "";
  }
}

function highlightSnippet(body: string, term: string) {
  const q = term.trim();
  if (!q) return body;
  const lower = body.toLowerCase();
  const needle = q.toLowerCase();
  const idx = lower.indexOf(needle);
  if (idx < 0) return body;

  const pad = 36;
  const start = Math.max(0, idx - pad);
  const end = Math.min(body.length, idx + q.length + pad);
  const prefix = start > 0 ? "…" : "";
  const suffix = end < body.length ? "…" : "";
  const before = body.slice(start, idx);
  const match = body.slice(idx, idx + q.length);
  const after = body.slice(idx + q.length, end);

  return (
    <>
      {prefix}
      {before}
      <mark className="rounded-sm bg-teal-100 px-0.5 font-semibold text-teal-700">{match}</mark>
      {after}
      {suffix}
    </>
  );
}

function avatarLetter(name: string) {
  const t = name.trim();
  return t ? t.charAt(0) : "?";
}

export function SocialMessageSearch({
  initialQuery = "",
  loading,
  results,
  onSearch,
  onClose,
  onSelect,
  className = "",
}: {
  initialQuery?: string;
  loading?: boolean;
  results: SearchHit[];
  onSearch: (q: string) => void;
  onClose: () => void;
  onSelect: (hit: SearchHit) => void;
  className?: string;
}) {
  const [q, setQ] = useState(initialQuery);
  const [submitted, setSubmitted] = useState(Boolean(initialQuery.trim()));
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  useEffect(() => {
    setQ(initialQuery);
    if (initialQuery.trim()) setSubmitted(true);
  }, [initialQuery]);

  const submit = (e?: FormEvent) => {
    e?.preventDefault();
    const term = q.trim();
    setSubmitted(Boolean(term));
    onSearch(term);
  };

  const clear = () => {
    setQ("");
    setSubmitted(false);
    onSearch("");
    inputRef.current?.focus();
  };

  return (
    <aside
      className={`flex min-h-0 w-full flex-col bg-white lg:max-w-[340px] lg:shrink-0 lg:border-l lg:border-slate-200 ${className}`}
      dir="rtl"
    >
      <div className="flex items-center gap-2 px-3 pb-2 pt-[max(0.75rem,env(safe-area-inset-top))] lg:pt-3">
        <button
          type="button"
          onClick={onClose}
          className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-slate-600 hover:bg-slate-100"
          aria-label="بازگشت"
        >
          <svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="2.2" aria-hidden>
            <path d="M9 5l7 7-7 7" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
        <h2 className="text-base font-bold text-slate-900">جستجوی پیام</h2>
      </div>

      <form onSubmit={submit} className="px-3 pb-2">
        <div className="flex items-center gap-2 rounded-2xl border border-slate-200 bg-slate-50 px-2.5 py-1.5 focus-within:border-teal-500 focus-within:bg-white focus-within:ring-1 focus-within:ring-teal-500">
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="جستجو…"
            className="min-w-0 flex-1 bg-transparent py-1.5 text-sm outline-none placeholder:text-slate-400"
          />
          {q ? (
            <button
              type="button"
              onClick={clear}
              className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-slate-400 hover:bg-slate-200 hover:text-slate-600"
              aria-label="پاک کردن"
            >
              <svg viewBox="0 0 24 24" className="h-4 w-4" fill="currentColor" aria-hidden>
                <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
              </svg>
            </button>
          ) : null}
          <button
            type="submit"
            className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-teal-600 text-white hover:bg-teal-700"
            aria-label="جستجو"
          >
            <svg viewBox="0 0 24 24" className="h-4 w-4 -scale-x-100" fill="currentColor" aria-hidden>
              <path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z" />
            </svg>
          </button>
        </div>
      </form>

      {submitted ? (
        <div className="flex items-center justify-between gap-2 border-b border-slate-100 px-3 py-2">
          <div className="text-xs font-medium text-slate-600">
            {loading ? "در حال جستجو…" : `${toFaDigits(results.length)} پیام یافت شد`}
          </div>
          <div className="flex items-center gap-1">
            <button
              type="button"
              title="فیلتر تاریخ (به‌زودی)"
              className="flex h-8 w-8 items-center justify-center rounded-full text-slate-400 hover:bg-slate-100"
              aria-label="فیلتر تاریخ"
            >
              <svg viewBox="0 0 24 24" className="h-5 w-5" fill="currentColor" aria-hidden>
                <path d="M19 4h-1V2h-2v2H8V2H6v2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H5V10h14v10zm0-12H5V6h14v2z" />
              </svg>
            </button>
            <button
              type="button"
              title="فیلتر کاربر (به‌زودی)"
              className="flex h-8 w-8 items-center justify-center rounded-full text-slate-400 hover:bg-slate-100"
              aria-label="فیلتر کاربر"
            >
              <svg viewBox="0 0 24 24" className="h-5 w-5" fill="currentColor" aria-hidden>
                <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
              </svg>
            </button>
          </div>
        </div>
      ) : null}

      <div className="min-h-0 flex-1 overflow-y-auto">
        {!submitted ? (
          <div className="p-8 text-center text-sm text-slate-400">عبارت مورد نظر را جستجو کنید</div>
        ) : loading ? (
          <div className="p-8 text-center text-sm text-slate-400">در حال جستجو…</div>
        ) : !results.length ? (
          <div className="p-8 text-center text-sm text-slate-400">پیامی یافت نشد</div>
        ) : (
          results.map((hit) => (
            <button
              key={`${hit.space_id ?? "s"}-${hit.id}`}
              type="button"
              onClick={() => onSelect(hit)}
              className="flex w-full items-start gap-3 border-b border-slate-50 px-3 py-3 text-right transition hover:bg-slate-50 active:bg-slate-100"
            >
              <div className="mt-0.5 flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-teal-600 text-sm font-bold text-white">
                {avatarLetter(hit.author?.name || "؟")}
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex items-center justify-between gap-2">
                  <div className="truncate text-sm font-semibold text-slate-900">
                    {hit.author?.name || "کاربر"}
                  </div>
                  <div className="shrink-0 text-[11px] text-slate-400">{formatHitDate(hit.created_at)}</div>
                </div>
                {hit.space_title ? (
                  <div className="mt-0.5 truncate text-[11px] text-slate-400">{hit.space_title}</div>
                ) : null}
                <div className="mt-0.5 line-clamp-2 text-xs leading-5 text-slate-600">
                  {highlightSnippet(hit.body || "", q)}
                </div>
              </div>
            </button>
          ))
        )}
      </div>
    </aside>
  );
}
