'use client';

import { Box, Group, Stack, Text } from '@tidbcloud/uikit';
import type { ReactNode } from 'react';
import { MarkdownContent } from './MarkdownContent';
import { IssueInfoMetadata } from './types';
import { useTranslation } from '@/lib/i18n';
import { formatAlertRulePath, shouldShowFullAlertExpr, summarizeAlertExpr } from './alertRuleFormat';

interface IssueInfoSystemMessageProps {
  issueInfo: IssueInfoMetadata;
  isMobile: boolean;
}

const empty = (value: string | undefined, na: string) => {
  const trimmed = (value || '').trim();
  return trimmed || na;
};

function badgeColors(kind: 'status' | 'priority', value: string) {
  const normalized = value.toLowerCase();

  if (kind === 'status') {
    if (/resolved|closed|done|recovered/.test(normalized)) {
      return { color: '#166534', background: '#dcfce7', border: '#bbf7d0' };
    }
    if (/created|open|progress|pending|running/.test(normalized)) {
      return { color: '#1d4ed8', background: '#dbeafe', border: '#bfdbfe' };
    }
    return { color: '#374151', background: '#f3f4f6', border: '#e5e7eb' };
  }

  if (/blocker|critical/.test(normalized)) {
    return { color: '#b91c1c', background: '#fee2e2', border: '#fecaca' };
  }
  if (/major|high/.test(normalized)) {
    return { color: '#c2410c', background: '#ffedd5', border: '#fed7aa' };
  }
  if (/medium/.test(normalized)) {
    return { color: '#854d0e', background: '#fef3c7', border: '#fde68a' };
  }
  return { color: '#374151', background: '#f3f4f6', border: '#e5e7eb' };
}

function BadgeValue({ kind, value, na }: { kind: 'status' | 'priority'; value: string; na: string }) {
  const colors = badgeColors(kind, value);
  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        borderRadius: '8px',
        border: `1px solid ${colors.border}`,
        backgroundColor: colors.background,
        color: colors.color,
        fontSize: '12px',
        fontWeight: 600,
        lineHeight: '20px',
        padding: '0 8px',
        whiteSpace: 'nowrap',
      }}
    >
      {empty(value, na)}
    </span>
  );
}

function Field({
  label,
  value,
  children,
  na,
}: {
  label: string;
  value?: string;
  children?: ReactNode;
  na: string;
}) {
  return (
    <Box style={{ minWidth: 0 }}>
      <Text size="xs" style={{ color: '#6b7280', marginBottom: 2 }}>
        {label}
      </Text>
      <Box
        style={{
          color: '#111827',
          fontSize: '13px',
          lineHeight: 1.35,
          overflowWrap: 'anywhere',
        }}
      >
        {children || empty(value, na)}
      </Box>
    </Box>
  );
}

function Section({
  title,
  children,
}: {
  title: string;
  children: ReactNode;
}) {
  return (
    <Stack gap={6}>
      <Text size="xs" style={{ color: '#4b5563', fontWeight: 700, textTransform: 'uppercase' }}>
        {title}
      </Text>
      {children}
    </Stack>
  );
}

