'use client'

import { Section } from '@/components/ui/section'
import { cn } from '@/lib/utils/cn'
import ImageLoader from '@/lib/utils/ImageLoader'
import { AudienceCard, Media, RentalItems } from '@/payload-types'
import { useHasBeenVisible } from '@/lib/utils/hooks'

import React, { useEffect, useRef, useState } from 'react'

export const RentalConditions = ({
  title,
  rentalItems,
  leftPhoto,
}: {
  title: string
  rentalItems: RentalItems
  leftPhoto: string | Media
}) => {
  const [activeIndex, setActiveIndex] = useState(0)
  const sectionRef = useRef<HTMLDivElement>(null)
  const hasBeenVisible = useHasBeenVisible(sectionRef)

  useEffect(() => {
    if (!hasBeenVisible) return
    const interval = setInterval(() => {
      setActiveIndex((prev) => (prev + 1) % (rentalItems?.length || 1))
    }, 2000)
    return () => clearInterval(interval)
  }, [hasBeenVisible])

  return (
    <Section
      ref={sectionRef}
      sectionClass="bg-base-white py-[80px] tablet:py-[100px] xl:py-[120px]"
    >
      <h2 className="subheadline-semibold tablet:h3 xl:h2 mb-6 tablet:mb-8">{title}</h2>
      <div className="grid rounded-[12px] overflow-hidden bg-base-black grid-cols-1 xl:[grid-template-columns:auto_1fr_1fr] items-stretch">
        {/* Карточки */}
        <div className="grid grid-cols-1 xl:grid-cols-2 gap-4 p-6 xl:col-span-2 xl:row-span-2 w-full">
          {(rentalItems || []).map((item, i) => (
            <div
              key={i}
              className={cn(
                'p-4  flex flex-col gap-8 xl:gap-[48px] border border-grey-800 rounded-[12px] xl:h-full',
              )}
            >
              <div className="w-[48px] h-[48px] rounded-full overflow-hidden bg-grey-900 flex items-center justify-center p-2">
                <ImageLoader
                  media={item.icon}
                  alt={item.title}
                  className="w-full h-full object-contain"
                />
              </div>
              <div>
                <p className="text-grey-200 mb-2 b2-medium xl:b1-medium">{item.title}</p>
                <p className="subheadline-semibold xl:h4 text-grey-50">{item.subtitle}</p>
                {item.caption && (
                  <p className="b3-regular xl:b2-regular text-grey-50">{item.caption}</p>
                )}
              </div>
            </div>
          ))}
        </div>
        {/* Картинка */}
        <div className="w-full xl:w-[384px] h-[320px] tablet:h-[440px] xl:h-full xl:col-span-1 xl:row-span-2 row-start-2 xl:row-start-1">
          <ImageLoader media={leftPhoto} alt="Left photo" className="w-full h-full object-cover" />
        </div>
      </div>
    </Section>
  )
}
