import {
  useState,
  useEffect,
  Table,
  Button,
  Input,
  Modal,
  Form,
  Select,
  Tag,
  Space,
  message,
  Popconfirm,
  Typography,
  Card,
  Row,
  Col,
  Progress,
  Tooltip,
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  LinkOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  SyncOutlined,
  GlobalOutlined,
  SafetyCertificateOutlined,
  Option,
  Title,
  Text,
  ReactNode,
  FC,
} from '@/imports';

interface Domain {
  id: string;
  domain: string;
  status: 'active' | 'pending' | 'error' | 'expired';
  siteId: string;
  siteName: string;
  ssl: boolean;
  sslExpiry?: string;
  registrar: string;
  expiryDate: string;
  autoRenew: boolean;
  dnsProvider: string;
  records: DNSRecord[];
}

interface DNSRecord {
  type: 'A' | 'CNAME' | 'MX' | 'TXT' | 'NS';
  name: string;
  value: string;
  ttl: number;
}

const mockDomains: Domain[] = [
  {
    id: '1',
    domain: 'mystore.com',
    status: 'active',
    siteId: 'site-1',
    siteName: '我的商店',
    ssl: true,
    sslExpiry: '2025-06-15',
    registrar: '阿里云',
    expiryDate: '2025-12-20',
    autoRenew: true,
    dnsProvider: '阿里云DNS',
    records: [
      { type: 'A', name: '@', value: '192.168.1.1', ttl: 600 },
      { type: 'CNAME', name: 'www', value: 'mystore.com', ttl: 600 },
    ],
  },
  {
    id: '2',
    domain: 'shop.example.cn',
    status: 'pending',
    siteId: 'site-2',
    siteName: '测试站点',
    ssl: false,
    registrar: '腾讯云',
    expiryDate: '2025-08-10',
    autoRenew: false,
    dnsProvider: 'DNSPod',
    records: [],
  },
];

