'use client'
import { RichText } from '@/components/shared/RichText/RichText'
import { ShareButtons } from '@/components/shared/shareButtons/ShareButtons'
import { CustomBreadcrumb } from '@/components/ui/breadcrumb'
import { Button } from '@/components/ui/button'
import { Section } from '@/components/ui/section'
import { getReadingTime } from '@/lib/utils/calculateArticleReadTime'
import { cn } from '@/lib/utils/cn'
import ImageLoader from '@/lib/utils/ImageLoader'
import { useCurrentLocale, useI18n } from '@/locales/client'
import { News } from '@/payload-types'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { Fragment, useEffect, useState } from 'react'

export const ArticleContent = ({
  currentNews,
  allNews,
}: {
  currentNews: News
  allNews: News[]
}) => {
  const locale = useCurrentLocale()
  const router = useRouter()
  const [activeId, setActiveId] = useState<string | null>(null)
  const [activeIndex, setActiveIndex] = useState(
    allNews.findIndex((item) => item.id === currentNews.id),
  )

  useEffect(() => {
    if (
      allNews[activeIndex] &&
      allNews[activeIndex].id &&
      allNews[activeIndex].id !== currentNews.id
    ) {
      router.push(`/${locale}/blog/${allNews[activeIndex].id}`)
    }
  }, [activeIndex])

  useEffect(() => {
    const headings = currentNews?.contents
      ?.map((item) => item.id)
      .filter((id): id is string => !!id)
      .map((id) => document.getElementById(id))

    const handleScroll = () => {
      if (!headings || headings.length === 0) return

      let closestHeading = null
      let minDistance = Infinity

      for (const heading of headings) {
        if (!heading) continue

        const rect = heading.getBoundingClientRect()
        const distance = Math.abs(rect.top - 100)

        if (rect.top <= 150 && distance < minDistance) {
          minDistance = distance
          closestHeading = heading
        }
      }

      setActiveId(closestHeading?.id || headings[0]?.id || null)
    }

    window.addEventListener('scroll', handleScroll)
    handleScroll()

    return () => window.removeEventListener('scroll', handleScroll)
  }, [currentNews?.contents])


  const t = useI18n()

  const getLocaleTimeZone = () => {
    if (locale === 'en') return "en-US"
    if (locale === 'ru') return 'ru-RU'
    if (locale === 'es') return 'es-ES'
    return 'en-US'
  }
  return (
    <Section sectionClass="bg-base-black py-30">
      <CustomBreadcrumb
        pages={[
          { pageName: t('navigation.blog'), href: `/${locale}/blog` },
          { pageName: currentNews.title, href: `${locale}/blog/${currentNews.id}`, isActive: true },
        ]}
      />
      <div className="flex flex-col md:flex-row gap-y-4 justify-between  items-start md:items-end mt-8">
        <div className="max-w-[951] h4 lg:h1 text-base-white">{currentNews.title}</div>
        <div className="min-w-[209px] rounded-[40px] bg-grey-700 flex gap-2 p-1 pr-4">
          <div className="size-12 rounded-full bg-base-black flex items-center justify-center">
            <ImageLoader
              media={currentNews.authorImage}
              className="size-6 rounded-full object-cover"
            />
          </div>

          <div className="flex flex-col gap-1">
            <div className="text-grey-400 label-medium-regular">{t('blog.author')}</div>
            <div className="label-medium-semibold text-grey-50">{currentNews.author}</div>
          </div>
        </div>
      </div>
      <div className="flex flex-col md:flex-row gap-y-4 justify-between items-start md:items-end mt-6">
        <div className="flex gap-2 items-center">
          {currentNews.tags &&
            currentNews.tags.map((tag) => (
              <div
                key={tag.id}
                className="label-medium-regular text-grey-100 px-4 py-1 rounded-[40px] bg-grey-700 cursor-pointer hover:bg-grey-400"
              >
                {tag.title}
              </div>
            ))}
        </div>
        <div className="flex gap-2 items-center">
          <div className="b3-regular text-grey-100">
            {getReadingTime(currentNews.contents, t)}
          </div>
          <div className="b3-regular text-grey-600">/</div>
          <div className="b3-regular text-grey-100">
            {new Date(currentNews.createdAt).toLocaleDateString(getLocaleTimeZone(), {
              year: 'numeric',
              month: 'long',
              day: 'numeric',
            })}
          </div>
        </div>
      </div>
      <div className="mt-10 relative">
        <ImageLoader
          className="w-full h-[380px] md:h-[654px] object-cover rounded-xl"
          media={currentNews.image}
        />
        <div className="absolute left-1/2 -translate-x-1/2 md:translate-x-0 bottom-4 md:left-4 rounded-2xl bg-transparent-black-78 flex items-center gap-4 p-3 flex-col gap-y-4 md:flex-row">
          <div className="b3-semibold text-base-white">{t('blog.share')}</div>
          <ShareButtons />
        </div>
      </div>
      <div className={cn('mt-16 flex justify-between flex-col-reverse  lg:flex-row gap-y-6')}>
        <div className={cn('w-full lg:w-[784px]')}>
          <div className="b1-regular text-grey-100 mb-16">{currentNews.subtitle}</div>
          {currentNews?.contents?.map((item) => (
            <Fragment key={item.id}>
              <div className="h4 lg:h2 text-base-white" id={item.id ?? ''}>
                {item.title}
              </div>
              <RichText data={item.content} />
            </Fragment>
          ))}
        </div>
        <div className={cn('relative w-full lg:w-[384px]')}>
          <div
            className={cn(
              'flex flex-col justify-start gap-1 border border-grey-700 w-full pl-0 lg:sticky top-20 left-0 bg-transparent-grey-40 p-4 rounded-xl',
            )}
          >
            {currentNews?.contents?.map((item, idx) => (
              <Link
                key={idx}
                href={`#${item?.id}`}
                onClick={(e) => {
                  e.preventDefault()
                  document.getElementById(item.id!)?.scrollIntoView({
                    behavior: 'smooth',
                  })
                }}
              >
                <div
                  className={cn(
                    'b2-regular cursor-pointer transition-colors w-full p-4 rounded-md hover:bg-transparent-white-20 hover:text-grey-50',
                    activeId === item.id ? 'text-grey-50 bg-transparent-white-20' : 'text-grey-200',
                  )}
                >
                  {`${item?.title}`}
                </div>
              </Link>
            ))}
            <div className="hidden lg:block h-px w-full bg-grey-800 mt-6 mb-8" />
            <div className="hidden lg:block b3-semibold text-base-white">{t('blog.share')}</div>
            <div className="hidden lg:block mt-4">
              <ShareButtons />
            </div>
          </div>
        </div>
      </div>
      <div className="block lg:hidden">
        <div className="flex flex-col items-center justify-center p-6 rounded-xl  gradient-border gradient-border--white gap-4">
          <div className="b3-semibold text-base-white">{t('blog.share')}</div>
          <ShareButtons />
        </div>
      </div>
      <div className="flex items-center justify-center gap-2 md:gap-10 py-8 mt-16 border-t border-b border-grey-800">
        <Button
          disabled={activeIndex === 0}
          onClick={() => {
            if (activeIndex > 0) {
              setActiveIndex(activeIndex - 1)
            }
          }}
          variant="secondary"
          isLeftIcon={true}
          className="px-4 button-small-medium md:button-large-medium"
        >
          {t('blog.prev')}
        </Button>
        <Button
          disabled={activeIndex === allNews.length - 1}
          onClick={() => {
            if (activeIndex < allNews.length - 1 && allNews[activeIndex + 1]) {
              setActiveIndex(activeIndex + 1)
            }
          }}
          variant="secondary"
          isRightIcon={true}
          className="px-2 md:px-4 button-small-medium md:button-large-medium"
        >
          {t('blog.next')}
        </Button>
      </div>
    </Section>
  )
}