export function IssueInfoSystemMessage({ issueInfo, isMobile }: IssueInfoSystemMessageProps) {
  const { t } = useTranslation();
  const na = t('chat.issueInfo.na');
  const gridColumns = isMobile ? '1fr' : 'repeat(2, minmax(0, 1fr))';
  const rulePath = empty(issueInfo.rule, na);
  const ruleFile = formatAlertRulePath(issueInfo.rule);
  const exprSummary = summarizeAlertExpr(issueInfo.ruleExpr);
  const showFullExpr = shouldShowFullAlertExpr(issueInfo.ruleExpr);

  return (
    <Stack gap="sm">
      <Stack gap={3}>
        <Group gap="xs" align="center" style={{ flexWrap: 'wrap' }}>
          <Text style={{ color: '#111827', fontSize: '15px', fontWeight: 700 }}>
            {issueInfo.issueId}
          </Text>
          <BadgeValue kind="status" value={issueInfo.status} na={na} />
          <BadgeValue kind="priority" value={issueInfo.priority} na={na} />
        </Group>
        <Text style={{ color: '#374151', fontSize: '14px', lineHeight: 1.35, overflowWrap: 'anywhere' }}>
          {empty(issueInfo.summary, na)}
        </Text>
      </Stack>

      <Section title={t('chat.issueInfo.section.issue')}>
        <Box style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, minmax(0, 1fr))', gap: '8px 16px' }}>
          <Field label={t('chat.issueInfo.field.component')} value={issueInfo.component} na={na} />
          <Field label={t('chat.issueInfo.field.alert')} value={issueInfo.alertName} na={na} />
          <Field label={t('chat.issueInfo.field.created')} value={issueInfo.created} na={na} />
        </Box>
      </Section>

      <Section title={t('chat.issueInfo.section.cluster')}>
        <Box style={{ display: 'grid', gridTemplateColumns: gridColumns, gap: '8px 16px' }}>
          <Field label={t('chat.issueInfo.field.name')} na={na}>
            {issueInfo.clinicUrl ? (
              <a
                href={issueInfo.clinicUrl}
                target="_blank"
                rel="noopener noreferrer"
                style={{ color: '#2563eb', textDecoration: 'underline' }}
              >
                {empty(issueInfo.clusterName, na)}
              </a>
            ) : (
              empty(issueInfo.clusterName, na)
            )}
          </Field>
          <Field label={t('chat.issueInfo.field.id')} value={issueInfo.clusterId} na={na} />
          <Field label={t('chat.issueInfo.field.version')} value={issueInfo.version} na={na} />
          <Field label={t('chat.issueInfo.field.type')} value={issueInfo.clusterType} na={na} />
          <Field label={t('chat.issueInfo.field.region')} value={issueInfo.region} na={na} />
          <Field label={t('chat.issueInfo.field.tenantOrg')} value={`${empty(issueInfo.tenantId, na)} / ${empty(issueInfo.orgId, na)}`} na={na} />
        </Box>
      </Section>

      <Section title={t('chat.issueInfo.section.alertRule')}>
        <Box style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'minmax(0, 1.1fr) 88px minmax(0, 1.7fr)', gap: '8px 16px' }}>
          <Field label={t('chat.issueInfo.field.rule')} value={ruleFile} na={na} />
          <Field label={t('chat.issueInfo.field.for')} value={issueInfo.ruleFor} na={na} />
          <Field label={t('chat.issueInfo.field.expr')} value={exprSummary} na={na} />
        </Box>
        {(showFullExpr || rulePath !== ruleFile) && (
          <details>
            <summary
              style={{
                cursor: 'pointer',
                color: '#2563eb',
                fontSize: '12px',
                fontWeight: 600,
                lineHeight: 1.4,
              }}
            >
              {t('chat.issueInfo.fullRule')}
            </summary>
            <Stack gap={6} style={{ marginTop: 6 }}>
              {rulePath !== ruleFile && <Field label={t('chat.issueInfo.field.path')} value={rulePath} na={na} />}
              {showFullExpr && (
                <Field label={t('chat.issueInfo.field.expr')} na={na}>
                  <Box
                    style={{
                      maxHeight: 180,
                      overflow: 'auto',
                      whiteSpace: 'pre-wrap',
                      fontFamily: 'monospace',
                      fontSize: '12px',
                      lineHeight: 1.45,
                      backgroundColor: '#f9fafb',
                      border: '1px solid #e5e7eb',
                      borderRadius: '6px',
                      padding: '8px',
                    }}
                  >
                    {empty(issueInfo.ruleExpr, na)}
                  </Box>
                </Field>
              )}
            </Stack>
          </details>
        )}
      </Section>

      {issueInfo.jiraStatusSummary && (
        <Section title={t('chat.issueInfo.section.jiraStatus')}>
          <Box
            style={{
              borderLeft: '3px solid #93c5fd',
              paddingLeft: 12,
              backgroundColor: '#f8fbff',
            }}
          >
            <MarkdownContent content={issueInfo.jiraStatusSummary} isUser={false} />
          </Box>
        </Section>
      )}
    </Stack>
  );
}
