import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { FormDesigner } from '@/components/FormDesigner';
import type { FormSchema } from '@/components/FormDesigner';
import { ArrowLeft, Workflow } from 'lucide-react';
import { getDefinitionById, updateDefinition } from './service';
import type { FormDefinitionRequest } from './types';

/**
 * 表单设计器页面
 */
const FormDesignerPage: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [formSchema, setFormSchema] = useState<FormSchema | null>(null);
  const [formDefinition, setFormDefinition] = useState<any>(null);

  // 加载表单定义
  useEffect(() => {
    if (id) {
      loadFormDefinition(Number(id));
    }
  }, [id]);

  const loadFormDefinition = async (definitionId: number) => {
    try {
      const result = await getDefinitionById(definitionId);
      setFormDefinition(result);
      setFormSchema(result.schema);
    } catch (error) {
      console.error('加载表单定义失败:', error);
    }
  };

  // 保存表单（只更新 schema，不修改基本信息）
  const handleSave = async (schema: FormSchema) => {
    if (!id || !formDefinition) {
      alert('表单信息加载失败');
      return;
    }

    const request: FormDefinitionRequest = {
      name: formDefinition.name,
      key: formDefinition.key,
      categoryId: formDefinition.categoryId,
      description: formDefinition.description,
      isTemplate: formDefinition.isTemplate,
      schema,
      status: formDefinition.status || 'DRAFT',
    };

    try {
      await updateDefinition(Number(id), request);
      alert('保存成功');
    } catch (error) {
      console.error('保存表单失败:', error);
      alert('保存失败');
    }
  };

  // 返回列表
  const handleBack = () => {
    navigate('/form/definitions');
  };

  return (
    <div className="flex flex-col gap-6 p-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-blue-500/10">
            <Workflow className="h-6 w-6 text-blue-600" />
          </div>
          <div>
            <h1 className="text-3xl font-bold tracking-tight">
              {formDefinition?.name || '表单设计'}
            </h1>
            <p className="text-sm text-muted-foreground mt-1">
              {formDefinition?.description || '拖拽左侧组件到画布，配置字段属性和验证规则'}
            </p>
          </div>
        </div>
        <Button variant="outline" onClick={handleBack}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          返回列表
        </Button>
      </div>

      {/* 表单设计器区域 */}
      <Card>
        <CardContent className="p-0">
          <div className="rounded-lg">
            <FormDesigner
              value={formSchema || undefined}
              onChange={setFormSchema}
              onSave={handleSave}
            />
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default FormDesignerPage;
