import { useState, useEffect } from 'react';
import { Form, Input, Button, Card, message, Spin } from 'antd';
import { SaveOutlined } from '@ant-design/icons';
import type { Dataset } from '~/api/dify-dataset/type/datasetTypes';
import { updateDatasetName } from '~/api/dify-dataset/api/datasetApi';

const { TextArea } = Input;

interface DatasetSettingsProps {
    dataset: Dataset | null;
    onDatasetUpdated: (dataset: Dataset) => void;
}

/**
 * 知识库设置组件
 * 用于修改知识库名称和描述
 */
export default function DatasetSettings({
    dataset,
    onDatasetUpdated,
}: DatasetSettingsProps) {
    const [form] = Form.useForm();
    const [saving, setSaving] = useState(false);
    const [hasChanges, setHasChanges] = useState(false);

    // 初始化表单数据
    useEffect(() => {
        if (dataset) {
            form.setFieldsValue({
                name: dataset.name,
                description: dataset.description || '',
            });
            setHasChanges(false);
        }
    }, [dataset, form]);

    /**
     * 处理表单值变化
     */
    const handleValuesChange = () => {
        const values = form.getFieldsValue();
        const changed =
            values.name !== dataset?.name ||
            values.description !== (dataset?.description || '');
        setHasChanges(changed);
    };

    /**
     * 保存设置
     */
    const handleSave = async () => {
        if (!dataset) {
            message.error('知识库不存在');
            return;
        }

        try {
            const values = await form.validateFields();
            setSaving(true);

            // 目前只支持修改名称
            const updatedDataset = await updateDatasetName(dataset.id, values.name);

            message.success('保存成功');
            onDatasetUpdated(updatedDataset);
            setHasChanges(false);
        } catch (err: any) {
            console.error('保存设置失败:', err);
            message.error(err.message || '保存失败');
        } finally {
            setSaving(false);
        }
    };

    /**
     * 重置表单
     */
    const handleReset = () => {
        if (dataset) {
            form.setFieldsValue({
                name: dataset.name,
                description: dataset.description || '',
            });
            setHasChanges(false);
        }
    };

    if (!dataset) {
        return (
            <div className="settings-loading">
                <Spin size="large" />
            </div>
        );
    }

    return (
        <div className="dataset-settings-page">
            {/* 页面标题 */}
            <div className="page-header">
                <h1>设置</h1>
                <p className="page-description">
                    管理知识库的基本信息
                </p>
            </div>

            {/* 设置表单 */}
            <Card className="settings-card">
                <Form
                    form={form}
                    layout="vertical"
                    onValuesChange={handleValuesChange}
                >
                    <Form.Item
                        name="name"
                        label="知识库名称"
                        rules={[
                            { required: true, message: '请输入知识库名称' },
                            { max: 100, message: '名称不能超过100个字符' },
                        ]}
                    >
                        <Input placeholder="请输入知识库名称" maxLength={100} />
                    </Form.Item>

                    <Form.Item
                        name="description"
                        label="知识库描述"
                        extra="描述知识库的用途和内容（仅展示，暂不支持修改）"
                    >
                        <TextArea
                            placeholder="请输入知识库描述"
                            rows={4}
                            maxLength={500}
                            showCount
                            disabled
                        />
                    </Form.Item>

                    {/* 只读信息 */}
                    <div className="readonly-info">
                        <div className="info-item">
                            <span className="info-label">索引方式：</span>
                            <span className="info-value">
                                {dataset.indexing_technique === 'high_quality' ? '高质量' : '经济'}
                            </span>
                        </div>
                        {/* <div className="info-item">
                            <span className="info-label">Embedding 模型：</span>
                            <span className="info-value">
                                {dataset.embedding_model || '默认模型'}
                            </span>
                        </div> */}
                        <div className="info-item">
                            <span className="info-label">文档数量：</span>
                            <span className="info-value">{dataset.document_count}</span>
                        </div>
                        <div className="info-item">
                            <span className="info-label">总字符数：</span>
                            <span className="info-value">{dataset.word_count?.toLocaleString()}</span>
                        </div>
                        <div className="info-item">
                            <span className="info-label">创建时间：</span>
                            <span className="info-value">
                                {new Date(dataset.created_at * 1000).toLocaleString('zh-CN')}
                            </span>
                        </div>
                    </div>

                    {/* 操作按钮 */}
                    <div className="form-actions">
                        <Button onClick={handleReset} disabled={!hasChanges}>
                            重置
                        </Button>
                        <Button
                            type="primary"
                            icon={<SaveOutlined />}
                            onClick={handleSave}
                            loading={saving}
                            disabled={!hasChanges}
                        >
                            保存
                        </Button>
                    </div>
                </Form>
            </Card>
        </div>
    );
}
