import {
  useState,
  useEffect,
  Card,
  Table,
  Tag,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
  message,
  Row,
  Col,
  Badge,
  Tabs,
  Tree,
  Checkbox,
  Radio,
  Slider,
  Progress,
  Descriptions,
  Timeline,
  Tooltip,
  Popconfirm,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DisconnectOutlined,
  ReloadOutlined,
  EyeOutlined,
  SettingOutlined,
  AlertOutlined,
  GroupOutlined,
  HomeOutlined,
  MonitorOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  clientDataSource,
  Option,
  FC,
} from '@/imports';
import type { Client, ClientGroup } from '../services/clientDataSource';

const ClientManagement: FC = () => {
  const [clients, setClients] = useState<Client[]>([]);
  const [groups, setGroups] = useState<ClientGroup[]>([]);
  const [selectedClient, setSelectedClient] = useState<Client | null>(null);
  const [selectedGroup, setSelectedGroup] = useState<ClientGroup | null>(null);
  const [connectModalVisible, setConnectModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [groupModalVisible, setGroupModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [monitoringModalVisible, setMonitoringModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('all');
  const [selectedGroupId, setSelectedGroupId] = useState('all');
  const [connectForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [groupForm] = Form.useForm();

  useEffect(() => {
    fetchClients();
    fetchGroups();
    const interval = setInterval(fetchClients, 5000);
    return () => clearInterval(interval);
  }, []);

  const fetchClients = async () => {
    try {
      const clientList = await clientDataSource.fetchClients();
      setClients(clientList);
    } catch (error) {
      message.error('Failed to load clients');
    }
  };

  const fetchGroups = async () => {
    try {
      const groupList = await clientDataSource.fetchGroups();
      setGroups(groupList);
    } catch (error) {
      message.error('Failed to load groups');
    }
  };

  const handleConnect = async () => {
    try {
      const values = await connectForm.validateFields();
      setLoading(true);
      await clientDataSource.connectClient(
        values.host,
        values.port,
        values.name,
        values.groupId,
        values.description
      );
      message.success('Client connected successfully');
      setConnectModalVisible(false);
      connectForm.resetFields();
      fetchClients();
      fetchGroups();
    } catch (error) {
      message.error('Failed to connect to client');
    } finally {
      setLoading(false);
    }
  };

  const handleDisconnect = async (clientId: string) => {
    try {
      await clientDataSource.disconnectClient(clientId);
      message.success('Client disconnected successfully');
      fetchClients();
      fetchGroups();
    } catch (error) {
      message.error('Failed to disconnect client');
    }
  };

  const handleEdit = (client: Client) => {
    setSelectedClient(client);
    editForm.setFieldsValue({
      name: client.name,
      host: client.host,
      port: client.port,
      groupId: client.groupId,
      tags: client.tags,
      description: client.description,
    });
    setEditModalVisible(true);
  };

  const handleEditSubmit = async () => {
    try {
      const values = await editForm.validateFields();
      if (selectedClient) {
        await clientDataSource.updateClient(selectedClient.id, values);
        setEditModalVisible(false);
        message.success('Client updated successfully');
        fetchClients();
        fetchGroups();
      }
    } catch (error) {
      message.error('Failed to update client');
    }
  };

  const handleCreateGroup = async () => {
    try {
      const values = await groupForm.validateFields();
      await clientDataSource.createGroup({
        name: values.name,
        description: values.description,
        color: values.color,
      });
      setGroupModalVisible(false);
      groupForm.resetFields();
      message.success('Group created successfully');
      fetchGroups();
    } catch (error) {
      message.error('Failed to create group');
    }
  };

  const handleViewDetail = (client: Client) => {
    setSelectedClient(client);
    setDetailModalVisible(true);
  };

  const handleViewMonitoring = (client: Client) => {
    setSelectedClient(client);
    setMonitoringModalVisible(true);
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'connected':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'disconnected':
        return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
      case 'error':
        return <AlertOutlined style={{ color: '#faad14' }} />;
      default:
        return <ClockCircleOutlined style={{ color: '#1890ff' }} />;
    }
  };

  const getFilteredClients = () => {
    let filtered = clients;

    if (activeTab !== 'all') {
      filtered = filtered.filter((c) => c.status === activeTab);
    }

    if (selectedGroupId !== 'all') {
      filtered = filtered.filter((c) => c.groupId === selectedGroupId);
    }

    return filtered;
  };

  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: Client) => (
        <Space size="middle">
          {getStatusIcon(record.status)}
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: 'Host:Port',
      dataIndex: 'host',
      key: 'host',
      render: (host: string, record: Client) => `${host}:${record.port}`,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        let color = 'default';
        switch (status) {
          case 'connected':
            color = 'success';
            break;
          case 'disconnected':
            color = 'error';
            break;
          case 'error':
            color = 'warning';
            break;
        }
        return <Tag color={color}>{status}</Tag>;
      },
    },
    {
      title: 'Group',
      dataIndex: 'groupId',
      key: 'groupId',
      render: (groupId: string) => {
        const group = groups.find(g => g.id === groupId);
        return group ? <Tag color={group.color}>{group.name}</Tag> : <Tag color="default">Ungrouped</Tag>;
      },
    },
    {
      title: 'Last Seen',
      dataIndex: 'lastSeen',
      key: 'lastSeen',
      render: (lastSeen: Date) => new Date(lastSeen).toLocaleString(),
    },
    {
      title: 'Performance',
      dataIndex: 'performance',
      key: 'performance',
      render: (performance: any) => (
        <Space direction="vertical">
          <div>
            <span>CPU: {performance?.cpu?.toFixed(1)}%</span>
            <Progress percent={performance?.cpu || 0} size="small" />
          </div>
          <div>
            <span>Memory: {performance?.memory?.toFixed(1)}%</span>
            <Progress percent={performance?.memory || 0} size="small" />
          </div>
        </Space>
      ),
    },
    {
      title: 'Actions',
      key: 'action',
      render: (_: any, record: Client) => (
        <Space size="small">
          <Tooltip title="View Details">
            <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)} />
          </Tooltip>
          <Tooltip title="View Monitoring">
            <Button type="link" icon={<MonitorOutlined />} onClick={() => handleViewMonitoring(record)} />
          </Tooltip>
          {record.status === 'disconnected' && (
            <Tooltip title="Connect">
              <Button type="link" icon={<PlusOutlined />} onClick={() => setConnectModalVisible(true)} />
            </Tooltip>
          )}
          {record.status === 'connected' && (
            <Popconfirm
              title="Are you sure to disconnect this client?"
              onConfirm={() => handleDisconnect(record.id)}
              okText="Yes"
              cancelText="No"
            >
              <Tooltip title="Disconnect">
                <Button type="link" danger icon={<DisconnectOutlined />} />
              </Tooltip>
            </Popconfirm>
          )}
          <Tooltip title="Edit">
            <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)} />
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <div className="client-management">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card
            title={
              <Space size="middle">
                <HomeOutlined style={{ color: '#1890ff' }} />
                <span>Client Management</span>
              </Space>
            }
            extra={
              <Space>
                <Button icon={<ReloadOutlined />} onClick={fetchClients}>
                  Refresh
                </Button>
                <Button type="primary" icon={<PlusOutlined />} onClick={() => setConnectModalVisible(true)}>
                  Connect Client
                </Button>
              </Space>
            }
          >
            <Tabs activeKey={activeTab} onChange={setActiveTab}>
              <Tabs.TabPane tab="All Clients" key="all" />
              <Tabs.TabPane tab="Connected" key="connected" />
              <Tabs.TabPane tab="Disconnected" key="disconnected" />
              <Tabs.TabPane tab="Error" key="error" />
            </Tabs>

            <Card size="small" style={{ marginBottom: 16, marginTop: 16 }}>
              <Row gutter={16}>
                <Col span={8}>
                  <Select
                    placeholder="Filter by group"
                    value={selectedGroupId}
                    onChange={setSelectedGroupId}
                    style={{ width: '100%' }}
                  >
                    <Option value="all">All Groups</Option>
                    {groups.map((group) => (
                      <Option key={group.id} value={group.id}>
                        {group.name}
                      </Option>
                    ))}
                  </Select>
                </Col>
                <Col span={8}>
                  <Button icon={<GroupOutlined />} onClick={() => setGroupModalVisible(true)}>
                    Manage Groups
                  </Button>
                </Col>
              </Row>
            </Card>

            <Table
              columns={columns}
              dataSource={getFilteredClients()}
              rowKey="id"
              loading={loading}
              scroll={{ x: 1400 }}
              pagination={{
                showSizeChanger: true,
                showTotal: (total) => `Total ${total} clients`,
              }}
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card
            title={
              <Space size="middle">
                <GroupOutlined style={{ color: '#1890ff' }} />
                <span>Client Groups</span>
              </Space>
            }
          >
            <Tree
              defaultExpandAll
              treeData={[
                {
                  title: 'All Clients',
                  key: 'all',
                  children: groups.map((group) => ({
                    title: (
                      <Space size="middle">
                        <Tag color={group.color}>{group.name}</Tag>
                        <span style={{ fontSize: 12, color: '#999' }}>{group.clientIds.length} clients</span>
                      </Space>
                    ),
                    key: group.id,
                    children: clients
                      .filter((c) => c.groupId === group.id)
                      .map((c) => ({
                        title: (
                          <Space size="middle">
                            {getStatusIcon(c.status)}
                            <span>{c.name}</span>
                            <Tag color={c.status === 'connected' ? 'success' : 'error'}>{c.status}</Tag>
                          </Space>
                        ),
                        key: c.id,
                      })),
                  })),
                },
              ]}
              onSelect={(selectedKeys) => {
                if (selectedKeys.length > 0) {
                  setSelectedGroupId(String(selectedKeys[0]));
                }
              }}
            />
          </Card>
        </Col>
      </Row>

      <Modal
        title="Connect to Client"
        open={connectModalVisible}
        onOk={handleConnect}
        onCancel={() => setConnectModalVisible(false)}
        loading={loading}
      >
        <Form form={connectForm} layout="vertical">
          <Form.Item
            name="name"
            label="Client Name"
            rules={[{ required: true, message: 'Please enter client name' }]}
          >
            <Input placeholder="Enter client name" />
          </Form.Item>
          <Form.Item
            name="host"
            label="Host"
            rules={[{ required: true, message: 'Please enter host' }]}
          >
            <Input placeholder="Enter host (e.g., localhost)" />
          </Form.Item>
          <Form.Item
            name="port"
            label="Port"
            rules={[{ required: true, message: 'Please enter port' }]}
          >
            <InputNumber min={1} max={65535} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="groupId"
            label="Group"
          >
            <Select placeholder="Select group">
              <Option value="">Ungrouped</Option>
              {groups.map((group) => (
                <Option key={group.id} value={group.id}>
                  {group.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="description"
            label="Description"
          >
            <Input.TextArea rows={3} placeholder="Enter description" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Edit Client"
        open={editModalVisible}
        onOk={handleEditSubmit}
        onCancel={() => setEditModalVisible(false)}
      >
        <Form form={editForm} layout="vertical">
          <Form.Item
            name="name"
            label="Client Name"
            rules={[{ required: true, message: 'Please enter client name' }]}
          >
            <Input placeholder="Enter client name" />
          </Form.Item>
          <Form.Item
            name="host"
            label="Host"
            rules={[{ required: true, message: 'Please enter host' }]}
          >
            <Input placeholder="Enter host (e.g., localhost)" />
          </Form.Item>
          <Form.Item
            name="port"
            label="Port"
            rules={[{ required: true, message: 'Please enter port' }]}
          >
            <InputNumber min={1} max={65535} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="groupId"
            label="Group"
          >
            <Select placeholder="Select group">
              <Option value="">Ungrouped</Option>
              {groups.map((group) => (
                <Option key={group.id} value={group.id}>
                  {group.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="tags"
            label="Tags"
          >
            <Select mode="tags" placeholder="Enter tags" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="description"
            label="Description"
          >
            <Input.TextArea rows={3} placeholder="Enter description" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Manage Groups"
        open={groupModalVisible}
        onOk={handleCreateGroup}
        onCancel={() => setGroupModalVisible(false)}
      >
        <Form form={groupForm} layout="vertical">
          <Form.Item
            name="name"
            label="Group Name"
            rules={[{ required: true, message: 'Please enter group name' }]}
          >
            <Input placeholder="Enter group name" />
          </Form.Item>
          <Form.Item
            name="description"
            label="Description"
          >
            <Input.TextArea rows={3} placeholder="Enter description" />
          </Form.Item>
          <Form.Item
            name="color"
            label="Color"
            rules={[{ required: true, message: 'Please select color' }]}
          >
            <Select placeholder="Select color">
              <Option value="#1890ff">Blue</Option>
              <Option value="#52c41a">Green</Option>
              <Option value="#faad14">Orange</Option>
              <Option value="#ff4d4f">Red</Option>
              <Option value="#722ed1">Purple</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Client Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={800}
      >
        {selectedClient && (
          <>
            <Descriptions column={2} bordered>
              <Descriptions.Item label="Name">{selectedClient.name}</Descriptions.Item>
              <Descriptions.Item label="Host:Port">{selectedClient.host}:{selectedClient.port}</Descriptions.Item>
              <Descriptions.Item label="Status">
                <Tag color={selectedClient.status === 'connected' ? 'success' : selectedClient.status === 'error' ? 'warning' : 'error'}>
                  {selectedClient.status}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Last Seen">{new Date(selectedClient.lastSeen).toLocaleString()}</Descriptions.Item>
              <Descriptions.Item label="Group">
                {selectedClient.groupId ? (
                  <Tag color={groups.find(g => g.id === selectedClient.groupId)?.color || 'default'}>
                    {groups.find(g => g.id === selectedClient.groupId)?.name || 'Unknown'}
                  </Tag>
                ) : (
                  <Tag color="default">Ungrouped</Tag>
                )}
              </Descriptions.Item>
              <Descriptions.Item label="Description">{selectedClient.description || '-'}</Descriptions.Item>
            </Descriptions>

            <Card title="Performance" style={{ marginTop: 16 }}>
              <Row gutter={16}>
                <Col span={8}>
                  <Card size="small">
                    <div style={{ textAlign: 'center' }}>
                      <h4>CPU</h4>
                      <Progress percent={selectedClient.performance?.cpu || 0} status="active" />
                      <p>{selectedClient.performance?.cpu?.toFixed(1)}%</p>
                    </div>
                  </Card>
                </Col>
                <Col span={8}>
                  <Card size="small">
                    <div style={{ textAlign: 'center' }}>
                      <h4>Memory</h4>
                      <Progress percent={selectedClient.performance?.memory || 0} status="active" />
                      <p>{selectedClient.performance?.memory?.toFixed(1)}%</p>
                    </div>
                  </Card>
                </Col>
                <Col span={8}>
                  <Card size="small">
                    <div style={{ textAlign: 'center' }}>
                      <h4>Network</h4>
                      <Progress percent={selectedClient.performance?.network || 0} status="active" />
                      <p>{selectedClient.performance?.network?.toFixed(1)}%</p>
                    </div>
                  </Card>
                </Col>
              </Row>
            </Card>

            <Card title="History" style={{ marginTop: 16 }}>
              <Timeline>
                {selectedClient.history?.map((item, index) => (
                  <Timeline.Item key={index} color={item.status === 'connected' ? 'green' : 'red'}>
                    <div>
                      <p>{item.message}</p>
                      <p style={{ fontSize: 12, color: '#999' }}>{new Date(item.timestamp).toLocaleString()}</p>
                    </div>
                  </Timeline.Item>
                ))}
              </Timeline>
            </Card>
          </>
        )}
      </Modal>

      <Modal
        title="Client Monitoring"
        open={monitoringModalVisible}
        onCancel={() => setMonitoringModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setMonitoringModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={800}
      >
        {selectedClient && (
          <Card>
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <h3>{selectedClient.name}</h3>
              <p>{selectedClient.host}:{selectedClient.port}</p>
              <Tag color={selectedClient.status === 'connected' ? 'success' : 'error'}>
                {selectedClient.status}
              </Tag>
            </div>

            <div style={{ height: 400, marginBottom: 24 }}>
              {/* 这里可以添加实时监控图表 */}
              <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: '#f5f5f5' }}>
                <p>Real-time monitoring chart would appear here</p>
              </div>
            </div>

            <Row gutter={16}>
              <Col span={8}>
                <Card size="small" title="CPU Usage">
                  <Progress percent={selectedClient.performance?.cpu || 0} status="active" />
                  <p style={{ marginTop: 8, textAlign: 'center' }}>{selectedClient.performance?.cpu?.toFixed(1)}%</p>
                </Card>
              </Col>
              <Col span={8}>
                <Card size="small" title="Memory Usage">
                  <Progress percent={selectedClient.performance?.memory || 0} status="active" />
                  <p style={{ marginTop: 8, textAlign: 'center' }}>{selectedClient.performance?.memory?.toFixed(1)}%</p>
                </Card>
              </Col>
              <Col span={8}>
                <Card size="small" title="Network Usage">
                  <Progress percent={selectedClient.performance?.network || 0} status="active" />
                  <p style={{ marginTop: 8, textAlign: 'center' }}>{selectedClient.performance?.network?.toFixed(1)}%</p>
                </Card>
              </Col>
            </Row>
          </Card>
        )}
      </Modal>
    </div>
  );
};

export default ClientManagement;
