import React, { useState, useEffect } from 'react';
import { 
  Card, Form, Input, Button, Space, Typography, 
  App, Divider, Skeleton 
} from 'antd';
import { 
  ArrowLeftOutlined, SaveOutlined, EditOutlined 
} from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import apiClient from '../utils/apiClient';
import { buildApiUrl, API_ENDPOINTS } from '../config/api';
import MarkdownEditor from '../components/MarkdownEditor';

const { Title } = Typography;

const EditKnowledgeBase = ({ user }) => {
  const { kb_id } = useParams();
  const navigate = useNavigate();
  const { message } = App.useApp();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    fetchKbDetail();
  }, [kb_id]);

  const fetchKbDetail = async () => {
    try {
      const response = await apiClient.get(buildApiUrl(API_ENDPOINTS.KNOWLEDGE_BASE.DETAIL(kb_id)));
      form.setFieldsValue(response.data);
    } catch (error) {
      message.error('加载知识库详情失败');
    } finally {
      setLoading(false);
    }
  };

  const onFinish = async (values) => {
    setSaving(true);
    try {
      await apiClient.put(buildApiUrl(API_ENDPOINTS.KNOWLEDGE_BASE.UPDATE(kb_id)), values);
      message.success('更新成功');
      navigate('/knowledge-base');
    } catch (error) {
      message.error('更新失败');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="edit-kb-modern" style={{ maxWidth: 1000, margin: '0 auto', padding: '24px 0' }}>
      <Card variant="borderless" style={{ borderRadius: 16, boxShadow: '0 4px 20px rgba(0,0,0,0.05)' }}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 32 }}>
          <Button icon={<ArrowLeftOutlined />} shape="circle" onClick={() => navigate(-1)} style={{ marginRight: 16 }} />
          <Title level={3} style={{ margin: 0 }}>编辑知识库条目</Title>
        </div>

        {loading ? <Skeleton active paragraph={{ rows: 10 }} /> : (
          <Form form={form} layout="vertical" onFinish={onFinish}>
            <Form.Item label="条目名称" name="title" rules={[{ required: true, message: '请输入名称' }]}>
              <Input size="large" prefix={<EditOutlined />} />
            </Form.Item>

            <Form.Item label="条目内容 (Markdown)" name="content" rules={[{ required: true }]}>
              <MarkdownEditor 
                height={500} 
                onChange={(val) => form.setFieldsValue({ content: val })} 
                value={form.getFieldValue('content')}
              />
            </Form.Item>

            <Divider />

            <Form.Item>
              <Button type="primary" htmlType="submit" size="large" icon={<SaveOutlined />} loading={saving} block style={{ height: 50, fontSize: 16, borderRadius: 8 }}>
                保存修改
              </Button>
            </Form.Item>
          </Form>
        )}
      </Card>
    </div>
  );
};

export default EditKnowledgeBase;
