import React, { useEffect, useState } from 'react';
import { Table, Button, Modal, Form, Input, Space, message, Card, Row, Col, Collapse, Tabs, Badge, Tooltip, Radio } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, ReloadOutlined, SyncOutlined, 
  EyeOutlined, CodeOutlined, BuildOutlined, HistoryOutlined, FolderOutlined } from '@ant-design/icons';
import type { JenkinsDTO, JenkinsQuery, JenkinsViewDTO, JenkinsJobDTO, JenkinsBuildDTO } from './types';
import * as jenkinsService from './service';
import SyncStatusDrawer from './components/SyncStatusDrawer';
import dayjs from 'dayjs';

const { Panel } = Collapse;
const { TabPane } = Tabs;

interface JenkinsDetailDTO extends JenkinsDTO {
  views?: {
    viewName: string;
    viewUrl: string;
    description?: string;
  }[];
  jobs?: {
    jobName: string;
    jobUrl: string;
    lastBuildStatus?: string;
    lastBuildTime?: string;
  }[];
  builds?: {
    buildNumber: number;
    buildStatus: string;
    startTime: string;
    duration: number;
    triggerCause?: string;
  }[];
}

const JenkinsPage: React.FC = () => {
  const [jenkinsList, setJenkinsList] = useState<JenkinsDetailDTO[]>([]);
  const [loading, setLoading] = useState(false);
  const [syncLoading, setSyncLoading] = useState(false);
  const [selectedJenkins, setSelectedJenkins] = useState<number>();
  const [syncStatusVisible, setSyncStatusVisible] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingJenkins, setEditingJenkins] = useState<JenkinsDetailDTO | null>(null);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [viewLoading, setViewLoading] = useState<Record<number, boolean>>({});
  const [viewData, setViewData] = useState<Record<number, JenkinsViewDTO[]>>({});
  const [jobLoading, setJobLoading] = useState<Record<number, boolean>>({});
  const [jobData, setJobData] = useState<Record<number, JenkinsJobDTO[]>>({});
  const [buildLoading, setBuildLoading] = useState<Record<string, boolean>>({});
  const [buildData, setBuildData] = useState<Record<string, JenkinsBuildDTO[]>>({});
  const [viewPagination, setViewPagination] = useState<Record<number, { current: number; pageSize: number }>>({});
  const [jobPagination, setJobPagination] = useState<Record<number, { current: number; pageSize: number }>>({});
  const [buildPagination, setBuildPagination] = useState<Record<string, { current: number; pageSize: number }>>({});
  const [selectedRow, setSelectedRow] = useState<JenkinsDTO>();
  const [selectedView, setSelectedView] = useState<string>();

  const DEFAULT_PAGE_SIZE = 10;

  const fetchJenkinsList = async (params?: JenkinsQuery) => {
    try {
      setLoading(true);
      const response = await jenkinsService.getJenkinsList(params);
      setJenkinsList(response || []);
    } catch (error) {
      console.error('获取Jenkins列表失败:', error);
      message.error('获取Jenkins列表失败');
    } finally {
      setLoading(false);
    }
  };

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

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

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

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

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

  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个Jenkins配置吗？',
      onOk: async () => {
        try {
          await jenkinsService.deleteJenkins(id);
          message.success('删除成功');
          fetchJenkinsList();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingJenkins) {
        await jenkinsService.updateJenkins(editingJenkins.id, values);
        message.success('更新成功');
      } else {
        await jenkinsService.createJenkins(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchJenkinsList();
    } catch (error) {
      message.error('操作失败');
    }
  };

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

  const handleSync = async (id: number, type: 'ALL' | 'VIEW' | 'JOB' | 'BUILD') => {
    try {
      setSelectedJenkins(id);
      setSyncLoading(true);
      
      if (!id) {
        message.error('Jenkins ID 不能为空');
        return;
      }

      await jenkinsService.sync(id, type);
      message.success('同步任务已开始');
      setSyncStatusVisible(true);
    } catch (error: any) {
      if (error.response?.data?.message === '该Jenkins已有同步任务正在运行中') {
        message.warning('该Jenkins已有同步任务正在运行中');
      } else {
        message.error('同步失败');
      }
    } finally {
      setSyncLoading(false);
      setSelectedJenkins(undefined);
    }
  };

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

  const fetchViewData = async (jenkinsId: number) => {
    if (viewData[jenkinsId]) {
      return;
    }

    try {
      setViewLoading(prev => ({ ...prev, [jenkinsId]: true }));
      const response = await jenkinsService.getJenkinsViews(jenkinsId);
      setViewData(prev => ({ ...prev, [jenkinsId]: response || [] }));
    } catch (error) {
      console.error('获取视图列表失败:', error);
      message.error('获取视图列表失败');
    } finally {
      setViewLoading(prev => ({ ...prev, [jenkinsId]: false }));
    }
  };

  const fetchJobData = async (jenkinsId: number) => {
    if (jobData[jenkinsId]) {
      return;
    }

    try {
      setJobLoading(prev => ({ ...prev, [jenkinsId]: true }));
      const response = await jenkinsService.getJenkinsJobs(jenkinsId);
      setJobData(prev => ({ ...prev, [jenkinsId]: response || [] }));
    } catch (error) {
      console.error('获取作业列表失败:', error);
      message.error('获取作业列表失败');
    } finally {
      setJobLoading(prev => ({ ...prev, [jenkinsId]: false }));
    }
  };

  const fetchBuildData = async (jenkinsId: number, jobId: number) => {
    const key = `${jenkinsId}-${jobId}`;
    if (buildData[key]) {
      return;
    }

    try {
      setBuildLoading(prev => ({ ...prev, [key]: true }));
      const response = await jenkinsService.getJenkinsBuilds(jenkinsId, jobId);
      setBuildData(prev => ({ ...prev, [key]: response || [] }));
    } catch (error) {
      console.error('获取构建历史失败:', error);
      message.error('获取构建历史失败');
    } finally {
      setBuildLoading(prev => ({ ...prev, [key]: false }));
    }
  };

  const columns = [
    {
      title: 'Jenkins名称',
      dataIndex: 'name',
      key: 'name',
      width: '12%',
    },
    {
      title: 'Jenkins地址',
      dataIndex: 'url',
      key: 'url',
      width: '15%',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: '8%',
    },
    {
      title: '最后全量同步时间',
      key: 'lastAllSyncTime',
      width: '15%',
      render: (_, record: JenkinsDTO) => (
        record.lastAllSyncTime ? dayjs(record.lastAllSyncTime).format('YYYY-MM-DD HH:mm:ss') : '-'
      ),
    },
    {
      title: '最后视图同步时间',
      key: 'lastViewSyncTime',
      width: '15%',
      render: (_, record: JenkinsDTO) => (
        record.lastViewSyncTime ? dayjs(record.lastViewSyncTime).format('YYYY-MM-DD HH:mm:ss') : '-'
      ),
    },
    {
      title: '最后作业同步时间',
      key: 'lastJobSyncTime',
      width: '15%',
      render: (_, record: JenkinsDTO) => (
        record.lastJobSyncTime ? dayjs(record.lastJobSyncTime).format('YYYY-MM-DD HH:mm:ss') : '-'
      ),
    },
    {
      title: '最后构建同步时间',
      key: 'lastBuildSyncTime',
      width: '12%',
      render: (_, record: JenkinsDTO) => (
        record.lastBuildSyncTime ? dayjs(record.lastBuildSyncTime).format('YYYY-MM-DD HH:mm:ss') : '-'
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: '20%',
      render: (_, record: JenkinsDTO) => (
        <Space>
          <Button
            type="link"
            icon={<SyncOutlined />}
            loading={syncLoading && selectedJenkins === record.id}
            onClick={() => handleSync(record.id, 'ALL')}
          >
            全量同步
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleExpand = async (expanded: boolean, record: JenkinsDetailDTO) => {
    if (expanded) {
      await Promise.all([
        fetchViewData(record.id),
        fetchJobData(record.id)
      ]);
      
      const jobs = jobData[record.id] || [];
      await Promise.all(
        jobs.map(job => fetchBuildData(record.id, job.id))
      );
    }
  };

  const expandedRowRender = (record: JenkinsDetailDTO) => {
    return (
      <div style={{ width: '100%', padding: '16px 0' }}>
        {/* 视图选择器 */}
        <Radio.Group 
          value={selectedView} 
          onChange={(e) => {
            setSelectedView(e.target.value);
            fetchJobData(record.id);
          }}
          style={{ marginBottom: 16 }}
        >
          <Radio.Button value={undefined}>全部视图</Radio.Button>
          {viewData[record.id]?.map(view => (
            <Radio.Button key={view.id} value={view.viewName}>
              <Space>
                <FolderOutlined />
                {view.viewName}
              </Space>
            </Radio.Button>
          ))}
        </Radio.Group>

        {/* 作业和构建历史 */}
        <Tabs
          tabPosition="left"
          style={{ 
            height: 600,
            border: '1px solid #f0f0f0',
            borderRadius: '8px',
            padding: '16px'
          }}
          items={
            jobData[record.id]
              ?.filter(job => !selectedView || job.viewName === selectedView)
              ?.map(job => ({
                label: (
                  <Tooltip title={job.description} placement="right">
                    <Space>
                      <CodeOutlined />
                      {job.jobName}
                      {job.lastBuildStatus && (
                        <Badge 
                          status={job.lastBuildStatus === 'SUCCESS' ? 'success' : job.lastBuildStatus === 'FAILURE' ? 'error' : 'default'} 
                        />
                      )}
                    </Space>
                  </Tooltip>
                ),
                key: job.id.toString(),
                children: (
                  <div>
                    <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Space>
                        <span>最后构建状态：</span>
                        {job.lastBuildStatus && (
                          <Badge 
                            status={job.lastBuildStatus === 'SUCCESS' ? 'success' : job.lastBuildStatus === 'FAILURE' ? 'error' : 'default'} 
                            text={job.lastBuildStatus} 
                          />
                        )}
                      </Space>
                      <Button
                        type="link"
                        size="small"
                        icon={<SyncOutlined />}
                        onClick={() => fetchBuildData(record.id, job.id)}
                        loading={buildLoading[`${record.id}-${job.id}`]}
                      >
                        刷新构建历史
                      </Button>
                    </div>
                    <Table
                      size="small"
                      loading={buildLoading[`${record.id}-${job.id}`]}
                      columns={[
                        {
                          title: '构建编号',
                          dataIndex: 'buildNumber',
                          width: 100,
                        },
                        {
                          title: '构建状态',
                          dataIndex: 'buildStatus',
                          width: 120,
                          render: (status: string) => (
                            <Badge 
                              status={status === 'SUCCESS' ? 'success' : status === 'FAILURE' ? 'error' : 'default'} 
                              text={status || '-'} 
                            />
                          ),
                        },
                        {
                          title: '开始时间',
                          dataIndex: 'startTime',
                          width: 180,
                          render: (time: string) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-',
                        },
                        {
                          title: '持续时间',
                          dataIndex: 'duration',
                          width: 100,
                          render: (duration: number) => {
                            const seconds = Math.floor(duration / 1000);
                            if (seconds < 60) return `${seconds}秒`;
                            const minutes = Math.floor(seconds / 60);
                            const remainingSeconds = seconds % 60;
                            return `${minutes}分${remainingSeconds}秒`;
                          },
                        },
                        {
                          title: '触发原因',
                          dataIndex: 'triggerCause',
                          ellipsis: true,
                        },
                        {
                          title: '操作',
                          key: 'action',
                          width: 100,
                          fixed: 'right',
                          render: (_, record: JenkinsBuildDTO) => (
                            <a href={record.buildUrl} target="_blank" rel="noopener noreferrer">
                              查看详情
                            </a>
                          ),
                        }
                      ]}
                      dataSource={buildData[`${record.id}-${job.id}`] || []}
                      rowKey="id"
                      pagination={{
                        size: 'small',
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条`,
                      }}
                    />
                  </div>
                ),
              })) || []
          }
        />
      </div>
    );
  };

  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="Jenkins名称">
                <Input placeholder="请输入Jenkins名称" allowClear />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="url" label="Jenkins地址">
                <Input placeholder="请输入Jenkins地址" 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}>
              新增Jenkins
            </Button>
          </Col>
          <Col>
            <Space>
              <Button
                type="primary"
                icon={<SyncOutlined />}
                onClick={() => selectedRow && handleSync(selectedRow.id, 'ALL')}
                disabled={!selectedRow}
              >
                全量同步
              </Button>
              <Button
                type="primary"
                icon={<EyeOutlined />}
                onClick={() => selectedRow && handleSync(selectedRow.id, 'VIEW')}
                disabled={!selectedRow}
              >
                视图同步
              </Button>
              <Button
                type="primary"
                icon={<CodeOutlined />}
                onClick={() => selectedRow && handleSync(selectedRow.id, 'JOB')}
                disabled={!selectedRow}
              >
                作业同步
              </Button>
              <Button
                type="primary"
                icon={<BuildOutlined />}
                onClick={() => selectedRow && handleSync(selectedRow.id, 'BUILD')}
                disabled={!selectedRow}
              >
                构建同步
              </Button>
              <Button
                type="primary"
                icon={<HistoryOutlined />}
                onClick={() => setSyncStatusVisible(true)}
              >
                查看历史同步记录
              </Button>
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={jenkinsList}
          rowKey="id"
          expandable={{
            expandedRowRender,
            expandRowByClick: true,
            onExpand: handleExpand
          }}
          pagination={false}
          size="middle"
          bordered
          rowClassName={(record) => record.id === selectedRow?.id ? 'ant-table-row-selected' : ''}
          onRow={(record) => ({
            onClick: () => setSelectedRow(record)
          })}
        />
      </Card>

      <Modal
        title={editingJenkins ? '编辑Jenkins' : '新增Jenkins'}
        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="Jenkins名称"
            rules={[{ required: true, message: '请输入Jenkins名称' }]}
          >
            <Input placeholder="请输入Jenkins名称" />
          </Form.Item>

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

          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码/Token"
            rules={[{ required: true, message: '请输入密码或Token' }]}
          >
            <Input.Password placeholder="请输入密码或Token" />
          </Form.Item>

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

      <SyncStatusDrawer
        visible={syncStatusVisible}
        onClose={() => setSyncStatusVisible(false)}
      />
    </div>
  );
};

export default JenkinsPage; 