"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { MetricsPanel } from "../../components/MetricsPanel";
import { NewsList } from "../../components/NewsList";
import { PredictionPanel } from "../../components/PredictionPanel";
import { StockChart } from "../../components/StockChart";
import {
  api,
  type ChartPayload,
  type LatestPredictionResponse,
} from "../../lib/api";

export default function CodePage({ params }: { params: { code: string } }) {
  const { code } = params;
  const [chart, setChart] = useState<ChartPayload | null>(null);
  const [prediction, setPrediction] = useState<LatestPredictionResponse | null>(null);
  const [err, setErr] = useState<string | null>(null);
  const [days, setDays] = useState(180);

  useEffect(() => {
    let alive = true;
    setErr(null);
    setChart(null);
    api
      .getChart(code, days)
      .then((c) => {
        if (alive) setChart(c);
      })
      .catch((e) => {
        if (alive) setErr(e instanceof Error ? e.message : String(e));
      });
    return () => {
      alive = false;
    };
  }, [code, days]);

  useEffect(() => {
    let alive = true;
    api
      .latestPrediction(code)
      .then((r) => {
        if (alive && r.found) setPrediction(r);
      })
      .catch(() => {
        // 예측 이력 없는 경우는 무시.
      });
    return () => {
      alive = false;
    };
  }, [code]);

  return (
    <main className="mx-auto max-w-5xl px-6 py-10">
      <div className="mb-4 flex items-center justify-between">
        <Link href="/" className="text-xs text-zinc-500 hover:text-zinc-300">
          ← 검색으로
        </Link>
        <select
          value={days}
          onChange={(e) => setDays(Number(e.target.value))}
          className="rounded-md border border-zinc-700 bg-zinc-900 px-2 py-1 text-xs"
        >
          <option value={60}>최근 3개월</option>
          <option value={180}>최근 6개월</option>
          <option value={365}>최근 1년</option>
          <option value={1095}>최근 3년</option>
        </select>
      </div>

      {chart && (
        <div className="mb-4">
          <h1 className="text-2xl font-semibold text-zinc-100">
            {chart.name}{" "}
            <span className="text-sm font-normal text-zinc-500">
              {chart.code} · {chart.market}
            </span>
          </h1>
        </div>
      )}

      {err && <div className="mb-4 text-sm text-red-400">차트 로딩 실패: {err}</div>}

      {chart && (
        <>
          <StockChart chart={chart} prediction={prediction} />
          <div className="mt-6">
            <PredictionPanel code={code} initial={prediction} onResult={setPrediction} />
          </div>
          <div className="mt-6 grid gap-6 md:grid-cols-2">
            <MetricsPanel code={code} />
            <NewsList code={code} />
          </div>
        </>
      )}
    </main>
  );
}
