import { Card, Tabs, Typography } from 'antd';
import type { MarkdownDocument } from './markdown-document';
import { MarkdownPreviewContent } from './MarkdownPreviewContent';
import { WorklogSourcePreview } from './WorklogSourcePreview';

const { Paragraph, Text, Title } = Typography;

const ARTIFACT_SECTION_TITLE_PATTERN =
  /^(##|###)\s+(스크린샷|화면 캡처|산출물|확인 경로|참고 링크|preview|source|소스|실행 커맨드|변경 파일|신규 파일|변경\/신규 파일)/i;
const INLINE_ARTIFACT_PATTERN = /!\[[^\]]*\]\(([^)]+)\)|\[[^\]]+\]\(([^)]+)\)|`([^`]+\.(?:png|jpg|jpeg|gif|webp|svg|md|ts|tsx|js|jsx|css|json|mjs))`|(https?:\/\/\S+)/gi;

export type MarkdownPreviewCardProps = {
  document: MarkdownDocument;
};

type WorklogSections = {
  mainContent: string;
  artifactSections: ArtifactSection[];
};

type ArtifactSection = {
  key: string;
  label: string;
  content: string;
  count: number;
};

type WorklogTabItem = {
  key: string;
  label: string;
  count?: number;
  content: string;
};

function finalizeArtifactSection(section: ArtifactSection) {
  return {
    ...section,
    content: section.content.trim(),
  };
}

function mergeArtifactSections(sections: ArtifactSection[]) {
  const mergedSections: ArtifactSection[] = [];

  for (const section of sections) {
    const normalizedSection = finalizeArtifactSection(section);
    const existingSection = mergedSections.find((item) => item.label === normalizedSection.label);

    if (!existingSection) {
      mergedSections.push({
        ...normalizedSection,
        key: `${mergedSections.length}-${normalizedSection.label.toLowerCase()}`,
      });
      continue;
    }

    const existingBody = existingSection.content.replace(/^#{2,3}\s+.+\n?/u, '').trim();
    const nextBody = normalizedSection.content.replace(/^#{2,3}\s+.+\n?/u, '').trim();
    const mergedBody = [existingBody, nextBody].filter(Boolean).join('\n\n').trim();
    existingSection.content = `## ${existingSection.label}${mergedBody ? `\n\n${mergedBody}` : ''}`;
  }

  mergedSections.forEach((section) => {
    section.count = section.content.match(INLINE_ARTIFACT_PATTERN)?.length ?? 0;
  });

  return mergedSections.filter((section) => section.content);
}

function normalizeArtifactSectionLabel(rawTitle: string) {
  const normalizedTitle = rawTitle.trim().toLowerCase();

  if (normalizedTitle === '화면 캡처' || normalizedTitle === '스크린샷') {
    return '스크린샷';
  }

  if (normalizedTitle === 'source' || normalizedTitle === '소스') {
    return '소스';
  }

  if (normalizedTitle === 'preview') {
    return 'Preview';
  }

  if (normalizedTitle === '실행 커맨드') {
    return '커맨드';
  }

  if (
    normalizedTitle === '변경 파일' ||
    normalizedTitle === '신규 파일' ||
    normalizedTitle === '변경/신규 파일'
  ) {
    return '파일';
  }

  return rawTitle.trim();
}

