'use client'

import { Button } from '@/components/ui/button'
import { Section } from '@/components/ui/section'

import { useRouter, useSearchParams } from 'next/navigation'
import { useEffect, useState } from 'react'
import { ReviewsCard } from '@/components/shared/cards/reviewsCard'
import { Media } from '@/payload-types'
import ModalRadix from '@/components/shared/ModalRadix'
import ModalReviewSlider from '@/components/shared/slider/ModalReviewSlider'

interface ReviewsSectionClientProps {
  title: string
  subtitle: string
  initialDocs: any[]
  totalCount: number
  initialLimit: number
}

export function ReviewsSectionClient({
  title,
  subtitle,
  initialDocs,
  totalCount,
  initialLimit,
}: ReviewsSectionClientProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [reviews, setReviews] = useState(initialDocs)
  const [limit, setLimit] = useState(initialLimit)
  const [loading, setLoading] = useState(false)

  // При монтировании читаем лимит из URL, если он есть и отличается от initialLimit
  useEffect(() => {
    const urlLimit = Number(searchParams.get('limit'))
    if (urlLimit && urlLimit !== initialLimit) {
      setLimit(urlLimit)
      fetch(`/api/reviews?limit=${urlLimit}`)
        .then((res) => res.json())
        .then((data) => setReviews(data.docs))
    }
    // eslint-disable-next-line
  }, [])

  const handleShowMore = async () => {
    setLoading(true)
    const newLimit = limit + 4
    const res = await fetch(`/api/reviews-list?limit=${newLimit}`)
    const data = await res.json()
    setReviews(data.docs)
    setLimit(newLimit)
    // Обновляем URL
    const params = new URLSearchParams(Array.from(searchParams.entries()))
    params.set('limit', String(newLimit))
    router.replace(`?${params.toString()}`, { scroll: false })
    setLoading(false)
  }

  const [activeId, setActiveId] = useState<string | null>(null)
  const [isModalOpen, setIsModalOpen] = useState(false)

  const handleShowCard = (id: string) => {
    setActiveId(id)
    setIsModalOpen(true)
  }
  const handleCloseModal = () => {
    setIsModalOpen(false)
    setActiveId(null)
  }

  return (
    <>
      <Section sectionClass="mt-0 xl:mt-[56px] mb-[80px] tablet:mb-[100px] xl:mb-[120px]">
        <h2 className=" h4 tablet:h2 xl:h1 text-base-white mb-2">{title}</h2>
        <p className="b3-regular tablet:b1-regular text-grey-100 mb-6 tablet:mb-8">{subtitle}</p>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {reviews.map((card) => (
            <ReviewsCard
              text={card.subtitle}
              title={card.title}
              image={card.image as Media}
              key={card.id}
              onClick={() => handleShowCard(card.id)}
              type="button"
            />
          ))}
        </div>
        {reviews.length < totalCount && (
          <div className="flex justify-center pt-8">
            <Button variant="secondary" onClick={handleShowMore} disabled={loading}>
              {loading ? 'Loading...' : 'Show more'}
            </Button>
          </div>
        )}
      </Section>
      <ModalRadix open={isModalOpen} onClose={handleCloseModal}>
        {activeId && (
          <ModalReviewSlider
            cards={reviews}
            initialId={activeId}
            totalCount={totalCount}
            onShowMore={handleShowMore}
            loadingMore={loading}
          />
        )}
      </ModalRadix>
    </>
  )
}
