import React from 'react';
import { X } from 'lucide-react';
import listPrdMarkdown from '../.spec/requirements-prd-list.md?raw';
import detailPrdMarkdown from '../.spec/requirements-prd-detail.md?raw';

export type RequirementsPrdVariant = 'list' | 'detail';

interface RequirementsModalProps {
  open: boolean;
  variant: RequirementsPrdVariant;
  onClose: () => void;
}

const PRD_BY_VARIANT: Record<RequirementsPrdVariant, string> = {
  list: listPrdMarkdown,
  detail: detailPrdMarkdown,
};

function renderInline(text: string): React.ReactNode {
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return parts.map((part, index) => {
    if (part.startsWith('**') && part.endsWith('**')) {
      return <strong key={index}>{part.slice(2, -2)}</strong>;
    }
    return part;
  });
}

function renderMarkdown(markdown: string): React.ReactNode[] {
  const lines = markdown.replace(/\r\n/g, '\n').split('\n');
  const nodes: React.ReactNode[] = [];
  let listItems: string[] = [];
  let tableRows: string[][] = [];
  let inTable = false;
  let key = 0;

  const flushList = () => {
    if (listItems.length === 0) return;
    nodes.push(
      <ul key={`ul-${key += 1}`} className="vm-prd-list">
        {listItems.map((item) => (
          <li key={item}>{renderInline(item)}</li>
        ))}
      </ul>,
    );
    listItems = [];
  };

  const flushTable = () => {
    if (tableRows.length < 2) {
      tableRows = [];
      inTable = false;
      return;
    }
    const [header, , ...body] = tableRows;
    nodes.push(
      <div key={`table-${key += 1}`} className="vm-prd-table-wrap">
        <table className="vm-prd-table">
          <thead>
            <tr>{header.map((cell) => <th key={cell}>{renderInline(cell.trim())}</th>)}</tr>
          </thead>
          <tbody>
            {body.map((row) => (
              <tr key={row.join('|')}>
                {row.map((cell) => <td key={cell}>{renderInline(cell.trim())}</td>)}
              </tr>
            ))}
          </tbody>
        </table>
      </div>,
    );
    tableRows = [];
    inTable = false;
  };

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

    if (trimmed.startsWith('|')) {
      flushList();
      inTable = true;
      tableRows.push(
        trimmed
          .slice(1, trimmed.endsWith('|') ? -1 : undefined)
          .split('|')
          .map((cell) => cell.trim()),
      );
      continue;
    }
    if (inTable) flushTable();

    if (!trimmed) {
      flushList();
      continue;
    }

    if (trimmed === '---') {
      flushList();
      nodes.push(<hr key={`hr-${key += 1}`} className="vm-prd-hr" />);
      continue;
    }

    if (trimmed.startsWith('# ')) {
      flushList();
      nodes.push(<h1 key={`h1-${key += 1}`} className="vm-prd-h1">{trimmed.slice(2)}</h1>);
      continue;
    }
    if (trimmed.startsWith('## ')) {
      flushList();
      nodes.push(<h2 key={`h2-${key += 1}`} className="vm-prd-h2">{trimmed.slice(3)}</h2>);
      continue;
    }
    if (trimmed.startsWith('### ')) {
      flushList();
      nodes.push(<h3 key={`h3-${key += 1}`} className="vm-prd-h3">{trimmed.slice(4)}</h3>);
      continue;
    }

    if (trimmed.startsWith('> ')) {
      flushList();
      nodes.push(
        <blockquote key={`quote-${key += 1}`} className="vm-prd-quote">
          {renderInline(trimmed.slice(2))}
        </blockquote>,
      );
      continue;
    }

    if (trimmed.startsWith('- ')) {
      listItems.push(trimmed.slice(2));
      continue;
    }

    flushList();
    nodes.push(<p key={`p-${key += 1}`} className="vm-prd-p">{renderInline(trimmed)}</p>);
  }

  flushList();
  flushTable();
  return nodes;
}

export function RequirementsModal({ open, variant, onClose }: RequirementsModalProps) {
  if (!open) return null;

  const prdMarkdown = PRD_BY_VARIANT[variant];

  return (
    <div className="vm-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="vm-modal vm-modal-prd"
        role="dialog"
        aria-modal="true"
        aria-label="需求说明"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="vm-modal-header vm-prd-header vm-prd-header--compact">
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭">
            <X size={18} aria-hidden />
          </button>
        </header>
        <article className="vm-prd-body">{renderMarkdown(prdMarkdown)}</article>
        <footer className="vm-modal-footer">
          <button type="button" className="vm-btn vm-btn-primary" onClick={onClose}>关闭</button>
        </footer>
      </div>
    </div>
  );
}
