"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { api, type Symbol } from "../lib/api";
import { Sparkline } from "./Sparkline";

export function SearchBox({ autoFocus = false }: { autoFocus?: boolean }) {
  const [q, setQ] = useState("");
  const [items, setItems] = useState<Symbol[]>([]);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [seedOnly, setSeedOnly] = useState(false);

  useEffect(() => {
    const term = q.trim();
    if (!term) {
      setItems([]);
      setErr(null);
      return;
    }
    setLoading(true);
    setErr(null);
    const handle = setTimeout(async () => {
      try {
        // with_sparkline=true: 백엔드가 최근 30 종가 + close + pct_change 동봉.
        const r = await api.search(term, seedOnly, 15, true);
        setItems(r.items);
      } catch (e) {
        setErr(e instanceof Error ? e.message : String(e));
        setItems([]);
      } finally {
        setLoading(false);
      }
    }, 200);
    return () => clearTimeout(handle);
  }, [q, seedOnly]);

  return (
    <div className="w-full">
      <div className="flex items-center gap-3">
        <input
          autoFocus={autoFocus}
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder="종목명 또는 코드 (예: 삼성, 005930)"
          className="w-full rounded-md border border-zinc-700 bg-zinc-900 px-4 py-3 text-base outline-none focus:border-zinc-500"
        />
        <label className="flex shrink-0 items-center gap-2 text-xs text-zinc-400">
          <input
            type="checkbox"
            checked={seedOnly}
            onChange={(e) => setSeedOnly(e.target.checked)}
          />
          학습대상 10종목만
        </label>
      </div>

      <div className="mt-2 min-h-[1.5rem] text-xs text-zinc-500">
        {loading && "검색중…"}
        {err && <span className="text-red-400">에러: {err}</span>}
        {!loading && !err && q && items.length === 0 && "검색 결과 없음"}
      </div>

      {items.length > 0 && (
        <ul className="mt-2 divide-y divide-zinc-800 rounded-md border border-zinc-800 bg-zinc-900/40">
          {items.map((it) => (
            <SearchRow key={it.code} it={it} />
          ))}
        </ul>
      )}
    </div>
  );
}

function SearchRow({ it }: { it: Symbol }) {
  const pct = it.pct_change ?? null;
  const tone =
    pct == null || pct === 0
      ? "text-zinc-400"
      : pct > 0
      ? "text-rose-400"
      : "text-sky-400";
  const stroke = pct != null && pct < 0 ? "#3b82f6" : "#ef4444";
  const series = it.sparkline ?? [];

  return (
    <li>
      <Link
        href={`/${it.code}`}
        className="flex items-center justify-between gap-3 px-4 py-3 text-sm hover:bg-zinc-800/70"
      >
        <div className="min-w-0">
          <div className="font-medium text-zinc-100">
            {it.name}
            {it.is_seed && (
              <span className="ml-2 rounded-full bg-emerald-900/60 px-2 py-0.5 text-[10px] font-semibold text-emerald-300">
                SEED
              </span>
            )}
          </div>
          <div className="text-xs text-zinc-500">
            {it.code} · {it.market}
            {it.sector ? ` · ${it.sector}` : ""}
          </div>
        </div>
        <div className="flex shrink-0 items-center gap-3">
          {series.length >= 2 && (
            <Sparkline values={series} stroke={stroke} width={80} height={28} />
          )}
          <div className="text-right tabular-nums">
            <div className="text-xs text-zinc-100">
              {it.close != null
                ? it.close.toLocaleString(undefined, { maximumFractionDigits: 0 })
                : "—"}
            </div>
            <div className={`text-[11px] ${tone}`}>
              {pct != null ? `${pct >= 0 ? "+" : ""}${pct.toFixed(2)}%` : ""}
            </div>
          </div>
        </div>
      </Link>
    </li>
  );
}
