import React from 'react';
import { Drawer, Form, Typography, Divider, Button, Space } from 'antd';
import { useThemeMode } from '../hooks/useThemeMode';

export interface FormSection {
  title: string;
  fields: React.ReactNode;
  defaultCollapsed?: boolean;
}

interface DrawerFormProps {
  title: string;
  open: boolean;
  onClose: () => void;
  onSubmit: (values: Record<string, unknown>) => Promise<void>;
  initialValues?: Record<string, unknown>;
  loading?: boolean;
  width?: number | string;
  sections?: FormSection[];
  children?: React.ReactNode;
  columns?: 1 | 2;
  form?: ReturnType<typeof Form.useForm>[0];
  onValuesChange?: (changedValues: Record<string, unknown>, allValues: Record<string, unknown>) => void;
}

export function DrawerForm({
  title,
  open,
  onClose,
  onSubmit,
  initialValues,
  loading,
  width = 640,
  sections,
  children,
  columns = 2,
  form: externalForm,
  onValuesChange,
}: DrawerFormProps) {
  const [internalForm] = Form.useForm();
  const form = externalForm ?? internalForm;
  const isDark = useThemeMode();

  React.useEffect(() => {
    if (open) {
      form.resetFields();
      if (initialValues) {
        form.setFieldsValue(initialValues);
      }
    }
  }, [open, initialValues, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      await onSubmit(values);
    } catch (error: unknown) {
      // validateFields 失败时 error 包含 errorFields（预期行为，不记录）
      // 其他类型的错误才记录
      if (error && typeof error === 'object' && !('errorFields' in error)) {
        console.error('[DrawerForm] submit error:', error);
      }
    }
  };

  const gridStyle: React.CSSProperties =
    columns === 2
      ? { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 16px' }
      : {};

  return (
    <Drawer
      title={title}
      open={open}
      onClose={onClose}
      width={width}
      styles={{
        body: { background: isDark ? '#141414' : undefined },
      }}
      extra={
        <Space>
          <Button onClick={onClose}>取消</Button>
          <Button type="primary" onClick={handleSubmit} loading={loading}>
            保存
          </Button>
        </Space>
      }
    >
      <Form form={form} layout="vertical" initialValues={initialValues} onValuesChange={onValuesChange}>
        {sections
          ? sections.map((s, i) => (
              <div key={i}>
                {i > 0 && <Divider style={{ margin: '16px 0' }} />}
                <Typography.Text
                  strong
                  style={{ fontSize: 14, marginBottom: 12, display: 'block' }}
                >
                  {s.title}
                </Typography.Text>
                <div style={gridStyle}>{s.fields}</div>
              </div>
            ))
          : children && <div style={gridStyle}>{children}</div>}
      </Form>
    </Drawer>
  );
}
