import {
  ArrowLeftOutlined,
  CopyOutlined,
  DeleteOutlined,
  EditOutlined,
  EllipsisOutlined,
  InboxOutlined,
  ReloadOutlined,
  SendOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';
import {
  Alert,
  App,
  Button,
  Col,
  Descriptions,
  Dropdown,
  Form,
  Input,
  List,
  Modal,
  Result,
  Row,
  Select,
  Skeleton,
  Space,
  Table,
  Tabs,
  Typography
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { MenuProps } from 'antd';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';

import { EmptyState } from '../../components/common/EmptyState';
import { PageHeader } from '../../components/common/PageHeader';
import { SectionCard } from '../../components/common/SectionCard';
import { StatusPill } from '../../components/common/StatusPill';
import { DnsRecordCard } from '../../components/domain/DnsRecordCard';
import { useAppContext } from '../../frontend/app-context';
import { buildDomainHealth, getVisibleDnsRecords } from '../../frontend/domain-model.js';
import { useI18n } from '../../frontend/i18n/react';
import { api } from '../../frontend/services/api';
import type {
  ApiToken,
  DnsCredential,
  Domain,
  DomainPatchPayload,
  InboundMailbox,
  SendEvent,
  SmtpCredential,
  SmtpRelay
} from '../../frontend/types';

const sections = ['overview', 'dns', 'sending', 'inbound', 'activity'] as const;
type DetailSection = (typeof sections)[number];

interface BaseData {
  domain: Domain | null;
  dnsCredentials: DnsCredential[];
  smtpRelays: SmtpRelay[];
}

export default function DomainDetail() {
  const { id, section } = useParams<{ id: string; section: string }>();
  const domainId = Number(id);
  const activeSection: DetailSection = isSection(section) ? section : 'overview';
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const { config } = useAppContext();
  const { locale } = useI18n();
  const copy = locale.startsWith('en') ? enCopy : zhCopy;
  const { message } = App.useApp();
  const [base, setBase] = useState<BaseData | null>(null);
  const [events, setEvents] = useState<SendEvent[] | null>(null);
  const [smtpCredential, setSmtpCredential] = useState<SmtpCredential | null | undefined>(undefined);
  const [apiTokens, setApiTokens] = useState<ApiToken[] | null>(null);
  const [mailboxes, setMailboxes] = useState<InboundMailbox[] | null>(null);
  const [loading, setLoading] = useState(true);
  const [sectionLoading, setSectionLoading] = useState(false);
  const [error, setError] = useState('');
  const [sectionError, setSectionError] = useState('');
  const [actionLoading, setActionLoading] = useState<Record<string, boolean>>({});
  const [editOpen, setEditOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [deleteConfirmation, setDeleteConfirmation] = useState('');
  const [testOpen, setTestOpen] = useState(false);
  const [editForm] = Form.useForm<DomainPatchPayload>();
  const [testForm] = Form.useForm<{ to: string; subject: string; text: string }>();

  const loadBase = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const [domainsResult, credentialsResult, relaysResult] = await Promise.all([
        api.domains(), api.dnsCredentials(), api.smtpRelays()
      ]);
      setBase({
        domain: domainsResult.domains.find((item) => item.id === domainId) || null,
        dnsCredentials: credentialsResult.credentials,
        smtpRelays: relaysResult.relays
      });
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : copy.loadFailed);
    } finally {
      setLoading(false);
    }
  }, [copy.loadFailed, domainId]);

  useEffect(() => {
    void loadBase();
  }, [loadBase]);

  useEffect(() => {
    if (!section || isSection(section)) return;
    navigate(`/domains/${id}/overview`, { replace: true });
  }, [id, navigate, section]);

  useEffect(() => {
    if (searchParams.get('edit') === '1' && base?.domain) openEdit(base.domain);
    // The query flag is an entry action; the form itself controls subsequent visibility.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [base?.domain?.id, searchParams]);

  const loadSection = useCallback(async () => {
    if (!base?.domain) return;
    if (activeSection === 'overview' || activeSection === 'dns') return;
    if (activeSection === 'activity' && events !== null) return;
    if (activeSection === 'sending' && apiTokens !== null && smtpCredential !== undefined) return;
    if (activeSection === 'inbound' && mailboxes !== null) return;
    setSectionLoading(true);
    setSectionError('');
    try {
      if (activeSection === 'activity') {
        const result = await api.events({ domainId: base.domain.id, page: 1, pageSize: 50 });
        setEvents(result.events);
      } else if (activeSection === 'sending') {
        const [credentialResult, tokensResult] = await Promise.all([api.smtpCredential(), api.apiTokens()]);
        setSmtpCredential(credentialResult.credential);
        setApiTokens(tokensResult.tokens);
      } else if (activeSection === 'inbound') {
        const result = await api.inboundMailboxes();
        setMailboxes(result.mailboxes.filter((mailbox) => mailbox.domainId === base.domain?.id));
      }
    } catch (reason) {
      setSectionError(reason instanceof Error ? reason.message : copy.sectionLoadFailed);
    } finally {
      setSectionLoading(false);
    }
  }, [activeSection, apiTokens, base?.domain, copy.sectionLoadFailed, events, mailboxes, smtpCredential]);

  useEffect(() => {
    void loadSection();
  }, [loadSection]);

  const domain = base?.domain || null;
  const health = useMemo(() => domain ? buildDomainHealth(domain) : null, [domain]);

  function updateDomain(nextDomain: Domain) {
    setBase((current) => current ? { ...current, domain: nextDomain } : current);
  }

  async function runAction<T>(name: string, operation: () => Promise<T>) {
    setActionLoading((current) => ({ ...current, [name]: true }));
    try {
      return await operation();
    } finally {
      setActionLoading((current) => ({ ...current, [name]: false }));
    }
  }

  async function checkDns() {
    if (!domain) return;
    try {
      const result = await runAction('check', () => api.checkDomain(domain.id));
      updateDomain(result.domain);
      message.success(copy.checked);
    } catch (reason) {
      message.error(errorMessage(reason, copy.actionFailed));
    }
  }

  async function applyDns() {
    if (!domain) return;
    try {
      const result = await runAction('apply', () => api.applyDns(domain.id));
      updateDomain(result.domain);
      if (result.apply?.ok === false) message.warning(copy.dnsPartial);
      else message.success(copy.dnsApplied);
    } catch (reason) {
      message.error(errorMessage(reason, copy.actionFailed));
    }
  }

  async function saveDomain() {
    if (!domain) return;
    let values: DomainPatchPayload;
    try {
      values = await editForm.validateFields();
    } catch {
      return;
    }
    try {
      const result = await runAction('edit', () => api.patchDomain(domain.id, {
        ...values,
        dnsCredentialId: values.dnsCredentialId ?? null,
        smtpRelayId: values.smtpRelayId ?? null
      }));
      updateDomain(result.domain);
      closeEdit();
      message.success(copy.saved);
    } catch (reason) {
      message.error(errorMessage(reason, copy.actionFailed));
    }
  }

  async function sendTest() {
    if (!domain) return;
    let values: { to: string; subject: string; text: string };
    try {
      values = await testForm.validateFields();
    } catch {
      return;
    }
    try {
      await runAction('test', () => api.sendTest(domain.id, values));
      setTestOpen(false);
      testForm.resetFields();
      message.success(copy.testQueued);
    } catch (reason) {
      message.error(errorMessage(reason, copy.actionFailed));
    }
  }

  async function deleteDomain() {
    if (!domain || deleteConfirmation !== domain.domain) return;
    try {
      await runAction('delete', () => api.deleteDomain(domain.id));
      message.success(copy.deleted);
      navigate('/domains', { replace: true });
    } catch (reason) {
      message.error(errorMessage(reason, copy.actionFailed));
    }
  }

  function openEdit(target: Domain) {
    editForm.setFieldsValue({
      selector: target.selector,
      dnsCredentialId: target.dnsCredentialId,
      smtpRelayId: target.smtpRelayId,
      senderHost: target.senderHost,
      sendingIp: target.sendingIp,
      spfExtra: target.spfExtra,
      dmarcPolicy: target.dmarcPolicy,
      dmarcRua: target.dmarcRua,
      catchAllAddress: target.catchAllAddress
    });
    setEditOpen(true);
  }

  function closeEdit() {
    setEditOpen(false);
    if (searchParams.has('edit')) {
      const next = new URLSearchParams(searchParams);
      next.delete('edit');
      setSearchParams(next, { replace: true });
    }
  }

  function dismissSetupNotice() {
    if (!searchParams.has('setup')) return;
    const next = new URLSearchParams(searchParams);
    next.delete('setup');
    setSearchParams(next, { replace: true });
  }

  function openTest() {
    if (!domain) return;
    testForm.setFieldsValue({ subject: copy.testSubject(domain.domain), text: copy.testBody(domain.domain) });
    setTestOpen(true);
  }

  async function copyValue(value: string) {
    try {
      await navigator.clipboard.writeText(value);
      message.success(copy.copied);
    } catch {
      message.error(copy.copyFailed);
    }
  }

  if (loading && !base) {
    return <Space direction="vertical" size={20} className="full-width" aria-label={copy.loading}><Skeleton active title={{ width: '36%' }} paragraph={{ rows: 3 }} /><SectionCard><Skeleton active paragraph={{ rows: 10 }} /></SectionCard></Space>;
  }

  if (error && !base) {
    return <Result status="error" title={copy.loadFailed} subTitle={error} extra={<Space><Button onClick={() => navigate('/domains')}>{copy.back}</Button><Button type="primary" onClick={() => void loadBase()}>{copy.retry}</Button></Space>} />;
  }

  if (!Number.isInteger(domainId) || domainId <= 0 || (base && !domain)) {
    return <Result status="404" title={copy.notFound} subTitle={copy.notFoundHint} extra={<Button type="primary" onClick={() => navigate('/domains')}>{copy.backToDomains}</Button>} />;
  }

  if (!domain || !base || !health) return null;

  const menuItems: MenuProps['items'] = [
    { key: 'check', icon: <ReloadOutlined />, label: copy.checkDns, onClick: () => void checkDns() },
    { key: 'apply', icon: <ThunderboltOutlined />, label: copy.autoDns, disabled: !domain.dnsCredentialId, onClick: () => void applyDns() },
    { key: 'edit', icon: <EditOutlined />, label: copy.edit, onClick: () => openEdit(domain) },
    { type: 'divider' },
    { key: 'delete', icon: <DeleteOutlined />, danger: true, label: copy.delete, onClick: () => { setDeleteConfirmation(''); setDeleteOpen(true); } }
  ];

  return (
    <Space direction="vertical" size={20} className="full-width">
      <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/domains')} style={{ width: 'fit-content', minHeight: 44 }}>{copy.backToDomains}</Button>
      <PageHeader
        title={domain.domain}
        subtitle={`${domain.senderHost} · ${domain.sendingIp}`}
        extra={
          <Space>
            <StatusPill tone={health.status === 'success' ? 'success' : health.status === 'warning' ? 'warning' : 'error'}>{health.passed}/{health.total} {health.status === 'success' ? copy.dnsPassed : copy.needsAttention}</StatusPill>
            <Button type="primary" icon={<SendOutlined />} style={{ minHeight: 44 }} onClick={openTest}>{copy.testSend}</Button>
            <Dropdown menu={{ items: menuItems }} trigger={['click']}><Button aria-label={copy.moreActions} icon={<EllipsisOutlined />} style={{ minHeight: 44 }} loading={Object.values(actionLoading).some(Boolean)} /></Dropdown>
          </Space>
        }
      />

      {searchParams.get('setup') === 'partial' ? (
        <Alert
          type="warning"
          showIcon
          closable
          message={copy.setupPartialTitle}
          description={copy.setupPartialDescription}
          onClose={dismissSetupNotice}
        />
      ) : searchParams.get('setup') === 'complete' ? (
        <Alert
          type="success"
          showIcon
          closable
          message={copy.setupCompleteTitle}
          description={domain.dnsCredentialId ? copy.setupAutomaticDescription : copy.setupManualDescription}
          onClose={dismissSetupNotice}
        />
      ) : null}

      <Tabs
        activeKey={activeSection}
        onChange={(key) => navigate(`/domains/${domain.id}/${key}`)}
        className="domain-detail-tabs"
        items={[
          { key: 'overview', label: copy.overview, children: <OverviewTab domain={domain} health={health} dnsName={base.dnsCredentials.find((item) => item.id === domain.dnsCredentialId)?.name} relayName={base.smtpRelays.find((item) => item.id === domain.smtpRelayId)?.name} copy={copy} onCheck={checkDns} onReviewDns={() => navigate(`/domains/${domain.id}/dns`)} onEdit={() => openEdit(domain)} onDelete={() => setDeleteOpen(true)} loading={actionLoading} /> },
          { key: 'dns', label: copy.dnsAndVerification, children: <DnsTab domain={domain} copy={copy} onCopy={copyValue} onCheck={checkDns} onApply={applyDns} loading={actionLoading} /> },
          { key: 'sending', label: copy.sendingConfiguration, children: <SectionContent loading={sectionLoading} error={sectionError} retry={loadSection} copy={copy}><SendingTab domain={domain} config={config} credential={smtpCredential} tokens={apiTokens || []} relayName={base.smtpRelays.find((item) => item.id === domain.smtpRelayId)?.name} copy={copy} onCopy={copyValue} onEdit={() => openEdit(domain)} /></SectionContent> },
          { key: 'inbound', label: copy.inboundConfiguration, children: <SectionContent loading={sectionLoading} error={sectionError} retry={loadSection} copy={copy}><InboundTab domain={domain} config={config} mailboxes={mailboxes || []} copy={copy} onNavigate={() => navigate('/inbox')} onEdit={() => openEdit(domain)} /></SectionContent> },
          { key: 'activity', label: copy.activity, children: <SectionContent loading={sectionLoading} error={sectionError} retry={loadSection} copy={copy}><ActivityTab events={events || []} copy={copy} onView={(event) => navigate(`/activity/${event.id}?domainId=${domain.id}`)} /></SectionContent> }
        ]}
      />

      <EditDomainModal open={editOpen} domain={domain} form={editForm} dnsCredentials={base.dnsCredentials} smtpRelays={base.smtpRelays} copy={copy} loading={Boolean(actionLoading.edit)} onCancel={closeEdit} onSave={saveDomain} />

      <Modal title={copy.deleteTitle} open={deleteOpen} okText={copy.delete} cancelText={copy.cancel} okButtonProps={{ danger: true, disabled: deleteConfirmation !== domain.domain, loading: Boolean(actionLoading.delete) }} onCancel={() => { setDeleteOpen(false); setDeleteConfirmation(''); }} onOk={() => void deleteDomain()}>
        <Space direction="vertical" size={16} className="full-width"><Alert type="error" showIcon message={copy.deleteWarning} /><Typography.Text>{copy.typeDomain} <Typography.Text code>{domain.domain}</Typography.Text></Typography.Text><Input value={deleteConfirmation} onChange={(event) => setDeleteConfirmation(event.target.value)} aria-label={copy.deleteConfirmation} style={{ minHeight: 44 }} /></Space>
      </Modal>

      <Modal title={copy.testSend} open={testOpen} okText={copy.queueTest} cancelText={copy.cancel} confirmLoading={Boolean(actionLoading.test)} onCancel={() => setTestOpen(false)} onOk={() => void sendTest()}>
        <Form form={testForm} layout="vertical"><Form.Item name="to" label={copy.recipient} rules={[{ required: true, type: 'email', message: copy.validRecipient }]}><Input placeholder="you@example.com" style={{ minHeight: 44 }} /></Form.Item><Form.Item name="subject" label={copy.subject} rules={[{ required: true }]}><Input style={{ minHeight: 44 }} /></Form.Item><Form.Item name="text" label={copy.body} rules={[{ required: true }]}><Input.TextArea rows={5} /></Form.Item></Form>
      </Modal>
    </Space>
  );
}

function OverviewTab({ domain, health, dnsName, relayName, copy, onCheck, onReviewDns, onEdit, onDelete, loading }: { domain: Domain; health: ReturnType<typeof buildDomainHealth>; dnsName?: string; relayName?: string; copy: typeof zhCopy; onCheck: () => void; onReviewDns: () => void; onEdit: () => void; onDelete: () => void; loading: Record<string, boolean> }) {
  return (
    <Space direction="vertical" size={20} className="full-width">
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={15}><SectionCard title={copy.domainSummary}><Descriptions column={1}><Descriptions.Item label={copy.domain}>{domain.domain}</Descriptions.Item><Descriptions.Item label={copy.senderHost}>{domain.senderHost}</Descriptions.Item><Descriptions.Item label={copy.sendingIp}>{domain.sendingIp}</Descriptions.Item><Descriptions.Item label="DKIM selector">{domain.selector}</Descriptions.Item><Descriptions.Item label={copy.dnsIntegration}>{dnsName || copy.manualDns}</Descriptions.Item><Descriptions.Item label={copy.relay}>{relayName || copy.defaultDelivery}</Descriptions.Item><Descriptions.Item label={copy.createdAt}>{new Date(domain.createdAt).toLocaleString()}</Descriptions.Item></Descriptions></SectionCard></Col>
        <Col xs={24} lg={9}><SectionCard title={copy.authenticationHealth}><Space direction="vertical" size={16} className="full-width"><Typography.Title level={2} style={{ margin: 0 }}>{health.passed}/{health.total}</Typography.Title><Typography.Text type="secondary">{copy.recordsPassed}</Typography.Text><StatusPill tone={health.status === 'success' ? 'success' : health.status === 'warning' ? 'warning' : 'error'}>{health.status === 'success' ? copy.ready : copy.needsAttention}</StatusPill><Button icon={<ReloadOutlined />} loading={loading.check} onClick={onCheck}>{copy.checkDns}</Button></Space></SectionCard></Col>
      </Row>
      <Row gutter={[16, 16]}><Col xs={24} lg={12}><SectionCard title={copy.nextActions}><Space wrap><Button icon={<ThunderboltOutlined />} onClick={onReviewDns}>{copy.reviewDns}</Button><Button icon={<EditOutlined />} onClick={onEdit}>{copy.edit}</Button></Space></SectionCard></Col><Col xs={24} lg={12}><SectionCard title={copy.dangerZone} className="domain-danger-card"><Space direction="vertical" className="full-width"><Typography.Text type="secondary">{copy.dangerHint}</Typography.Text><Button danger icon={<DeleteOutlined />} onClick={onDelete}>{copy.delete}</Button></Space></SectionCard></Col></Row>
    </Space>
  );
}

function DnsTab({ domain, copy, onCopy, onCheck, onApply, loading }: { domain: Domain; copy: typeof zhCopy; onCopy: (value: string) => void; onCheck: () => void; onApply: () => void; loading: Record<string, boolean> }) {
  const records = getVisibleDnsRecords(domain.status?.records || []);
  const copyAll = records.map((record) => `${record.host}\t${record.type}\t${record.value || ''}`).join('\n');
  return (
    <Space direction="vertical" size={16} className="full-width">
      <SectionCard title={copy.dnsAndVerification} extra={<Space wrap><Button icon={<ReloadOutlined />} loading={loading.check} onClick={onCheck}>{copy.recheck}</Button><Button icon={<ThunderboltOutlined />} disabled={!domain.dnsCredentialId} loading={loading.apply} onClick={onApply}>{copy.autoDns}</Button><Button icon={<CopyOutlined />} disabled={!copyAll} onClick={() => onCopy(copyAll)}>{copy.copyAll}</Button></Space>}>
        <Alert type={domain.status?.verified ? 'success' : 'warning'} showIcon message={domain.status?.verified ? copy.domainVerified : copy.domainNotVerified} description={`${copy.lastChecked}: ${domain.status?.checkedAt ? new Date(domain.status.checkedAt).toLocaleString() : copy.never}`} />
      </SectionCard>
      <DnsApplyResults apply={domain.status?.apply} copy={copy} />
      {records.length ? records.map((record) => <DnsRecordCard key={record.key} record={record} loading={loading.check} onCopy={onCopy} onRecheck={onCheck} />) : <SectionCard><EmptyState description={copy.noDnsRecords} action={<Button onClick={onCheck}>{copy.checkNow}</Button>} /></SectionCard>}
      {domain.status?.warnings?.length ? <Alert type="warning" showIcon message={copy.warnings} description={domain.status.warnings.join('\n')} /> : null}
    </Space>
  );
}

function DnsApplyResults({ apply, copy }: { apply?: Domain['status']['apply']; copy: typeof zhCopy }) {
  if (!apply?.results?.length) return null;
  return (
    <SectionCard
      title={copy.applyResults}
      extra={<StatusPill tone={apply.ok ? 'success' : 'warning'}>{apply.ok ? copy.applyComplete : copy.applyPartial}</StatusPill>}
    >
      <List
        dataSource={apply.results}
        renderItem={(result) => {
          const tone = result.skipped ? 'warning' : (result.ok ? 'success' : 'error');
          const label = result.skipped ? copy.applySkipped : (result.ok ? copy.applySucceeded : copy.applyFailed);
          const description = result.ok
            ? (result.detail || copy.applySucceededHint)
            : (result.error || copy.applyFailedHint);
          return (
            <List.Item>
              <List.Item.Meta
                title={<Space wrap><StatusPill tone={tone}>{label}</StatusPill><Typography.Text code>{result.type}</Typography.Text><Typography.Text>{result.host}</Typography.Text></Space>}
                description={<Typography.Text type={result.ok ? 'secondary' : 'danger'}>{description}</Typography.Text>}
              />
            </List.Item>
          );
        }}
      />
    </SectionCard>
  );
}

function SendingTab({ domain, config, credential, tokens, relayName, copy, onCopy, onEdit }: { domain: Domain; config: ReturnType<typeof useAppContext>['config']; credential: SmtpCredential | null | undefined; tokens: ApiToken[]; relayName?: string; copy: typeof zhCopy; onCopy: (value: string) => void; onEdit: () => void }) {
  const endpoint = `${config?.appBaseUrl || window.location.origin}/api/send`;
  return (
    <Row gutter={[16, 16]}>
      <Col xs={24} xl={12}><SectionCard title="SMTP" extra={<Button icon={<EditOutlined />} onClick={onEdit}>{copy.edit}</Button>}><Descriptions column={1}><Descriptions.Item label={copy.host}>{copyable(config?.submission?.host || '-', onCopy)}</Descriptions.Item><Descriptions.Item label={copy.ports}>{config?.submission?.ports?.map((item) => `${item.port}/${item.protocol}`).join(', ') || '-'}</Descriptions.Item><Descriptions.Item label={copy.username}>{credential?.username || config?.submission?.username || '-'}</Descriptions.Item><Descriptions.Item label={copy.password}><StatusPill tone={credential?.passwordSet ? 'success' : 'warning'}>{credential?.passwordSet ? copy.configured : copy.notConfigured}</StatusPill></Descriptions.Item><Descriptions.Item label={copy.relay}>{relayName || copy.defaultDelivery}</Descriptions.Item></Descriptions></SectionCard></Col>
      <Col xs={24} xl={12}><SectionCard title="API" extra={<Button href="/integrations/api-keys">{copy.manageKeys}</Button>}><Descriptions column={1}><Descriptions.Item label="Endpoint">{copyable(endpoint, onCopy)}</Descriptions.Item><Descriptions.Item label={copy.availableKeys}>{tokens.filter((token) => !token.revokedAt).length}</Descriptions.Item></Descriptions>{tokens.length ? <List size="small" dataSource={tokens.slice(0, 4)} renderItem={(token) => <List.Item><List.Item.Meta title={token.name} description={<Typography.Text code>{token.tokenPrefix}••••</Typography.Text>} /></List.Item>} /> : <EmptyState description={copy.noKeys} />}</SectionCard></Col>
      <Col span={24}><SectionCard title={copy.senderIdentity}><Descriptions column={1}><Descriptions.Item label={copy.fromDomain}>{domain.domain}</Descriptions.Item><Descriptions.Item label={copy.senderHost}>{domain.senderHost}</Descriptions.Item><Descriptions.Item label={copy.verification}><StatusPill tone={domain.status?.verified ? 'success' : 'warning'}>{domain.status?.verified ? copy.verified : copy.pending}</StatusPill></Descriptions.Item></Descriptions></SectionCard></Col>
    </Row>
  );
}

function InboundTab({ domain, config, mailboxes, copy, onNavigate, onEdit }: { domain: Domain; config: ReturnType<typeof useAppContext>['config']; mailboxes: InboundMailbox[]; copy: typeof zhCopy; onNavigate: () => void; onEdit: () => void }) {
  return (
    <Row gutter={[16, 16]}>
      <Col xs={24} xl={9}><SectionCard title={copy.inboundStatus}><Space direction="vertical" size={16} className="full-width"><StatusPill tone={config?.submission?.inboundEnabled ? 'success' : 'warning'}><InboxOutlined /> {config?.submission?.inboundEnabled ? copy.inboundEnabled : copy.inboundDisabled}</StatusPill><Typography.Text type="secondary">{copy.inboundHint}</Typography.Text><Button onClick={onNavigate}>{copy.openMailboxRouting}</Button></Space></SectionCard></Col>
      <Col xs={24} xl={15}><SectionCard title={copy.mailboxes} extra={<Typography.Text type="secondary">{mailboxes.length}</Typography.Text>}>{mailboxes.length ? <List dataSource={mailboxes} renderItem={(mailbox) => <List.Item><List.Item.Meta title={mailbox.address} description={`${mailbox.unreadCount} ${copy.unread} · ${mailbox.messageCount} ${copy.messages}`} /><StatusPill tone={mailbox.status === 'active' ? 'success' : 'warning'}>{mailbox.status}</StatusPill></List.Item>} /> : <EmptyState description={copy.noMailboxes} action={<Button onClick={onNavigate}>{copy.configureMailbox}</Button>} />}</SectionCard></Col>
      <Col span={24}><SectionCard title={copy.catchAll} extra={<Button icon={<EditOutlined />} onClick={onEdit}>{copy.edit}</Button>}><Descriptions column={1}><Descriptions.Item label={copy.catchAllAddress}>{domain.catchAllAddress || copy.notConfigured}</Descriptions.Item><Descriptions.Item label="IMAP">{config?.mailAccess?.imap.enabled ? config.mailAccess.imap.ports.map((item) => item.port).join(', ') : copy.disabled}</Descriptions.Item><Descriptions.Item label="POP3">{config?.mailAccess?.pop3.enabled ? config.mailAccess.pop3.ports.map((item) => item.port).join(', ') : copy.disabled}</Descriptions.Item></Descriptions></SectionCard></Col>
    </Row>
  );
}

function ActivityTab({ events, copy, onView }: { events: SendEvent[]; copy: typeof zhCopy; onView: (event: SendEvent) => void }) {
  const columns: ColumnsType<SendEvent> = [
    { title: copy.time, dataIndex: 'createdAt', width: 190, render: (value) => new Date(value).toLocaleString() },
    { title: copy.recipient, dataIndex: 'recipients', ellipsis: true, render: (value: string[]) => value.join(', ') },
    { title: copy.subject, dataIndex: 'subject', ellipsis: true },
    { title: copy.status, dataIndex: 'status', width: 130, render: (value) => <StatusPill tone={eventTone(value)}>{eventStatus(value, copy)}</StatusPill> }
  ];
  return events.length ? <SectionCard><Table rowKey="id" columns={columns} dataSource={events} pagination={{ pageSize: 20 }} scroll={{ x: 760 }} onRow={(event) => ({ onClick: () => onView(event), style: { cursor: 'pointer' }, 'aria-label': `${copy.viewActivity} ${event.id}` })} /></SectionCard> : <SectionCard><EmptyState description={copy.noActivity} /></SectionCard>;
}

function SectionContent({ loading, error, retry, copy, children }: { loading: boolean; error: string; retry: () => void; copy: typeof zhCopy; children: React.ReactNode }) {
  if (loading) return <SectionCard><Skeleton active paragraph={{ rows: 7 }} /></SectionCard>;
  if (error) return <Result status="error" title={copy.sectionLoadFailed} subTitle={error} extra={<Button type="primary" onClick={retry}>{copy.retry}</Button>} />;
  return <>{children}</>;
}

function EditDomainModal({ open, domain, form, dnsCredentials, smtpRelays, copy, loading, onCancel, onSave }: { open: boolean; domain: Domain; form: ReturnType<typeof Form.useForm<DomainPatchPayload>>[0]; dnsCredentials: DnsCredential[]; smtpRelays: SmtpRelay[]; copy: typeof zhCopy; loading: boolean; onCancel: () => void; onSave: () => void }) {
  return (
    <Modal title={copy.editTitle} open={open} width={640} confirmLoading={loading} okText={copy.save} cancelText={copy.cancel} onCancel={onCancel} onOk={onSave}>
      <Form form={form} layout="vertical"><Row gutter={16}><Col xs={24} md={12}><Form.Item name="dnsCredentialId" label={copy.dnsIntegration}><Select allowClear options={dnsCredentials.map((item) => ({ value: item.id, label: item.name }))} /></Form.Item></Col><Col xs={24} md={12}><Form.Item name="smtpRelayId" label={copy.relay}><Select allowClear options={smtpRelays.map((item) => ({ value: item.id, label: item.name }))} /></Form.Item></Col></Row><Row gutter={16}><Col xs={24} md={12}><Form.Item name="senderHost" label={copy.senderHost} rules={[{ required: true }]}><Input /></Form.Item></Col><Col xs={24} md={12}><Form.Item name="sendingIp" label={copy.sendingIp} rules={[{ required: true }]}><Input /></Form.Item></Col></Row><Row gutter={16}><Col xs={24} md={12}><Form.Item name="selector" label="DKIM selector" rules={[{ required: true }]}><Input /></Form.Item></Col><Col xs={24} md={12}><Form.Item name="dmarcPolicy" label="DMARC"><Select options={['none', 'quarantine', 'reject'].map((value) => ({ value, label: value }))} /></Form.Item></Col></Row><Form.Item name="spfExtra" label="SPF"><Input.TextArea rows={2} /></Form.Item><Form.Item name="dmarcRua" label="DMARC rua"><Input /></Form.Item><Form.Item name="catchAllAddress" label={copy.catchAllAddress}><Input placeholder={`inbox@${domain.domain}`} /></Form.Item></Form>
    </Modal>
  );
}

function copyable(value: string, onCopy: (value: string) => void) {
  return <Space><Typography.Text code>{value}</Typography.Text><Button type="text" size="small" aria-label="Copy" icon={<CopyOutlined />} onClick={() => onCopy(value)} /></Space>;
}

function isSection(value?: string): value is DetailSection {
  return sections.includes(value as DetailSection);
}

function eventTone(status: string): 'success' | 'warning' | 'error' | 'info' | 'neutral' {
  if (status === 'sent' || status === 'delivered') return 'success';
  if (status === 'queued') return 'info';
  if (status === 'deferred' || status === 'pending') return 'warning';
  if (status === 'failed' || status === 'bounced') return 'error';
  return 'neutral';
}

function eventStatus(status: string, copy: typeof zhCopy) {
  return ({ sent: copy.sent, delivered: copy.delivered, queued: copy.queued, deferred: copy.deferred, pending: copy.pending, failed: copy.failed, bounced: copy.bounced } as Record<string, string>)[status] || status;
}

function errorMessage(reason: unknown, fallback: string) {
  return reason instanceof Error ? reason.message : fallback;
}

const zhCopy = {
  loading: '正在加载域名详情', loadFailed: '域名详情加载失败', sectionLoadFailed: '当前页签加载失败', retry: '重试', back: '返回', backToDomains: '返回域名列表', notFound: '未找到该域名', notFoundHint: '域名不存在、已被删除，或当前账户没有访问权限。',
  moreActions: '更多操作', overview: '概览', dnsAndVerification: 'DNS 与验证', sendingConfiguration: '发送配置', inboundConfiguration: '收信配置', activity: '活动', domain: '域名', senderHost: '发信主机', sendingIp: '发信 IP', dnsIntegration: 'DNS 集成', relay: '发送中继', manualDns: '手动配置', defaultDelivery: '系统默认投递', createdAt: '创建时间',
  dnsPassed: 'DNS 已通过', needsAttention: '需要处理', testSend: '测试发送', checkDns: '检查 DNS', autoDns: '自动写入 DNS', edit: '编辑配置', delete: '删除域名', checked: 'DNS 检查已完成', dnsApplied: 'DNS 记录写入完成', dnsPartial: '部分 DNS 记录写入失败', saved: '配置已保存', testQueued: '测试邮件已加入队列', deleted: '域名已删除', actionFailed: '操作失败', copied: '已复制', copyFailed: '复制失败', setupPartialTitle: '域名已创建，但 DNS 后续操作需要处理', setupPartialDescription: '自动写入或即时检查未完全成功。请查看下方逐条结果，修正后重新执行。', setupCompleteTitle: '域名创建完成', setupAutomaticDescription: 'DNS 自动写入流程已执行，请核对逐条结果和当前验证状态。', setupManualDescription: '请按下方记录完成手动 DNS 配置，并在记录生效后重新检查。',
  domainSummary: '域名摘要', authenticationHealth: '认证健康度', recordsPassed: '项必需记录已通过', ready: '发送就绪', nextActions: '下一步操作', reviewDns: '查看 DNS 记录', dangerZone: '危险操作', dangerHint: '删除域名会停止相关发信配置，且不可撤销。', recheck: '重新检查', copyAll: '复制全部', domainVerified: '域名已验证，可用于发送', domainNotVerified: '域名尚未完成验证', lastChecked: '最近检查', never: '从未检查', noDnsRecords: '尚未生成 DNS 检查结果', checkNow: '立即检查', warnings: '需要注意', applyResults: 'DNS 写入结果', applyComplete: '全部完成', applyPartial: '部分失败', applySucceeded: '成功', applyFailed: '失败', applySkipped: '已跳过', applySucceededHint: '记录已写入或无需变更。', applyFailedHint: '未返回具体错误，请重新执行或改为手动配置。',
  host: '主机', ports: '端口', username: '用户名', password: '密码', configured: '已设置（不会返回明文）', notConfigured: '未设置', manageKeys: '管理 API 密钥', availableKeys: '可用密钥', noKeys: '尚无可用 API 密钥', senderIdentity: '发件身份', fromDomain: '发件域名', verification: '验证状态', verified: '已验证', pending: '等待验证',
  inboundStatus: '收信服务状态', inboundEnabled: '收信服务已启用', inboundDisabled: '收信服务未启用', inboundHint: '邮箱、别名和路由在独立收件箱工作区管理。', openMailboxRouting: '打开邮箱与路由', mailboxes: '邮箱', unread: '封未读', messages: '封邮件', noMailboxes: '该域名还没有邮箱', configureMailbox: '配置邮箱', catchAll: '默认收信路由', catchAllAddress: 'Catch-all 地址', disabled: '未启用',
  time: '时间', recipient: '收件人', subject: '主题', body: '正文', status: '状态', noActivity: '该域名尚无发送活动', viewActivity: '查看发送活动', sent: '已发送', delivered: '已送达', queued: '已入队', deferred: '已延迟', failed: '失败', bounced: '退信',
  editTitle: '编辑域名配置', save: '保存', cancel: '取消', deleteTitle: '删除域名', deleteWarning: '此操作不可撤销，域名相关发送配置将立即不可用。', typeDomain: '请输入域名以确认：', deleteConfirmation: '域名删除确认', queueTest: '加入发送队列', validRecipient: '请输入有效的收件邮箱', testSubject: (domain: string) => `MailHub ${domain} 测试邮件`, testBody: (domain: string) => `这是一封来自 ${domain} 的 MailHub 投递测试邮件。`
};

const enCopy: typeof zhCopy = {
  loading: 'Loading domain details', loadFailed: 'Unable to load domain details', sectionLoadFailed: 'Unable to load this section', retry: 'Retry', back: 'Back', backToDomains: 'Back to domains', notFound: 'Domain not found', notFoundHint: 'The domain does not exist, was deleted, or is not available to this account.',
  moreActions: 'More actions', overview: 'Overview', dnsAndVerification: 'DNS & verification', sendingConfiguration: 'Sending', inboundConfiguration: 'Receiving', activity: 'Activity', domain: 'Domain', senderHost: 'Sending host', sendingIp: 'Sending IP', dnsIntegration: 'DNS integration', relay: 'Sending relay', manualDns: 'Manual', defaultDelivery: 'System delivery', createdAt: 'Created',
  dnsPassed: 'DNS passed', needsAttention: 'Needs attention', testSend: 'Send test', checkDns: 'Check DNS', autoDns: 'Apply DNS', edit: 'Edit configuration', delete: 'Delete domain', checked: 'DNS check completed', dnsApplied: 'DNS records applied', dnsPartial: 'Some DNS records could not be applied', saved: 'Configuration saved', testQueued: 'Test email queued', deleted: 'Domain deleted', actionFailed: 'Action failed', copied: 'Copied', copyFailed: 'Unable to copy', setupPartialTitle: 'Domain created, but DNS follow-up needs attention', setupPartialDescription: 'Automatic application or the immediate check did not fully complete. Review each result below, correct it, and retry.', setupCompleteTitle: 'Domain created', setupAutomaticDescription: 'The automatic DNS flow ran. Review each result and the current verification status.', setupManualDescription: 'Add the records below at your DNS provider, then recheck after they propagate.',
  domainSummary: 'Domain summary', authenticationHealth: 'Authentication health', recordsPassed: 'required records passed', ready: 'Ready to send', nextActions: 'Next actions', reviewDns: 'Review DNS records', dangerZone: 'Danger zone', dangerHint: 'Deleting the domain stops its sending configuration and cannot be undone.', recheck: 'Recheck', copyAll: 'Copy all', domainVerified: 'Domain verified and ready to send', domainNotVerified: 'Domain verification is incomplete', lastChecked: 'Last checked', never: 'Never', noDnsRecords: 'No DNS check results yet', checkNow: 'Check now', warnings: 'Attention needed', applyResults: 'DNS apply results', applyComplete: 'Complete', applyPartial: 'Partially failed', applySucceeded: 'Succeeded', applyFailed: 'Failed', applySkipped: 'Skipped', applySucceededHint: 'The record was written or already matched.', applyFailedHint: 'No detailed error was returned. Retry or configure this record manually.',
  host: 'Host', ports: 'Ports', username: 'Username', password: 'Password', configured: 'Set (never returned in plaintext)', notConfigured: 'Not set', manageKeys: 'Manage API keys', availableKeys: 'Available keys', noKeys: 'No API keys available', senderIdentity: 'Sender identity', fromDomain: 'From domain', verification: 'Verification', verified: 'Verified', pending: 'Pending',
  inboundStatus: 'Inbound service', inboundEnabled: 'Inbound service enabled', inboundDisabled: 'Inbound service disabled', inboundHint: 'Manage mailboxes, aliases, and routes in the dedicated Inbox workspace.', openMailboxRouting: 'Open mailboxes & routing', mailboxes: 'Mailboxes', unread: 'unread', messages: 'messages', noMailboxes: 'No mailboxes for this domain', configureMailbox: 'Configure mailbox', catchAll: 'Default inbound route', catchAllAddress: 'Catch-all address', disabled: 'Disabled',
  time: 'Time', recipient: 'Recipient', subject: 'Subject', body: 'Body', status: 'Status', noActivity: 'No sending activity for this domain', viewActivity: 'View sending activity', sent: 'Sent', delivered: 'Delivered', queued: 'Queued', deferred: 'Deferred', failed: 'Failed', bounced: 'Bounced',
  editTitle: 'Edit domain configuration', save: 'Save', cancel: 'Cancel', deleteTitle: 'Delete domain', deleteWarning: 'This cannot be undone. Sending configuration will stop immediately.', typeDomain: 'Type the domain to confirm:', deleteConfirmation: 'Domain deletion confirmation', queueTest: 'Queue test', validRecipient: 'Enter a valid recipient email', testSubject: (domain: string) => `MailHub ${domain} test email`, testBody: (domain: string) => `This is a MailHub delivery test from ${domain}.`
};
