import { useState } from 'react';

export default function Home() {
  const [htmlContent, setHtmlContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<{ url: string } | null>(null);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setResult(null);

    try {
      const response = await fetch('http://localhost:8000/api/html/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ html_content: htmlContent }),
      });

      if (!response.ok) {
        throw new Error('生成 HTML 文件失败');
      }

      const data = await response.json();
      setResult({ url: data.url });
    } catch (err) {
      setError('生成 HTML 文件失败，请稍后重试');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-4xl mx-auto">
      <h2 className="text-2xl font-bold mb-6">HTML 文件生成器</h2>
      <form onSubmit={handleSubmit} className="space-y-6">
        <div>
          <label htmlFor="html-content" className="block text-sm font-medium mb-2">
            HTML 内容
          </label>
          <textarea
            id="html-content"
            value={htmlContent}
            onChange={(e) => setHtmlContent(e.target.value)}
            rows={10}
            className="w-full p-4 border border-border rounded-md bg-card focus:outline-none focus:ring-2 focus:ring-primary"
            placeholder="请输入 HTML 内容..."
          />
        </div>
        <div>
          <button
            type="submit"
            disabled={loading || !htmlContent.trim()}
            className="bg-primary text-primary-foreground px-6 py-2 rounded-md hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {loading ? '生成中...' : '生成 HTML 文件'}
          </button>
        </div>
      </form>

      {error && (
        <div className="mt-6 p-4 bg-destructive/10 text-destructive rounded-md">
          {error}
        </div>
      )}

      {result && (
        <div className="mt-6 p-4 bg-accent/10 text-accent rounded-md">
          <h3 className="font-medium mb-2">生成成功！</h3>
          <p className="mb-2">您的 HTML 文件已生成，可通过以下链接访问：</p>
          <a
            href={result.url}
            target="_blank"
            rel="noopener noreferrer"
            className="text-primary hover:underline"
          >
            {result.url}
          </a>
        </div>
      )}
    </div>
  );
}