"use client";

import { useEffect, useState } from "react";
import { api, SignalHistoryItem } from "@/lib/api";

export default function SignalsPage() {
  const [items, setItems] = useState<SignalHistoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const run = async () => {
      try {
        const data = await api.signalsHistory();
        setItems(data.items || []);
      } catch {
        setError("加载信号历史失败");
      } finally {
        setLoading(false);
      }
    };
    run();
  }, []);

  return (
    <div className="space-y-4">
      <h1 className="text-2xl font-bold text-slate-900">信号历史</h1>
      <div className="rounded-xl border border-slate-200 bg-white shadow-sm p-4 overflow-x-auto">
        {loading ? <p className="text-slate-400">加载中...</p> : null}
        {error ? <p className="text-red-500">{error}</p> : null}
        {!loading && !error ? (
          <table className="w-full text-sm">
            <thead>
              <tr className="text-slate-500 border-b border-slate-200">
                <th className="text-left py-2">时间</th>
                <th className="text-left py-2">币种</th>
                <th className="text-left py-2">年化</th>
                <th className="text-left py-2">信号类型</th>
              </tr>
            </thead>
            <tbody>
              {items.map((row) => (
                <tr key={row.id} className="border-b border-slate-100 text-slate-700">
                  <td className="py-2">{new Date(row.sent_at).toLocaleString("zh-CN")}</td>
                  <td className="py-2 font-medium">{row.symbol}</td>
                  <td className="py-2 text-blue-600 font-mono">{row.annualized}%</td>
                  <td className="py-2 text-slate-500">资金费率套利信号</td>
                </tr>
              ))}
              {!items.length ? (
                <tr>
                  <td className="py-3 text-slate-400" colSpan={4}>暂无信号记录（费率超10%时自动触发）</td>
                </tr>
              ) : null}
            </tbody>
          </table>
        ) : null}
      </div>
    </div>
  );
}
