import { useState, useEffect, useRef, type FC, type ReactNode } from 'react'
import { motion } from 'framer-motion'
import { cn } from '@/lib/utils/cn'
import { Button } from '@/components/ui/button'
import { ArrowLeftIcon, ArrowRightIcon } from '@/components/icons/common'
import useGetResponsiveView from '@/lib/hooks/useGetResponsiveView'

import { Review } from '@/payload-types'
import { ButtonArrow } from '@/components/icons/button-icon'
import ImageLoader from '@/lib/utils/ImageLoader'
import { InstagramIcon } from '@/components/icons/socials'

interface ModalReviewSliderProps {
  cards: Review[]
  initialId?: string
  initialIndex?: number
  gap?: number
  itemWidth?: number
  totalCount?: number
  onShowMore?: () => Promise<void>
  loadingMore?: boolean
}

export const ModalReviewSlider: FC<ModalReviewSliderProps> = ({
  cards,
  initialId,
  initialIndex,
  gap = 20,
  itemWidth = 540,
  totalCount,
  onShowMore,
  loadingMore,
}) => {
  const containerRef = useRef<HTMLDivElement>(null)
  const { isMobileView } = useGetResponsiveView()
  const currentWidth = isMobileView ? 320 : Math.min(itemWidth, 984)
  // Один слайд за раз
  const slideStep = 1

  // Определяем стартовый индекс
  const getInitialIndex = () => {
    if (typeof initialIndex === 'number') return initialIndex
    if (initialId) {
      const idx = cards.findIndex((card) => card.id === initialId)
      return idx !== -1 ? idx : 0
    }
    return 0
  }
  const [activeIndex, setActiveIndex] = useState(getInitialIndex())

  useEffect(() => {
    const idx = getInitialIndex()
    setActiveIndex(idx)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [initialId, initialIndex])

  const isBeginning = activeIndex === 0
  const isEnd = activeIndex === cards.length - 1

  const slideNext = async () => {
    if (!isEnd) {
      setActiveIndex((prev) => Math.min(prev + 1, cards.length - 1))
    } else if (totalCount && cards.length < totalCount && onShowMore) {
      await onShowMore()
      setActiveIndex((prev) => prev + 1)
    }
  }

  const slidePrev = () => {
    if (!isBeginning) setActiveIndex((prev) => Math.max(prev - 1, 0))
  }

  const goToSlide = (index: number) => {
    setActiveIndex(index)
  }

  return (
    <div className=" max-w-[984px] overflow-hidden" ref={containerRef}>
      {/* Один слайд */}
      <div className="max-h-[80vh] h-[70vh] tablet:max-h-[738px] xl:max-h-[466px] relative w-full bg-base-black rounded-2xl p-6 gradient-border gradient-border--white-light">
        {/* <div className="w-[338px] h-[36px] absolute right-[-60px] xl:right-[-171px] bottom-[10px] xl:bottom-[88px] rounded-full bg-[#D39E7F] blur-[78px] opacity-80"></div> */}
        <div className="w-full h-full flex gap-6  flex-col xl:flex-row relative z-10">
          <div className="rounded-xl relative overflow-hidden min-h-[180px] h-[180px] max-h-[180px] tablet:max-h-[359px] xl:max-h-[418px] flex-1">
            <ImageLoader
              media={cards[activeIndex].image}
              className="absolute inset-0 object-cover w-full h-full"
              alt=""
            />
          </div>
          <div className="flex flex-1 flex-col w-full min-h-0">
            {/* Header — фиксированная высота */}
            <div className="mb-4 tablet:mb-[48px] pb-4 flex justify-between border-b border-grey-900 flex-shrink-0">
              <div>
                <p className="label-medium-regular tablet:label-large-regular text-grey-400 mb-[2px]">
                  Author
                </p>
                <p className="label-medium-semibold tablet:label-large-semibold text-grey-50">
                  {cards[activeIndex].author || ''}
                </p>
              </div>
              <p className="label-medium-regular tablet:b3-regular text-grey-100 mt-[10px]">
                {new Date(cards[activeIndex].createdAt).toLocaleDateString('en-US', {
                  year: 'numeric',
                  month: 'long',
                  day: 'numeric',
                })}
              </p>
            </div>
            {/* Text block — занимает всё оставшееся пространство */}
            <div className="relative flex-1 min-h-0 flex flex-col">
              <div className="flex flex-col gap-2 h-full overflow-y-auto custom-scrollbar pr-4">
                <p className="text-base-white b2-semibold tablet:subheadline-semibold">
                  {cards[activeIndex].title}
                </p>
                <p className="text-grey-100 b3-regular tablet:b2-regular">
                  {cards[activeIndex].subtitle}
                </p>
              </div>
            </div>
            {/* Footer — фиксированная высота */}
            <div className="border-t border-grey-900 pt-4 mt-4 flex items-end justify-between flex-shrink-0">
              <p className="b3-regular text-grey-100">Review from</p>
              <Button
                iconOnly
                variant="icon-only"
                sizes="icon-btn-sm"
                icon={<InstagramIcon className="w-fit" width={14} height={14} />}
              />
            </div>
          </div>
        </div>
      </div>
      <div className="flex justify-between items-center gap-8 mt-8 select-none">
        <Button
          variant="icon-only"
          onClick={slidePrev}
          iconOnly
          disabled={isBeginning}
          sizes="icon-btn-md"
          className={cn(
            'text-[#FCFCFC] transition-colors',
            !isBeginning && 'hover:text-primary',
            isBeginning && 'opacity-30 cursor-not-allowed',
          )}
          icon={
            <ButtonArrow className="w-fit -rotate-180 transition-colors" width={7} height={14} />
          }
        />

        <div className="flex gap-[6px] items-center">
          {cards.map((_, i) => (
            <div
              key={i}
              onClick={() => goToSlide(i)}
              className={cn(
                'size-2 rounded-full opacity-45 transition-colors bg-grey-200 cursor-pointer',
                i === activeIndex && 'bg-grey-100 size-3 opacity-100',
              )}
            />
          ))}
        </div>
        <Button
          variant="icon-only"
          onClick={slideNext}
          iconOnly
          disabled={isEnd && (!totalCount || cards.length >= totalCount || loadingMore)}
          sizes="icon-btn-md"
          className={cn(
            'text-[#FCFCFC] transition-colors',
            (!isEnd || (totalCount && cards.length < totalCount && !loadingMore)) &&
              'hover:text-primary',
            isEnd && (!totalCount || cards.length >= totalCount) && 'opacity-30 cursor-not-allowed',
            loadingMore && 'opacity-50 cursor-wait',
          )}
          icon={<ButtonArrow className="w-fit transition-colors" width={7} height={14} />}
        />
      </div>
    </div>
  )
}

export default ModalReviewSlider
