'use client'

import Link from 'next/link'
import React, { useEffect, useMemo, useRef, useState } from 'react'

import { AffiliateUnlockButton } from '@/components/AffiliateUnlockButton'
import RichText from '@/components/RichText'

type AdjacentChapter = {
  slug: string
  title: string
  chapterNumber: number
}

type ChapterReaderProps = {
  chapter: {
    title: string
    chapterNumber: number
    content?: any | null
    affiliateUnlock?: {
      url?: string | null
      label?: string | null
    } | null
  }
  storySlug: string
  storyTitle: string
  prevChapter?: AdjacentChapter | null
  nextChapter?: AdjacentChapter | null
}

const ChapterNav: React.FC<{
  storySlug: string
  prevChapter?: AdjacentChapter | null
  nextChapter?: AdjacentChapter | null
}> = ({ storySlug, prevChapter, nextChapter }) => (
  <div className="flex items-center justify-between gap-4 py-4 border-y border-border my-6">
    <div className="flex-1">
      {prevChapter ? (
        <Link
          href={`/truyen/${storySlug}/${prevChapter.slug}`}
          className="inline-flex items-center gap-1 text-sm hover:text-primary transition-colors"
        >
          ← Chương {prevChapter.chapterNumber}
        </Link>
      ) : (
        <span className="text-sm text-muted-foreground opacity-40">← Trước</span>
      )}
    </div>

    <Link
      href={`/truyen/${storySlug}`}
      className="text-sm text-muted-foreground hover:text-foreground transition-colors whitespace-nowrap px-3 py-1 rounded border border-border hover:bg-accent"
    >
      Mục Lục
    </Link>

    <div className="flex-1 text-right">
      {nextChapter ? (
        <Link
          href={`/truyen/${storySlug}/${nextChapter.slug}`}
          className="inline-flex items-center gap-1 text-sm hover:text-primary transition-colors"
        >
          Chương {nextChapter.chapterNumber} →
        </Link>
      ) : (
        <span className="text-sm text-muted-foreground opacity-40">Sau →</span>
      )}
    </div>
  </div>
)

export const ChapterReader: React.FC<ChapterReaderProps> = ({
  chapter,
  storySlug,
  storyTitle,
  prevChapter,
  nextChapter,
}) => {
  const [unlocked, setUnlocked] = useState(false)
  const protectedContentRef = useRef<HTMLDivElement | null>(null)

  const { firstContent, restContent } = useMemo(() => {
    const root = chapter.content?.root
    const children: any[] = root?.children ?? []
    const firstParagraphIndex = children.findIndex((node) => node.type === 'paragraph')

    if (firstParagraphIndex === -1) {
      return { firstContent: chapter.content, restContent: null }
    }

    return {
      firstContent: {
        ...chapter.content,
        root: { ...root, children: children.slice(0, firstParagraphIndex + 1) },
      },
      restContent:
        children.length > firstParagraphIndex + 1
          ? {
              ...chapter.content,
              root: { ...root, children: children.slice(firstParagraphIndex + 1) },
            }
          : null,
    }
  }, [chapter.content])

  const affiliateUrl = chapter.affiliateUnlock?.url
  const showBlur = Boolean(restContent) && Boolean(affiliateUrl) && !unlocked

  useEffect(() => {
    const root = protectedContentRef.current
    if (!root) return

    const isInsideProtectedContent = (target: EventTarget | null) =>
      target instanceof Node && root.contains(target)

    const preventIfProtected = (event: Event) => {
      if (!isInsideProtectedContent(event.target)) return
      event.preventDefault()
    }

    const handleKeydown = (event: KeyboardEvent) => {
      if (!(event.ctrlKey || event.metaKey)) return
      if (!isInsideProtectedContent(document.activeElement) && !root.contains(document.getSelection()?.anchorNode ?? null)) {
        return
      }

      const key = event.key.toLowerCase()
      if (key === 'a' || key === 'c' || key === 'x') {
        event.preventDefault()
      }
    }

    document.addEventListener('copy', preventIfProtected)
    document.addEventListener('cut', preventIfProtected)
    document.addEventListener('contextmenu', preventIfProtected)
    document.addEventListener('dragstart', preventIfProtected)
    document.addEventListener('selectstart', preventIfProtected)
    document.addEventListener('keydown', handleKeydown)

    return () => {
      document.removeEventListener('copy', preventIfProtected)
      document.removeEventListener('cut', preventIfProtected)
      document.removeEventListener('contextmenu', preventIfProtected)
      document.removeEventListener('dragstart', preventIfProtected)
      document.removeEventListener('selectstart', preventIfProtected)
      document.removeEventListener('keydown', handleKeydown)
    }
  }, [])

  return (
    <div className="container py-8 max-w-3xl">
      <p className="text-center text-sm text-muted-foreground mb-1">{storyTitle}</p>
      <h1 className="text-xl md:text-2xl font-bold text-center mb-6">
        Chương {chapter.chapterNumber}: {chapter.title}
      </h1>

      <ChapterNav storySlug={storySlug} prevChapter={prevChapter} nextChapter={nextChapter} />

      <div
        ref={protectedContentRef}
        className="select-none"
        onCopy={(event) => event.preventDefault()}
        onCut={(event) => event.preventDefault()}
        onContextMenu={(event) => event.preventDefault()}
        onDragStart={(event) => event.preventDefault()}
        style={{
          WebkitUserSelect: 'none',
          userSelect: 'none',
          WebkitTouchCallout: 'none',
        }}
      >
        {firstContent && (
          <RichText
            data={firstContent}
            enableGutter={false}
            className="prose-headings:font-semibold prose-p:leading-relaxed prose-p:text-base"
          />
        )}

        {restContent && (
          <div className="relative">
            <div
              className={
                showBlur
                  ? 'blur-sm pointer-events-none max-h-[240px] overflow-hidden'
                  : undefined
              }
            >
              <RichText
                data={restContent}
                enableGutter={false}
                className="prose-headings:font-semibold prose-p:leading-relaxed prose-p:text-base"
              />
            </div>

            {showBlur && (
              <div className="absolute inset-0 flex items-end justify-center pb-6 bg-gradient-to-t from-background via-background/95 to-transparent">
                <AffiliateUnlockButton
                  url={chapter.affiliateUnlock?.url}
                  label={chapter.affiliateUnlock?.label}
                  onUnlock={() => setUnlocked(true)}
                />
              </div>
            )}
          </div>
        )}
      </div>

      <ChapterNav storySlug={storySlug} prevChapter={prevChapter} nextChapter={nextChapter} />
    </div>
  )
}