const DomainManagement: FC = () => {
  const [domains, setDomains] = useState<Domain[]>(mockDomains);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [dnsModalVisible, setDnsModalVisible] = useState(false);
  const [selectedDomain, setSelectedDomain] = useState<Domain | null>(null);
  const [form] = Form.useForm();
  const [dnsForm] = Form.useForm();

  const getStatusTag = (status: string) => {
    const statusMap: Record<string, { color: string; icon: React.ReactNode; text: string }> = {
      active: { color: 'success', icon: <CheckCircleOutlined />, text: '正常' },
      pending: { color: 'processing', icon: <SyncOutlined spin />, text: '解析中' },
      error: { color: 'error', icon: <ExclamationCircleOutlined />, text: '异常' },
      expired: { color: 'warning', icon: <ExclamationCircleOutlined />, text: '已过期' },
    };
    const config = statusMap[status] || statusMap.error;
    return <Tag color={config.color} icon={config.icon}>{config.text}</Tag>;
  };

  const handleAddDomain = () => {
    setSelectedDomain(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEditDomain = (domain: Domain) => {
    setSelectedDomain(domain);
    form.setFieldsValue(domain);
    setModalVisible(true);
  };

  const handleSaveDomain = async () => {
    try {
      const values = await form.validateFields();
      if (selectedDomain) {
        setDomains(domains.map(d => d.id === selectedDomain.id ? { ...d, ...values } : d));
        message.success('域名已更新');
      } else {
        const newDomain: Domain = {
          id: `domain-${Date.now()}`,
          ...values,
          status: 'pending',
          ssl: false,
          records: [],
        };
        setDomains([...domains, newDomain]);
        message.success('域名已添加，正在解析...');
      }
      setModalVisible(false);
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  const handleDeleteDomain = (id: string) => {
    setDomains(domains.filter(d => d.id !== id));
    message.success('域名已删除');
  };

  const handleViewDNS = (domain: Domain) => {
    setSelectedDomain(domain);
    setDnsModalVisible(true);
  };

  const handleRenewSSL = (domain: Domain) => {
    message.loading('正在申请SSL证书...');
    setTimeout(() => {
      setDomains(domains.map(d => 
        d.id === domain.id ? { ...d, ssl: true, sslExpiry: '2026-03-21' } : d
      ));
      message.success('SSL证书已更新');
    }, 2000);
  };

  const columns = [
    {
      title: '域名',
      dataIndex: 'domain',
      key: 'domain',
      render: (domain: string) => (
        <Space>
          <GlobalOutlined />
          <a href={`https://${domain}`} target="_blank" rel="noopener noreferrer">{domain}</a>
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: getStatusTag,
    },
    {
      title: '关联站点',
      dataIndex: 'siteName',
      key: 'siteName',
    },
    {
      title: 'SSL证书',
      dataIndex: 'ssl',
      key: 'ssl',
      render: (ssl: boolean, record: Domain) => (
        ssl ? (
          <Tooltip title={`到期时间: ${record.sslExpiry}`}>
            <Tag color="success" icon={<SafetyCertificateOutlined />}>已启用</Tag>
          </Tooltip>
        ) : (
          <Tag color="warning">未启用</Tag>
        )
      ),
    },
    {
      title: '注册商',
      dataIndex: 'registrar',
      key: 'registrar',
    },
    {
      title: '到期时间',
      dataIndex: 'expiryDate',
      key: 'expiryDate',
      render: (date: string) => {
        const daysLeft = Math.ceil((new Date(date).getTime() - Date.now()) / (1000 * 60 * 60 * 24));
        return (
          <Tooltip title={`剩余 ${daysLeft} 天`}>
            <span style={{ color: daysLeft < 30 ? '#ff4d4f' : undefined }}>
              {date}
              {daysLeft < 30 && <ExclamationCircleOutlined style={{ marginLeft: 4, color: '#ff4d4f' }} />}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: '自动续费',
      dataIndex: 'autoRenew',
      key: 'autoRenew',
      render: (autoRenew: boolean) => (
        <Tag color={autoRenew ? 'blue' : 'default'}>{autoRenew ? '已开启' : '未开启'}</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Domain) => (
        <Space>
          <Button type="link" size="small" onClick={() => handleViewDNS(record)}>
            DNS解析
          </Button>
          {!record.ssl && (
            <Button type="link" size="small" onClick={() => handleRenewSSL(record)}>
              申请SSL
            </Button>
          )}
          <Button type="link" size="small" onClick={() => handleEditDomain(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此域名吗？"
            onConfirm={() => handleDeleteDomain(record.id)}
          >
            <Button type="link" size="small" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="domain-management" style={{ padding: 24 }}>
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <Title level={2} style={{ margin: 0, color: '#52c41a' }}>
                {domains.filter(d => d.status === 'active').length}
              </Title>
              <Text type="secondary">正常运行</Text>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <Title level={2} style={{ margin: 0, color: '#1890ff' }}>
                {domains.filter(d => d.status === 'pending').length}
              </Title>
              <Text type="secondary">解析中</Text>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <Title level={2} style={{ margin: 0, color: '#ff4d4f' }}>
                {domains.filter(d => d.status === 'error' || d.status === 'expired').length}
              </Title>
              <Text type="secondary">异常/过期</Text>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <Title level={2} style={{ margin: 0, color: '#52c41a' }}>
                {domains.filter(d => d.ssl).length}/{domains.length}
              </Title>
              <Text type="secondary">SSL已启用</Text>
            </div>
          </Card>
        </Col>
      </Row>

      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Title level={4} style={{ margin: 0 }}>域名列表</Title>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAddDomain}>
            添加域名
          </Button>
        </div>
        <Table
          columns={columns}
          dataSource={domains}
          rowKey="id"
          loading={loading}
        />
      </Card>

      <Modal
        title={selectedDomain ? '编辑域名' : '添加域名'}
        open={modalVisible}
        onOk={handleSaveDomain}
        onCancel={() => setModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="domain" label="域名" rules={[{ required: true, message: '请输入域名' }]}>
            <Input placeholder="example.com" />
          </Form.Item>
          <Form.Item name="siteId" label="关联站点">
            <Select placeholder="选择关联站点">
              <Option value="site-1">我的商店</Option>
              <Option value="site-2">测试站点</Option>
            </Select>
          </Form.Item>
          <Form.Item name="registrar" label="注册商">
            <Select placeholder="选择注册商">
              <Option value="阿里云">阿里云</Option>
              <Option value="腾讯云">腾讯云</Option>
              <Option value="GoDaddy">GoDaddy</Option>
              <Option value="Namecheap">Namecheap</Option>
              <Option value="Cloudflare">Cloudflare</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dnsProvider" label="DNS服务商">
            <Select placeholder="选择DNS服务商">
              <Option value="阿里云DNS">阿里云DNS</Option>
              <Option value="DNSPod">DNSPod</Option>
              <Option value="Cloudflare">Cloudflare</Option>
              <Option value="AWS Route53">AWS Route53</Option>
            </Select>
          </Form.Item>
          <Form.Item name="autoRenew" label="自动续费" valuePropName="checked">
            <Select>
              <Option value={true}>开启</Option>
              <Option value={false}>关闭</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={`DNS解析 - ${selectedDomain?.domain}`}
        open={dnsModalVisible}
        onCancel={() => setDnsModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDnsModalVisible(false)}>
            关闭
          </Button>,
          <Button key="add" type="primary" icon={<PlusOutlined />}>
            添加记录
          </Button>,
        ]}
        width={800}
      >
        <Table
          dataSource={selectedDomain?.records || []}
          rowKey={(r) => `${r.type}-${r.name}`}
          pagination={false}
          size="small"
        >
          <Table.Column title="类型" dataIndex="type" key="type" />
          <Table.Column title="主机记录" dataIndex="name" key="name" />
          <Table.Column title="记录值" dataIndex="value" key="value" />
          <Table.Column title="TTL" dataIndex="ttl" key="ttl" render={(ttl: number) => `${ttl}秒`} />
          <Table.Column
            title="操作"
            key="action"
            render={() => (
              <Space>
                <Button type="link" size="small">编辑</Button>
                <Button type="link" size="small" danger>删除</Button>
              </Space>
            )}
          />
        </Table>
      </Modal>
    </div>
  );
};

export default DomainManagement;
