import {
  CheckCircleOutlined,
  CopyOutlined,
  GlobalOutlined,
  LinkOutlined,
  PlusOutlined,
  ReloadOutlined,
  SafetyCertificateOutlined,
} from '@ant-design/icons';
import {
  Alert,
  App,
  Button,
  Card,
  Col,
  Descriptions,
  Drawer,
  Empty,
  Flex,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Space,
  Table,
  Tag,
  Typography,
} from 'antd';
import { useCallback, useEffect, useMemo, useState } from 'react';
import type { components } from '../api/schema.generated';
import { platformRequest } from '../api/platform';

type TenantItem = components['schemas']['PlatformTenantItem'];
type TenantList = components['schemas']['PlatformTenantList'];
type TenantDetail = components['schemas']['PlatformTenantDetail'];
type ProvisioningResult = components['schemas']['PlatformTenantProvisioningResult'];
type ActivationResult = components['schemas']['PlatformOwnerActivationLinkResult'];
type CreateTenantBody = components['schemas']['CreatePlatformTenantDto'];

interface CreateValues {
  slug: string;
  name: string;
  legalName?: string;
  primaryDomainHost: string;
  ownerName: string;
  ownerEmail?: string;
  ownerPhone?: string;
  trialDays?: number;
}

const activationLabels: Record<string, string> = {
  domain_pending: '等待域名激活',
  ready_to_issue: '可领取激活链接',
  issued: '激活链接已签发',
  expired: '激活链接已过期',
  activated: 'Owner 已激活',
};

function activationColor(status: string) {
  if (status === 'activated') return 'green';
  if (status === 'ready_to_issue') return 'blue';
  if (status === 'issued') return 'gold';
  if (status === 'expired') return 'red';
  return 'default';
}

function primaryDomain(detail: TenantDetail | null) {
  return detail?.domains.find((item) => item.isPrimary) ?? null;
}

