"use client";

import { useAuth, authFetch } from "@/lib/auth";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import StrategyForm, { StrategyFormData } from "@/components/StrategyForm";

export default function EditStrategyPage() {
  useAuth();
  const params = useParams();
  const router = useRouter();
  const sid = params?.id as string;
  const [formData, setFormData] = useState<StrategyFormData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!sid) return;
    authFetch(`/api/strategies/${sid}`)
      .then((r) => r.json())
      .then((d) => {
        const s = d.strategy;
        if (!s) throw new Error("策略不存在");
        setFormData({
          display_name: s.display_name,
          symbol: s.symbol,
          direction: s.direction,
          initial_balance: s.initial_balance,
          cvd_fast_window: s.cvd_fast_window,
          cvd_slow_window: s.cvd_slow_window,
          weight_direction: s.weight_direction,
          weight_env: s.weight_env,
          weight_aux: s.weight_aux,
          weight_momentum: s.weight_momentum,
          entry_score: s.entry_score,
          // 门1 波动率
          gate_vol_enabled: s.gate_vol_enabled,
          vol_atr_pct_min: s.vol_atr_pct_min,
          // 门2 CVD共振
          gate_cvd_enabled: s.gate_cvd_enabled ?? true,
          // 门3 鲸鱼否决
          gate_whale_enabled: s.gate_whale_enabled,
          whale_usd_threshold: s.whale_usd_threshold,
          whale_flow_pct: s.whale_flow_pct,
          // 门4 OBI否决
          gate_obi_enabled: s.gate_obi_enabled,
          obi_threshold: s.obi_threshold,
          // 门5 期现背离
          gate_spot_perp_enabled: s.gate_spot_perp_enabled,
          spot_perp_threshold: s.spot_perp_threshold,
          sl_atr_multiplier: s.sl_atr_multiplier,
          tp1_ratio: s.tp1_ratio,
          tp2_ratio: s.tp2_ratio,
          timeout_minutes: s.timeout_minutes,
          flip_threshold: s.flip_threshold,
          description: s.description || "",
        });
      })
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, [sid]);

  if (loading) return <div className="p-8 text-slate-400 text-sm animate-pulse">加载中...</div>;
  if (error) return <div className="p-8 text-red-500 text-sm">{error}</div>;
  if (!formData) return null;

  return (
    <div className="p-4 max-w-2xl mx-auto">
      <div className="mb-5">
        <h1 className="text-lg font-bold text-slate-800">调整策略参数</h1>
        <p className="text-slate-500 text-xs mt-0.5">修改保存后15秒内生效，不影响当前持仓</p>
      </div>
      <StrategyForm
        mode="edit"
        initialData={formData}
        strategyId={sid}
        isBalanceEditable={false}
        onSuccess={() => router.push(`/strategy-plaza/${sid}`)}
      />
    </div>
  );
}
