'use client'

import React, { useEffect, useRef } from 'react'
import { Button } from '../ui/button'
import { ButtonArrow } from '../icons/button-icon'
import { Swiper, SwiperRef, SwiperSlide } from 'swiper/react'
import 'swiper/css'
import 'swiper/css/navigation'
import 'swiper/css/grid'
import 'swiper/css/pagination'
import 'swiper/css/effect-fade'
import { cn } from '@/lib/utils/cn'

interface TimePickerProps {
  value?: Date
  onChange?: (date: Date) => void
  containerClass?: string
}

interface SliderElementProps {
  values: string[]
  selectedIndex: number
  onIndexChange: (index: number) => void
  sliderRef: React.RefObject<SwiperRef | null>
}

const SliderElement: React.FC<SliderElementProps> = ({
  values,
  selectedIndex,
  onIndexChange,
  sliderRef,
}) => {
  useEffect(() => {
    sliderRef.current?.swiper.slideToLoop(selectedIndex)
  }, [selectedIndex, sliderRef])

  return (
    <div className="flex flex-col justify-center items-center">
      <Button
        onClick={() => onIndexChange((selectedIndex + 1) % values.length)}
        sizes="icon-btn-sm"
        className="-rotate-90"
        iconOnly
        icon={<ButtonArrow width={10} height={10} fill="#F6ECE5" />}
        variant="icon-only-without-bg"
      />
      <Swiper
        loop
        ref={sliderRef as React.RefObject<SwiperRef>}
        slidesPerView={1}
        direction="vertical"
        initialSlide={selectedIndex}
        onSlideChange={(swiper) => onIndexChange(swiper.realIndex)}
        className="h-10 w-8 overflow-hidden"
      >
        {values.map((val, idx) => (
          <SwiperSlide key={idx} className="size-full w-full flex justify-center items-center">
            <div className="size-full flex justify-center items-center">
              <div className="text-center my-auto b2-regular text-base-white"> {val} </div>
            </div>
          </SwiperSlide>
        ))}
      </Swiper>
      <Button
        onClick={() => onIndexChange((selectedIndex - 1 + values.length) % values.length)}
        sizes="icon-btn-sm"
        className="rotate-90"
        iconOnly
        icon={<ButtonArrow width={10} height={10} fill="#F6ECE5" />}
        variant="icon-only-without-bg"
      />
    </div>
  )
}

export const TimePicker: React.FC<TimePickerProps> = ({ value, onChange, containerClass = '' }) => {
  const hoursRef = useRef<SwiperRef | null>(null)
  const minutesRef = useRef<SwiperRef | null>(null)
  const periodRef = useRef<SwiperRef | null>(null)

  const currentDate = value ?? new Date()

  const hour12 = currentDate.getHours() % 12 || 12
  const hours = Array.from({ length: 12 }, (_, i) => (i + 1).toString().padStart(2, '0'))
  const minutes = ['00', '15', '30', '45']
  const periods = ['AM', 'PM']

  // Fix: Calculate the correct 0-based index for the hour
  const initialHourIndex = (hour12 - 1 + 12) % 12
  
  const [hourIndex, setHourIndex] = React.useState(initialHourIndex)
  const [minuteIndex, setMinuteIndex] = React.useState(
    minutes.indexOf(currentDate.getMinutes().toString().padStart(2, '0')),
  )
  const [periodIndex, setPeriodIndex] = React.useState(currentDate.getHours() >= 12 ? 1 : 0)

  useEffect(() => {
    if (onChange) {
      const newDate = new Date(currentDate)
      let h = parseInt(hours[hourIndex], 10) % 12
      if (periods[periodIndex] === 'PM') h += 12
      newDate.setHours(h)
      newDate.setMinutes(parseInt(minutes[minuteIndex], 10))
      onChange(newDate)
    }
  }, [hourIndex, minuteIndex, periodIndex])

  return (
    <div
      className={cn(
        'p-2 bg-grey-700 flex items-center justify-center gap-4 rounded-lg border border-[#FCFCFC33]',
        containerClass,
      )}
    >
      <SliderElement
        values={hours}
        selectedIndex={hourIndex}
        onIndexChange={setHourIndex}
        sliderRef={hoursRef}
      />
      <div className="b2-regular text-base-white">:</div>
      <SliderElement
        values={minutes}
        selectedIndex={minuteIndex}
        onIndexChange={setMinuteIndex}
        sliderRef={minutesRef}
      />
      <SliderElement
        values={periods}
        selectedIndex={periodIndex}
        onIndexChange={setPeriodIndex}
        sliderRef={periodRef}
      />
    </div>
  )
}

export default TimePicker
