"use client";

import { useState, useEffect, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
import { EVENT_CONFIG, EventType, formatDuration } from "@/lib/event-config";
import { EventIcon } from "@/components/event-icon";
import { useBaby } from "@/contexts/baby-context";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import { Search, FileText, StickyNote } from "lucide-react";

interface SearchEvent {
  id: string;
  type: EventType;
  startedAt: string;
  endedAt?: string;
  notes?: string;
  metadata?: Record<string, unknown>;
  user: { id: string; name: string };
}

interface SearchNote {
  id: string;
  date: string;
  content: string;
  user: { id: string; name: string };
}

function eventSummary(ev: SearchEvent): string {
  const meta = ev.metadata ?? {};
  if (ev.type === "BREASTFEED") {
    const side = meta.breastSide === "left" ? "gauche" : meta.breastSide === "right" ? "droite" : "les deux";
    if (ev.endedAt) return `${formatDuration(new Date(ev.startedAt), new Date(ev.endedAt))} · ${side}`;
    return side;
  }
  if (ev.type === "BOTTLE") return meta.volume ? `${meta.volume} mL` : "";
  if (ev.type === "TEMPERATURE") return meta.value ? `${meta.value}°${meta.unit ?? "C"}` : "";
  if (ev.type === "MEDICATION") return String(meta.name ?? "");
  if (ev.type === "SYMPTOM") return ((meta.tags as string[]) ?? []).join(", ");
  if ((ev.type === "NAP" || ev.type === "NIGHT_SLEEP") && ev.endedAt)
    return formatDuration(new Date(ev.startedAt), new Date(ev.endedAt));
  return "";
}

function highlight(text: string, q: string): React.ReactNode {
  if (!q || !text) return text;
  const idx = text.toLowerCase().indexOf(q.toLowerCase());
  if (idx === -1) return text;
  return (
    <>
      {text.slice(0, idx)}
      <mark className="bg-yellow-200 dark:bg-yellow-700 rounded px-0.5">{text.slice(idx, idx + q.length)}</mark>
      {text.slice(idx + q.length)}
    </>
  );
}

export default function SearchPage() {
  const { selectedBaby } = useBaby();
  const [q, setQ] = useState("");
  const [debouncedQ, setDebouncedQ] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

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

  useEffect(() => {
    const t = setTimeout(() => setDebouncedQ(q), 300);
    return () => clearTimeout(t);
  }, [q]);

  const { data, isFetching } = useQuery<{ events: SearchEvent[]; notes: SearchNote[] }>({
    queryKey: ["search", selectedBaby?.id, debouncedQ],
    queryFn: () =>
      fetch(`/api/search?babyId=${selectedBaby!.id}&q=${encodeURIComponent(debouncedQ)}`).then((r) => r.json()),
    enabled: !!selectedBaby?.id && debouncedQ.length >= 2,
    placeholderData: { events: [], notes: [] },
  });

  const events = data?.events ?? [];
  const notes = data?.notes ?? [];
  const hasResults = events.length > 0 || notes.length > 0;
  const searched = debouncedQ.length >= 2;

  return (
    <div className="p-4 md:p-8 pb-24 md:pb-8">
      <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-5">Recherche</h1>

      <div className="relative mb-6">
        <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
        <input
          ref={inputRef}
          type="search"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder="Rechercher dans les notes et événements…"
          className="w-full pl-10 pr-4 py-3 rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
        />
        {isFetching && (
          <div className="absolute right-3.5 top-1/2 -translate-y-1/2 w-4 h-4 border-2 border-indigo-400 border-t-transparent rounded-full animate-spin" />
        )}
      </div>

      {!searched && (
        <p className="text-sm text-slate-400 dark:text-slate-500 text-center py-12">Saisissez au moins 2 caractères</p>
      )}

      {searched && !hasResults && !isFetching && (
        <p className="text-sm text-slate-400 dark:text-slate-500 text-center py-12">Aucun résultat pour « {debouncedQ} »</p>
      )}

      {events.length > 0 && (
        <div className="mb-6">
          <h2 className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-3 flex items-center gap-1.5">
            <FileText className="w-3.5 h-3.5" />
            Événements · {events.length}
          </h2>
          <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl overflow-hidden divide-y divide-slate-100 dark:divide-slate-700">
            {events.map((ev) => {
              const cfg = EVENT_CONFIG[ev.type];
              const summary = eventSummary(ev);
              return (
                <div key={ev.id} className="flex items-start gap-3 px-4 py-3">
                  <div className={`w-8 h-8 rounded-lg ${cfg.bgClass} flex items-center justify-center flex-shrink-0 mt-0.5`}>
                    <EventIcon name={cfg.icon} className={`w-4 h-4 ${cfg.colorClass}`} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium text-slate-700 dark:text-slate-200">{cfg.label}</span>
                      {summary && <span className="text-xs text-slate-400 dark:text-slate-500">{summary}</span>}
                    </div>
                    {ev.notes && (
                      <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5 line-clamp-2">
                        {highlight(ev.notes, debouncedQ)}
                      </p>
                    )}
                    <p className="text-[10px] text-slate-400 dark:text-slate-500 mt-1">
                      {format(new Date(ev.startedAt), "d MMM yyyy HH:mm", { locale: fr })} · {ev.user.name}
                    </p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {notes.length > 0 && (
        <div>
          <h2 className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-3 flex items-center gap-1.5">
            <StickyNote className="w-3.5 h-3.5" />
            Journal · {notes.length}
          </h2>
          <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl overflow-hidden divide-y divide-slate-100 dark:divide-slate-700">
            {notes.map((note) => (
              <div key={note.id} className="px-4 py-3">
                <p className="text-xs text-slate-400 dark:text-slate-500 mb-1">
                  {format(new Date(note.date), "d MMMM yyyy", { locale: fr })} · {note.user.name}
                </p>
                <p className="text-sm text-slate-700 dark:text-slate-200 line-clamp-3">
                  {highlight(note.content, debouncedQ)}
                </p>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
