import React from 'react';
import { Calendar } from 'lucide-react';
import { useTranslations } from 'next-intl';

interface CalendarDay {
  date: string;
  day: number;
  month: string;
  dayName: string;
  available: boolean;
}

interface DateSelectorProps {
  selectedDate: string;
  availableDates: string[];
  onDateChange: (date: string) => void;
  loading?: boolean;
}

const DateSelector: React.FC<DateSelectorProps> = ({
  selectedDate,
  availableDates,
  onDateChange,
  loading = false,
}) => {
  const t = useTranslations('bookingForm');

  const generateCalendarDays = (): CalendarDay[] => {
    const today = new Date();
    const days: CalendarDay[] = [];
    
    // Show 30 days instead of 14 for better selection
    for (let i = 0; i < 30; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);
      const dateString = date.toISOString().split('T')[0] || '';
      
      // Create date object from the ISO string to avoid timezone issues
      const displayDate = new Date(dateString + 'T12:00:00.000Z');
      
      days.push({
        date: dateString,
        day: parseInt(dateString.split('-')[2]),
        month: displayDate.toLocaleDateString('en', { month: 'short', timeZone: 'UTC' }),
        dayName: displayDate.toLocaleDateString('en', { weekday: 'short', timeZone: 'UTC' }),
        available: availableDates.includes(dateString)
      });
    }
    return days;
  };

  const calendarDays = generateCalendarDays();

  return (
    <div className="bg-white rounded-xl p-6 shadow-sm">
      <h2 className="text-xl font-semibold text-gray-900 mb-4 flex items-center gap-2">
        <Calendar className="w-5 h-5" />
        {t('chooseDate')}
      </h2>
      
      {loading ? (
        <div className="flex justify-center items-center py-8">
          <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
          <span className="ml-2 text-gray-600">Loading available dates...</span>
        </div>
      ) : (
        <div className="grid grid-cols-7 gap-2 md:gap-3">
          {calendarDays.map((day) => (
            <button
              key={day.date}
              type="button"
              onClick={() => day.available && onDateChange(day.date)}
              disabled={!day.available}
              className={`p-3 rounded-lg text-center transition-all ${
                !day.available
                  ? 'bg-gray-50 text-gray-300 cursor-not-allowed'
                  : selectedDate === day.date
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-100 hover:bg-gray-200 text-gray-700'
              }`}
            >
              <div className="text-xs font-medium">{day.dayName}</div>
              <div className="text-sm font-semibold">{day.day}</div>
              <div className="text-xs">{day.month}</div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

export default DateSelector;