import React, { useEffect, useState } from 'react';
import { Table, Button, Modal, Form, Input, Space, message, Switch, Card, Row, Col, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SyncOutlined, SearchOutlined, ReloadOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import type { RepositoryDTO, RepositoryQuery } from './types';
import * as repositoryService from './service';
import SyncStatusDrawer from './components/SyncStatusDrawer';
import dayjs from 'dayjs';

const RepositoryPage: React.FC = () => {
  const [repositories, setRepositories] = useState<RepositoryDTO[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRepository, setEditingRepository] = useState<RepositoryDTO | null>(null);
  const [loading, setLoading] = useState(false);
  const [syncLoading, setSyncLoading] = useState(false);
  const [selectedRepository, setSelectedRepository] = useState<number>();
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [syncStatusVisible, setSyncStatusVisible] = useState(false);
  const [autoRefresh, setAutoRefresh] = useState(false);

  const fetchRepositories = async (params?: RepositoryQuery) => {
    try {
      setLoading(true);
      const response = await repositoryService.getRepositories(params);
      setRepositories(response || []);
    } catch (error) {
      console.error('获取代码库列表失败:', error);
      message.error('获取代码库列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRepositories();
  }, []);

  const handleSearch = async () => {
    const values = await searchForm.validateFields();
    fetchRepositories(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    fetchRepositories();
  };

  const handleAdd = () => {
    setEditingRepository(null);
    form.resetFields();
    form.setFieldsValue({
      enabled: true,
      sort: 0
    });
    setModalVisible(true);
  };

  const handleEdit = (record: RepositoryDTO) => {
    setEditingRepository(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个代码库吗？',
      onOk: async () => {
        try {
          await repositoryService.deleteRepository(id);
          message.success('删除成功');
          fetchRepositories();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSync = async (id: number) => {
    try {
      setSelectedRepository(id);
      setSyncLoading(true);
      await repositoryService.syncAll(id);
      message.success('同步任务已开始');
      setSyncStatusVisible(true);
      setAutoRefresh(true);
    } catch (error) {
      message.error('启动同步任务失败');
    } finally {
      setSyncLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setSyncStatusVisible(false);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingRepository) {
        await repositoryService.updateRepository(editingRepository.id, values);
        message.success('更新成功');
      } else {
        await repositoryService.createRepository(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchRepositories();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleTestConnection = async () => {
    try {
      const values = await form.validateFields(['url', 'accessToken', 'apiVersion']);
      await repositoryService.testConnection(values);
      message.success('连接测试成功');
    } catch (error) {
      message.error('连接测试失败，请检查配置');
    }
  };

  const columns = [
    {
      title: '仓库名称',
      dataIndex: 'name',
      key: 'name',
      width: '15%',
    },
    {
      title: '仓库地址',
      dataIndex: 'url',
      key: 'url',
      width: '20%',
    },
    {
      title: 'API版本',
      dataIndex: 'apiVersion',
      key: 'apiVersion',
      width: '10%',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: '15%',
    },
    {
      title: '最后同步时间',
      dataIndex: 'lastSyncTime',
      key: 'lastSyncTime',
      width: '15%',
      render: (text: string) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '-'
    },
    {
      title: '最后同步状态',
      dataIndex: 'lastSyncStatus',
      key: 'lastSyncStatus',
      width: '10%',
      render: (status: string) => {
        switch (status) {
          case 'SUCCESS':
            return <Tag icon={<CheckCircleOutlined />} color="success">成功</Tag>;
          case 'FAILED':
            return <Tag icon={<CloseCircleOutlined />} color="error">失败</Tag>;
          case 'RUNNING':
            return <Tag icon={<SyncOutlined spin />} color="processing">同步中</Tag>;
          default:
            return <Tag>未同步</Tag>;
        }
      }
    },
    {
      title: '操作',
      key: 'action',
      width: '15%',
      render: (_: any, record: RepositoryDTO) => (
        <Space>
          <Button
            type="link"
            icon={<SyncOutlined />}
            loading={syncLoading && selectedRepository === record.id}
            onClick={() => handleSync(record.id)}
          >
            同步
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card style={{ marginBottom: '24px' }}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
        >
          <Row gutter={24} style={{ width: '100%' }}>
            <Col span={8}>
              <Form.Item name="name" label="仓库名称">
                <Input placeholder="请输入仓库名称" allowClear />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="url" label="仓库地址">
                <Input placeholder="请输入仓库地址" allowClear />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Space>
                <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                  查询
                </Button>
                <Button icon={<ReloadOutlined />} onClick={handleReset}>
                  重置
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card>
        <Row justify="space-between" style={{ marginBottom: 16 }}>
          <Col>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增仓库
            </Button>
          </Col>
          <Col>
            <Button
              type="primary"
              icon={<SyncOutlined />}
              onClick={() => setSyncStatusVisible(true)}
            >
              查看历史同步记录
            </Button>
          </Col>
        </Row>

        <Table
          loading={loading}
          columns={columns}
          dataSource={repositories}
          rowKey="id"
          pagination={false}
          size="middle"
          bordered
        />
      </Card>

      <Modal
        title={editingRepository ? '编辑仓库' : '新增仓库'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={600}
        destroyOnClose
        footer={[
          <Button key="test" onClick={handleTestConnection}>
            测试连接
          </Button>,
          <Button key="cancel" onClick={() => setModalVisible(false)}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleSubmit}>
            确定
          </Button>,
        ]}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="仓库名称"
            rules={[{ required: true, message: '请输入仓库名称' }]}
          >
            <Input placeholder="请输入仓库名称" />
          </Form.Item>

          <Form.Item
            name="url"
            label="仓库地址"
            rules={[{ required: true, message: '请输入仓库地址' }]}
          >
            <Input placeholder="请输入仓库地址" />
          </Form.Item>

          <Form.Item
            name="accessToken"
            label="访问令牌"
            rules={[{ required: true, message: '请输入访问令牌' }]}
          >
            <Input.Password placeholder="请输入访问令牌" />
          </Form.Item>

          <Form.Item
            name="apiVersion"
            label="API版本"
          >
            <Input placeholder="请输入API版本" />
          </Form.Item>

          <Form.Item
            name="remark"
            label="备注"
          >
            <Input.TextArea rows={2} placeholder="请输入备注" />
          </Form.Item>
        </Form>
      </Modal>

      <SyncStatusDrawer
        visible={syncStatusVisible}
        onClose={handleDrawerClose}
        autoRefresh={autoRefresh}
      />
    </div>
  );
};

export default RepositoryPage; 