export function TenantOnboardingWorkbench() {
  const { message } = App.useApp();
  const [tenants, setTenants] = useState<TenantItem[]>([]);
  const [selectedTenantId, setSelectedTenantId] = useState<string>();
  const [detail, setDetail] = useState<TenantDetail | null>(null);
  const [loading, setLoading] = useState(false);
  const [createOpen, setCreateOpen] = useState(false);
  const [issueOpen, setIssueOpen] = useState(false);
  const [domainOpen, setDomainOpen] = useState(false);
  const [activationUrl, setActivationUrl] = useState<string>();
  const [activationExpiresAt, setActivationExpiresAt] = useState<string>();
  const [createForm] = Form.useForm<CreateValues>();
  const [issueForm] = Form.useForm<{ reason: string }>();
  const [domainForm] = Form.useForm<{ host: string; reason: string }>();

  const loadTenants = useCallback(async () => {
    const result = await platformRequest<TenantList>('GET', '/api/platform/tenants', {
      query: { Limit: 200 },
    });
    setTenants(result.items);
    setSelectedTenantId((current) => current ?? result.items[0]?.id);
  }, []);

  const loadDetail = useCallback(async (tenantId: string, quiet = false) => {
    if (!quiet) setLoading(true);
    try {
      const result = await platformRequest<TenantDetail>(
        'GET',
        '/api/platform/tenants/detail',
        { query: { tenantId } },
      );
      setDetail(result);
    } catch (error) {
      if (!quiet) message.error(error instanceof Error ? error.message : '租户开通状态加载失败');
    } finally {
      if (!quiet) setLoading(false);
    }
  }, [message]);

  useEffect(() => {
    setLoading(true);
    loadTenants().catch((error) => message.error(error instanceof Error ? error.message : '租户列表加载失败'))
      .finally(() => setLoading(false));
  }, [loadTenants, message]);

  useEffect(() => {
    if (!selectedTenantId) {
      setDetail(null);
      return;
    }
    void loadDetail(selectedTenantId);
    const timer = window.setInterval(() => void loadDetail(selectedTenantId, true), 5000);
    return () => window.clearInterval(timer);
  }, [loadDetail, selectedTenantId]);

  const domain = primaryDomain(detail);
  const activation = detail?.ownerActivation;
  const canIssue = activation?.status === 'ready_to_issue' || activation?.status === 'expired';
  const canReplace = activation?.status === 'issued';

  const createTenant = async () => {
    const values = await createForm.validateFields();
    if (!values.ownerEmail && !values.ownerPhone) {
      message.error('Owner 邮箱或手机号至少填写一项');
      return;
    }
    setLoading(true);
    try {
      const body: CreateTenantBody = {
        slug: values.slug,
        name: values.name,
        legalName: values.legalName,
        primaryDomainHost: values.primaryDomainHost,
        ownerName: values.ownerName,
        ownerEmail: values.ownerEmail,
        ownerPhone: values.ownerPhone,
        trialDays: values.trialDays,
        defaultPaymentProvider: 'manual',
      };
      const result = await platformRequest<ProvisioningResult>('POST', '/api/platform/tenants', {
        headers: { 'Idempotency-Key': crypto.randomUUID() },
        body,
      });
      message.success(result.isReplay ? '已返回同一开通请求的租户记录' : '租户已创建，请按指引配置 DNS');
      setCreateOpen(false);
      createForm.resetFields();
      await loadTenants();
      setSelectedTenantId(result.tenant.id);
      await loadDetail(result.tenant.id);
    } catch (error) {
      message.error(error instanceof Error ? error.message : '租户创建失败');
    } finally {
      setLoading(false);
    }
  };

  const issueActivation = async () => {
    if (!selectedTenantId || !activation) return;
    const values = await issueForm.validateFields();
    setLoading(true);
    try {
      const result = await platformRequest<ActivationResult>(
        'POST',
        '/api/platform/tenants/{tenantId}/owner-activation-links',
        {
          path: { tenantId: selectedTenantId },
          headers: { 'Idempotency-Key': crypto.randomUUID() },
          body: { reason: values.reason, replaceExisting: activation.status === 'issued' },
        },
      );
      setIssueOpen(false);
      issueForm.resetFields();
      if (result.activationUrl) {
        setActivationUrl(result.activationUrl);
        setActivationExpiresAt(result.expiresAt);
      } else {
        message.warning('这是幂等重放；为保护密钥，历史激活链接不能再次显示。');
      }
      await loadDetail(selectedTenantId);
    } catch (error) {
      message.error(error instanceof Error ? error.message : '激活链接领取失败');
    } finally {
      setLoading(false);
    }
  };

  const replaceDomain = async () => {
    if (!selectedTenantId) return;
    const values = await domainForm.validateFields();
    setLoading(true);
    try {
      await platformRequest('PUT', '/api/platform/tenants/{tenantId}/primary-domain', {
        path: { tenantId: selectedTenantId },
        body: values,
      });
      setDomainOpen(false);
      domainForm.resetFields();
      message.success('主域名已更正，旧链接已撤销，请重新配置 DNS');
      await loadDetail(selectedTenantId);
    } catch (error) {
      message.error(error instanceof Error ? error.message : '主域名更正失败');
    } finally {
      setLoading(false);
    }
  };

  const columns = useMemo(() => [
    { title: '租户', dataIndex: 'name', key: 'name' },
    { title: '短编码', dataIndex: 'slug', key: 'slug' },
    { title: '状态', dataIndex: 'status', key: 'status', render: (value: unknown) => <Tag>{String(value)}</Tag> },
    { title: '试用到期', dataIndex: 'subscriptionExpiresAt', key: 'subscriptionExpiresAt', render: (value: unknown) => value ? new Date(String(value)).toLocaleString('zh-CN') : '-' },
  ], []);

  return (
    <div className="business-page commercial-workbench">
      <Flex justify="space-between" align="end" gap={16} wrap>
        <div>
          <Typography.Text type="secondary">商业交付</Typography.Text>
          <Typography.Title level={2}>租户开通工作台</Typography.Title>
          <Typography.Paragraph type="secondary">创建租户和主域名，跟踪 DNS/TLS 激活，并一次性领取 Owner 建站链接。</Typography.Paragraph>
        </div>
        <Space>
          <Button icon={<ReloadOutlined />} onClick={() => void loadTenants()} loading={loading}>刷新</Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新建租户</Button>
        </Space>
      </Flex>

      <Row gutter={[16, 16]}>
        <Col xs={24} xl={10}>
          <Card title="开通租户">
            <Table
              size="small"
              loading={loading}
              dataSource={tenants}
              columns={columns}
              rowKey="id"
              pagination={{ pageSize: 10 }}
              rowSelection={{
                type: 'radio',
                selectedRowKeys: selectedTenantId ? [selectedTenantId] : [],
                onChange: (keys) => setSelectedTenantId(String(keys[0])),
              }}
              onRow={(record) => ({ onClick: () => setSelectedTenantId(record.id) })}
            />
          </Card>
        </Col>
        <Col xs={24} xl={14}>
          {!detail || !domain || !activation ? <Card><Empty description="请选择租户查看开通进度" /></Card> : (
            <Space direction="vertical" size={16} style={{ width: '100%' }}>
              <Card
                title={<Space><GlobalOutlined />主域名与 DNS</Space>}
                extra={<Button onClick={() => { domainForm.setFieldsValue({ host: domain.host }); setDomainOpen(true); }}>更正主域名</Button>}
              >
                <Alert
                  type={String(domain.status) === 'Active' ? 'success' : 'info'}
                  showIcon
                  message={String(domain.status) === 'Active' ? 'DNS 与 TLS 已激活' : '请完成以下 DNS 配置，系统每 5 秒刷新开通状态'}
                  style={{ marginBottom: 16 }}
                />
                <Descriptions column={1} bordered size="small" items={[
                  { key: 'host', label: '主域名', children: domain.host },
                  { key: 'cname', label: 'CNAME 目标', children: <Typography.Text copyable>{domain.cnameTarget || '-'}</Typography.Text> },
                  { key: 'txt-name', label: 'TXT 记录名', children: <Typography.Text copyable>{domain.verificationRecordName || '-'}</Typography.Text> },
                  { key: 'txt-value', label: 'TXT 记录值', children: <Typography.Text copyable>{domain.verificationToken || '-'}</Typography.Text> },
                  { key: 'checked', label: '最近检查', children: domain.lastCheckedAt ? new Date(domain.lastCheckedAt).toLocaleString('zh-CN') : '尚未检查' },
                ]} />
                {domain.lastFailureReason && <Alert type="warning" showIcon message="最近检查未通过" description={domain.lastFailureReason} style={{ marginTop: 16 }} />}
              </Card>

              <Card title={<Space><SafetyCertificateOutlined />Owner 激活</Space>}>
                <Flex justify="space-between" align="center" gap={16} wrap>
                  <div>
                    <Tag color={activationColor(activation.status)}>{activationLabels[activation.status] ?? activation.status}</Tag>
                    {activation.expiresAt && <Typography.Text type="secondary"> 有效期至 {new Date(activation.expiresAt).toLocaleString('zh-CN')}</Typography.Text>}
                  </div>
                  {(canIssue || canReplace) && (
                    <Button
                      type="primary"
                      danger={canReplace}
                      icon={<LinkOutlined />}
                      onClick={() => setIssueOpen(true)}
                    >
                      {canReplace ? '撤销并重新签发' : '领取激活链接'}
                    </Button>
                  )}
                  {activation.status === 'activated' && <Space><CheckCircleOutlined style={{ color: '#52c41a' }} />Owner 已完成激活</Space>}
                </Flex>
              </Card>
            </Space>
          )}
        </Col>
      </Row>

      <Drawer
        title="新建租户并配置主域名"
        width={600}
        open={createOpen}
        onClose={() => setCreateOpen(false)}
        footer={<Flex justify="end" gap={8}><Button onClick={() => setCreateOpen(false)}>取消</Button><Button type="primary" loading={loading} onClick={() => void createTenant()}>创建租户</Button></Flex>}
      >
        <Form form={createForm} layout="vertical" requiredMark="optional">
          <Row gutter={12}>
            <Col span={12}><Form.Item name="slug" label="租户短编码" rules={[{ required: true }, { pattern: /^[a-z][a-z0-9-]*$/, message: '请使用小写字母、数字和连字符' }]}><Input /></Form.Item></Col>
            <Col span={12}><Form.Item name="name" label="租户名称" rules={[{ required: true }]}><Input /></Form.Item></Col>
          </Row>
          <Form.Item name="legalName" label="法定名称"><Input /></Form.Item>
          <Form.Item name="primaryDomainHost" label="主域名" rules={[{ required: true }, { message: '只填写域名，不含协议、端口或路径', pattern: /^[^/:*]+\.[^/:*]+$/ }]}><Input placeholder="learn.example.com" /></Form.Item>
          <Form.Item name="ownerName" label="Owner 姓名" rules={[{ required: true }]}><Input /></Form.Item>
          <Row gutter={12}>
            <Col span={12}><Form.Item name="ownerEmail" label="Owner 邮箱"><Input /></Form.Item></Col>
            <Col span={12}><Form.Item name="ownerPhone" label="Owner 手机号"><Input /></Form.Item></Col>
          </Row>
          <Form.Item name="trialDays" label="试用天数" extra="留空使用平台默认配置"><InputNumber min={1} max={365} style={{ width: '100%' }} /></Form.Item>
        </Form>
      </Drawer>

      <Modal
        title={canReplace ? '撤销并重新签发激活链接' : '领取一次性激活链接'}
        open={issueOpen}
        onCancel={() => setIssueOpen(false)}
        onOk={() => void issueActivation()}
        confirmLoading={loading}
        okText={canReplace ? '确认撤销并签发' : '确认领取'}
        okButtonProps={{ danger: canReplace }}
      >
        {canReplace && <Alert type="warning" showIcon message="当前有效链接将立即失效" style={{ marginBottom: 16 }} />}
        <Form form={issueForm} layout="vertical">
          <Form.Item name="reason" label="操作原因" rules={[{ required: true, min: 3 }]}><Input.TextArea rows={3} /></Form.Item>
        </Form>
      </Modal>

      <Modal
        title="更正主域名"
        open={domainOpen}
        onCancel={() => setDomainOpen(false)}
        onOk={() => void replaceDomain()}
        confirmLoading={loading}
        okButtonProps={{ danger: true }}
      >
        <Alert type="warning" showIcon message="更正后旧主域名将停用，所有未消费激活链接都会撤销。" style={{ marginBottom: 16 }} />
        <Form form={domainForm} layout="vertical">
          <Form.Item name="host" label="新主域名" rules={[{ required: true }]}><Input /></Form.Item>
          <Form.Item name="reason" label="更正原因" rules={[{ required: true, min: 3 }]}><Input.TextArea rows={3} /></Form.Item>
        </Form>
      </Modal>

      <Modal
        title="一次性 Owner 激活链接"
        open={Boolean(activationUrl)}
        closable={false}
        maskClosable={false}
        onCancel={() => { setActivationUrl(undefined); setActivationExpiresAt(undefined); }}
        footer={[
          <Button key="copy" type="primary" icon={<CopyOutlined />} onClick={async () => {
            if (!activationUrl) return;
            await navigator.clipboard.writeText(activationUrl);
            message.success('激活链接已复制');
          }}>复制链接</Button>,
          <Button key="close" onClick={() => { setActivationUrl(undefined); setActivationExpiresAt(undefined); }}>我已安全保存，关闭</Button>,
        ]}
      >
        <Alert type="warning" showIcon message="链接只在本弹窗显示一次" description="关闭后平台无法恢复明文，请立即通过既有安全渠道交给租户 Owner。" />
        <Typography.Paragraph copyable={{ text: activationUrl }} style={{ marginTop: 16, wordBreak: 'break-all' }}>{activationUrl}</Typography.Paragraph>
        {activationExpiresAt && <Typography.Text type="secondary">有效期至 {new Date(activationExpiresAt).toLocaleString('zh-CN')}</Typography.Text>}
      </Modal>
    </div>
  );
}