function splitWorklogContent(content: string): WorklogSections {
  const lines = content.split('\n');
  const mainLines: string[] = [];
  const artifactSections: ArtifactSection[] = [];
  let currentSection: ArtifactSection | null = null;
  let inCodeFence = false;

  for (const line of lines) {
    const trimmedLine = line.trim();
    const isFenceLine = /^```/.test(trimmedLine);

    if (isFenceLine) {
      inCodeFence = !inCodeFence;
      if (currentSection) {
        currentSection.content += `${line}\n`;
      } else {
        mainLines.push(line);
      }
      continue;
    }

    const match = inCodeFence ? null : trimmedLine.match(ARTIFACT_SECTION_TITLE_PATTERN);
    const isHeading = !inCodeFence && /^#{2,3}\s+/.test(trimmedLine);

    if (match) {
      if (currentSection) {
        artifactSections.push(finalizeArtifactSection(currentSection));
      }

      const rawTitle = match[2] ?? '자료';
      currentSection = {
        key: `${artifactSections.length}-${rawTitle.toLowerCase()}`,
        label: normalizeArtifactSectionLabel(rawTitle),
        content: `${line}\n`,
        count: 0,
      };
      continue;
    }

    if (isHeading) {
      if (currentSection) {
        artifactSections.push(finalizeArtifactSection(currentSection));
      }
      currentSection = null;
      mainLines.push(line);
      continue;
    }

    if (currentSection) {
      currentSection.content += `${line}\n`;
    } else {
      mainLines.push(line);
    }
  }

  if (currentSection) {
    artifactSections.push(finalizeArtifactSection(currentSection));
  }

  return {
    mainContent: mainLines.join('\n').trim(),
    artifactSections: mergeArtifactSections(artifactSections),
  };
}

function isRepoPathBullet(line: string) {
  return /^-\s+.*`(?:src|docs|scripts|etc|public|\.github)\/[^`]+`/.test(line);
}

function sanitizeDetailedWorklogSection(content: string) {
  const lines = content.split('\n');
  const sanitizedLines: string[] = [];
  let inDetailedSection = false;
  let inCodeFence = false;

  for (const line of lines) {
    const trimmedLine = line.trim();

    if (!inCodeFence && /^##\s+상세 작업 내역\b/.test(trimmedLine)) {
      inDetailedSection = true;
      sanitizedLines.push(line);
      continue;
    }

    if (!inCodeFence && inDetailedSection && /^##\s+/.test(trimmedLine)) {
      inDetailedSection = false;
    }

    if (/^```/.test(trimmedLine)) {
      if (inDetailedSection) {
        inCodeFence = !inCodeFence;
        continue;
      }

      sanitizedLines.push(line);
      continue;
    }

    if (inDetailedSection) {
      if (isRepoPathBullet(trimmedLine)) {
        continue;
      }
      if (/^(diff --git|@@\s|--- a\/|\+\+\+ b\/)/.test(trimmedLine)) {
        continue;
      }
    }

    sanitizedLines.push(line);
  }

  return sanitizedLines.join('\n').replace(/\n{3,}/g, '\n\n').trim();
}

export function MarkdownPreviewCard({ document }: MarkdownPreviewCardProps) {
  const isWorklog = document.folder === 'worklogs';
  const { mainContent, artifactSections } = splitWorklogContent(document.content);
  const filesSection = artifactSections.find((section) => section.label === '파일');
  const visibleArtifactSections = isWorklog
    ? artifactSections.filter((section) => section.label !== '파일')
    : artifactSections;
  const worklogTabs: WorklogTabItem[] = isWorklog
    ? [
        {
          key: 'worklog-main',
          label: '작업일지',
          content: sanitizeDetailedWorklogSection(mainContent || document.content),
        },
        ...visibleArtifactSections,
      ]
    : [];

  return (
    <Card className="feature-markdown-card">
      <Title level={4}>{document.title}</Title>
      {isWorklog ? (
        <Tabs
          className="feature-markdown-card__tabs"
          items={worklogTabs.map((section) => ({
            key: section.key,
            label: `${section.label}${section.count && section.count > 0 ? ` (${section.count})` : ''}`,
            children:
              section.label === '소스' ? (
                <WorklogSourcePreview
                  sourceSectionContent={section.content}
                  filesSectionContent={filesSection?.content}
                />
              ) : section.content ? (
                <MarkdownPreviewContent content={section.content} documentPath={document.path} />
              ) : (
                <Paragraph type="secondary" className="feature-markdown-card__artifacts-copy">
                  기록된 내용이 없습니다.
                </Paragraph>
              ),
          }))}
        />
      ) : (
        <MarkdownPreviewContent content={document.content} documentPath={document.path} />
      )}
      <Text type="secondary" code>
        {document.path}
      </Text>
    </Card>
  );
}
