import { getServerSession } from "next-auth"
import { authOptions } from "@/lib/auth"
import { NextRequest, NextResponse } from 'next/server'
import {
  Document,
  Packer,
  Paragraph,
  TextRun,
  AlignmentType,
  BorderStyle,
  HeadingLevel,
  Footer,
  PageNumber,
  TabStopPosition,
  TabStopType,
} from 'docx'

// ─── Markdown → docx Paragraphs ─────────────────────────────────

function parseMarkdownToParagraphs(markdown: string): Paragraph[] {
  const lines = markdown.split('\n')
  const paragraphs: Paragraph[] = []

  let inList = false

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i]

    // Skip empty lines
    if (!line.trim()) {
      continue
    }

    // Headings
    const h1Match = line.match(/^#\s+(.+)/)
    const h2Match = line.match(/^##\s+(.+)/)
    const h3Match = line.match(/^###\s+(.+)/)
    const h4Match = line.match(/^####\s+(.+)/)

    if (h1Match) {
      paragraphs.push(new Paragraph({
        heading: HeadingLevel.HEADING_1,
        spacing: { before: 360, after: 200 },
        children: parseInlineFormatting(h1Match[1], { bold: true, size: 32, font: 'Times New Roman' }),
      }))
      continue
    }
    if (h2Match) {
      paragraphs.push(new Paragraph({
        heading: HeadingLevel.HEADING_2,
        spacing: { before: 300, after: 160 },
        children: parseInlineFormatting(h2Match[1], { bold: true, size: 28, font: 'Times New Roman' }),
      }))
      continue
    }
    if (h3Match) {
      paragraphs.push(new Paragraph({
        heading: HeadingLevel.HEADING_3,
        spacing: { before: 240, after: 120 },
        children: parseInlineFormatting(h3Match[1], { bold: true, size: 26, font: 'Times New Roman' }),
      }))
      continue
    }
    if (h4Match) {
      paragraphs.push(new Paragraph({
        spacing: { before: 200, after: 100 },
        children: parseInlineFormatting(h4Match[1], { bold: true, size: 24, font: 'Times New Roman' }),
      }))
      continue
    }

    // Horizontal rule
    if (/^[-*_]{3,}\s*$/.test(line.trim())) {
      paragraphs.push(new Paragraph({
        border: { bottom: { style: BorderStyle.SINGLE, size: 1, color: '999999' } },
        spacing: { before: 200, after: 200 },
      }))
      continue
    }

    // Bullet list
    const bulletMatch = line.match(/^[\s]*[-*+]\s+(.+)/)
    if (bulletMatch) {
      paragraphs.push(new Paragraph({
        bullet: { level: 0 },
        spacing: { before: 60, after: 60 },
        children: parseInlineFormatting(bulletMatch[1], { size: 24, font: 'Times New Roman' }),
      }))
      continue
    }

    // Numbered list
    const numMatch = line.match(/^[\s]*\d+[.)]\s+(.+)/)
    if (numMatch) {
      paragraphs.push(new Paragraph({
        bullet: { level: 0 },
        spacing: { before: 60, after: 60 },
        children: parseInlineFormatting(numMatch[1], { size: 24, font: 'Times New Roman' }),
      }))
      continue
    }

    // Blockquote
    const quoteMatch = line.match(/^>\s*(.+)/)
    if (quoteMatch) {
      paragraphs.push(new Paragraph({
        indent: { left: 720 },
        spacing: { before: 120, after: 120 },
        border: { left: { style: BorderStyle.SINGLE, size: 3, color: '0D9488' } },
        children: parseInlineFormatting(quoteMatch[1], { italics: true, size: 24, font: 'Times New Roman', color: '555555' }),
      }))
      continue
    }

    // Regular paragraph
    paragraphs.push(new Paragraph({
      spacing: { before: 120, after: 120, line: 360 },
      alignment: AlignmentType.JUSTIFIED,
      children: parseInlineFormatting(line, { size: 24, font: 'Times New Roman' }),
    }))
  }

  return paragraphs
}

interface InlineDefaults {
  bold?: boolean
  italics?: boolean
  size?: number
  font?: string
  color?: string
}

function parseInlineFormatting(text: string, defaults: InlineDefaults): TextRun[] {
  const runs: TextRun[] = []
  // Match bold+italic, bold, italic, or plain text
  const regex = /(\*\*\*(.+?)\*\*\*|\*\*(.+?)\*\*|\*(.+?)\*|([^*]+))/g
  let match

  while ((match = regex.exec(text)) !== null) {
    if (match[2]) {
      // Bold + Italic
      runs.push(new TextRun({
        text: match[2],
        bold: true,
        italics: true,
        size: defaults.size || 24,
        font: defaults.font || 'Times New Roman',
        color: defaults.color,
      }))
    } else if (match[3]) {
      // Bold
      runs.push(new TextRun({
        text: match[3],
        bold: true,
        italics: defaults.italics,
        size: defaults.size || 24,
        font: defaults.font || 'Times New Roman',
        color: defaults.color,
      }))
    } else if (match[4]) {
      // Italic
      runs.push(new TextRun({
        text: match[4],
        bold: defaults.bold,
        italics: true,
        size: defaults.size || 24,
        font: defaults.font || 'Times New Roman',
        color: defaults.color,
      }))
    } else if (match[5]) {
      // Plain text
      runs.push(new TextRun({
        text: match[5],
        bold: defaults.bold,
        italics: defaults.italics,
        size: defaults.size || 24,
        font: defaults.font || 'Times New Roman',
        color: defaults.color,
      }))
    }
  }

  return runs.length ? runs : [new TextRun({
    text,
    bold: defaults.bold,
    italics: defaults.italics,
    size: defaults.size || 24,
    font: defaults.font || 'Times New Roman',
    color: defaults.color,
  })]
}

// ─── API Route ───────────────────────────────────────────────────

export async function POST(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
  }

  try {
    const { title, content } = await req.json()

    if (!title || !content) {
      return NextResponse.json({ error: 'Título e conteúdo são obrigatórios' }, { status: 400 })
    }

    const bodyParagraphs = parseMarkdownToParagraphs(content)

    const doc = new Document({
      styles: {
        default: {
          document: {
            run: {
              font: 'Times New Roman',
              size: 24,
            },
            paragraph: {
              spacing: { line: 360 },
            },
          },
        },
      },
      sections: [{
        properties: {
          page: {
            margin: {
              top: 1440,
              bottom: 1440,
              left: 1440,
              right: 1440,
            },
          },
        },
        headers: {
          default: {
            options: {
              children: [
                new Paragraph({
                  alignment: AlignmentType.LEFT,
                  spacing: { after: 100 },
                  children: [
                    new TextRun({
                      text: 'LexMind',
                      bold: true,
                      size: 28,
                      font: 'Times New Roman',
                      color: '0D9488',
                    }),
                    new TextRun({
                      text: ' — Inteligência Artificial Jurídica',
                      size: 20,
                      font: 'Times New Roman',
                      color: '6B7280',
                    }),
                  ],
                }),
                new Paragraph({
                  border: {
                    bottom: { style: BorderStyle.SINGLE, size: 2, color: '0D9488' },
                  },
                  spacing: { after: 200 },
                }),
              ],
            },
          },
        },
        footers: {
          default: {
            options: {
              children: [
                new Paragraph({
                  border: {
                    top: { style: BorderStyle.SINGLE, size: 1, color: 'D1D5DB' },
                  },
                  spacing: { before: 100 },
                  alignment: AlignmentType.CENTER,
                  children: [
                    new TextRun({
                      text: 'Documento gerado por LexMind — lexmind.adv.br',
                      size: 16,
                      font: 'Times New Roman',
                      color: '9CA3AF',
                    }),
                    new TextRun({
                      text: '    Página ',
                      size: 16,
                      font: 'Times New Roman',
                      color: '9CA3AF',
                    }),
                    new TextRun({
                      children: [PageNumber.CURRENT],
                      size: 16,
                      font: 'Times New Roman',
                      color: '9CA3AF',
                    }),
                  ],
                }),
              ],
            },
          },
        },
        children: [
          // Document Title
          new Paragraph({
            alignment: AlignmentType.CENTER,
            spacing: { before: 200, after: 400 },
            children: [
              new TextRun({
                text: title,
                bold: true,
                size: 36,
                font: 'Times New Roman',
                color: '111827',
              }),
            ],
          }),
          // Separator
          new Paragraph({
            border: {
              bottom: { style: BorderStyle.SINGLE, size: 1, color: 'D1D5DB' },
            },
            spacing: { after: 300 },
          }),
          // Body
          ...bodyParagraphs,
        ],
      }],
    })

    const buffer = await Packer.toBuffer(doc)

    return new NextResponse(buffer, {
      status: 200,
      headers: {
        'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'Content-Disposition': `attachment; filename="${encodeURIComponent(title)}.docx"`,
      },
    })
  } catch (error) {
    console.error('DOCX export error:', error)
    return NextResponse.json({ error: 'Erro ao gerar documento Word' }, { status: 500 })
  }
}
