'use client';

import React from 'react';

import { useLocale } from 'next-intl';

import { format, isSameDay } from 'date-fns';
import { enUS, hu } from 'date-fns/locale';
import { MdChevronLeft, MdChevronRight } from 'react-icons/md';
import { useMediaQuery } from 'react-responsive';

import AppSwiper, { AppSwiperSlide } from '@/components/swiper/AppSwiper';
import { useAppSwiper } from '@/components/swiper/useAppSwiper';
import { cn } from '@/lib/utils';

import { Event } from '@/types/Events';

interface DayCarouselProps {
  days: Date[];
  selectedDay: Date | null;
  onSelectDay: (day: Date | null) => void;
  eventsByDate: Record<string, Event[]>;
}

const DayCarousel: React.FC<DayCarouselProps> = ({
  days,
  selectedDay,
  onSelectDay,
  eventsByDate,
}) => {
  const locale = useLocale();
  const dateLocale = locale === 'hu' ? hu : enUS;
  const isMobile = useMediaQuery({ maxWidth: 1023 });
  const controller = useAppSwiper({
    slideCount: days.length,
    loop: false,
    autoplay: false,
  });

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const isToday = (day: Date) => {
    const dayToCheck = new Date(day);
    dayToCheck.setHours(0, 0, 0, 0);
    return dayToCheck.getTime() === today.getTime();
  };

  const handleDayClick = (day: Date) => {
    if (selectedDay && isSameDay(day, selectedDay)) {
      onSelectDay(null);
    } else {
      onSelectDay(day);
    }
  };

  const renderDayButton = (day: Date) => {
    const isSelected = selectedDay && isSameDay(day, selectedDay);
    const eventCount = (eventsByDate[format(day, 'yyyy-MM-dd')] || []).length;
    const hasEvents = eventCount > 0;
    const todayFlag = isToday(day);

    return (
      <button
        key={format(day, 'yyyy-MM-dd')}
        onClick={() => handleDayClick(day)}
        className={cn(
          'relative flex-shrink-0 snap-center border transition-all duration-200 flex flex-col items-center justify-center',
          isMobile ? 'py-1.5 px-2.5 min-w-14' : 'py-3 px-3 min-w-20',
          isSelected
            ? 'bg-[#151720] text-white border-[#151720] shadow-[0_20px_40px_-30px_rgba(20,25,40,0.9)]'
            : todayFlag
              ? 'bg-mma-yellow/35 text-[#151720] border-[#151720]/20'
              : !hasEvents
                ? 'bg-[#151720]/[0.03] text-[#151720]/55 border-[#151720]/10 hover:border-[#151720]/25 hover:bg-[#151720]/[0.05]'
                : 'bg-white text-[#151720]/80 border-[#151720]/10 hover:border-[#151720]/30 hover:bg-[#151720]/[0.04]'
        )}
      >
        <div
          className={cn(
            'text-[9px] sm:text-[10px] font-semibold uppercase tracking-[0.14em] sm:tracking-[0.16em]',
            isSelected ? 'text-white/70' : 'text-[#151720]/50'
          )}
        >
          {format(day, 'MMM', { locale: dateLocale }).replace(/\.$/, '')}
        </div>
        <div className={cn('font-black', isMobile ? 'text-base' : 'text-xl')}>
          {format(day, 'd', { locale: dateLocale })}
        </div>
        <div className="text-[10px] font-semibold uppercase tracking-[0.12em]">
          {format(day, 'EE', { locale: dateLocale })}
        </div>
        <div
          className={cn(
            'mt-1',
            isMobile ? 'w-1 h-1' : 'w-1.5 h-1.5',
            hasEvents ? (isSelected ? 'bg-white' : 'bg-[#151720]/70') : 'bg-transparent'
          )}
        />
      </button>
    );
  };

  return (
    <div className="ui-panel z-20 w-full p-1.5 sm:p-2 shadow-[0_20px_60px_-45px_rgba(20,25,40,0.3)] flex flex-col gap-1.5 sm:gap-2 lg:sticky lg:top-[var(--header-h)]">
      <div className={cn('flex items-center', isMobile ? 'gap-0' : 'gap-2')}>
        {!isMobile && (
          <button
            onClick={controller.prev}
            disabled={controller.isBeginning}
            className={cn(
              'ui-control p-2 text-[#151720]/70 transition-colors flex-shrink-0',
              controller.isBeginning && 'cursor-not-allowed opacity-40'
            )}
            aria-label="Previous day"
          >
            <MdChevronLeft size={20} />
          </button>
        )}

        <div className="min-w-0 flex-1">
          <AppSwiper
            slideCount={days.length}
            controller={controller}
            loop={false}
            autoplay={false}
            enableKeyboard={false}
            swiperOptions={{
              slidesPerView: 'auto',
              spaceBetween: isMobile ? 6 : 8,
              speed: 450,
              className: cn('scroll-smooth', isMobile ? 'py-1.5 -mx-1 px-1' : 'pb-2'),
            }}
          >
            {days.map((day) => (
              <AppSwiperSlide key={format(day, 'yyyy-MM-dd')} className="!w-auto">
                {renderDayButton(day)}
              </AppSwiperSlide>
            ))}
          </AppSwiper>
        </div>

        {!isMobile && (
          <button
            onClick={controller.next}
            disabled={controller.isEnd}
            className={cn(
              'ui-control p-2 text-[#151720]/70 transition-colors flex-shrink-0',
              controller.isEnd && 'cursor-not-allowed opacity-40'
            )}
            aria-label="Next day"
          >
            <MdChevronRight size={20} />
          </button>
        )}
      </div>
    </div>
  );
};

export default DayCarousel;
