'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Loader2 } from "lucide-react";

export default function StockInputForm() {
  const [symbol, setSymbol] = useState('');
  const [market, setMarket] = useState('china');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const router = useRouter();

  const handleSearch = async (e?: React.FormEvent) => {
    if (e) {
      e.preventDefault();
    }
    if (!symbol.trim()) return;

    setIsLoading(true);
    setError('');

    try {
      // 1. 调用后端进行 Symbol 归一化，但不启动工作流
      const response = await fetch('/api/tools/resolve-symbol', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          symbol: symbol.trim(),
          market: market,
        }),
      });

      if (!response.ok) {
        const errText = await response.text();
        throw new Error(errText || '解析股票代码失败');
      }

      const data = await response.json();
      // data 结构: { symbol: string, market: string }

      // 2. 跳转到报告页面，仅携带归一化后的 Symbol
      // 此时并没有 request_id，所以详情页不会自动开始，而是等待用户点击
      router.push(`/report/${encodeURIComponent(data.symbol)}?market=${data.market}`);

    } catch (err) {
      console.error(err);
      setError(err instanceof Error ? err.message : '操作失败，请重试');
      setIsLoading(false);
    }
  };

  return (
    <div className="flex justify-center items-center h-full">
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle>基本面分析报告</CardTitle>
          <CardDescription>输入股票代码和市场，生成综合分析报告。</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSearch} className="space-y-4">
            <div className="space-y-2">
              <label>股票代码</label>
              <Input 
                placeholder="例如: 600519 或 AAPL"
                value={symbol}
                onChange={(e) => setSymbol(e.target.value)}
                disabled={isLoading}
              />
            </div>
            <div className="space-y-2">
              <label>交易市场</label>
              <Select value={market} onValueChange={setMarket} disabled={isLoading}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="china">中国</SelectItem>
                  <SelectItem value="hongkong">香港</SelectItem>
                  <SelectItem value="usa">美国</SelectItem>
                  <SelectItem value="japan">日本</SelectItem>
                </SelectContent>
              </Select>
            </div>
            
            {error && (
              <div className="text-sm text-red-500 font-medium">
                {error}
              </div>
            )}

            <Button type="submit" className="w-full" disabled={isLoading || !symbol.trim()}>
              {isLoading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  正在解析...
                </>
              ) : (
                '生成报告'
              )}
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
