import { useState, useMemo } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
interface DateRange {
  start: string;
  end: string;
}

interface AvailabilityCalendarProps {
  blockedDates: DateRange[];
  bookedDates: DateRange[];
}

type DayStatus = 'available' | 'booked' | 'blocked';

function isDateInRanges(date: Date, ranges: DateRange[]): boolean {
  const time = date.getTime();
  return ranges.some(range => {
    const start = new Date(range.start);
    start.setHours(0, 0, 0, 0);
    const end = new Date(range.end);
    end.setHours(23, 59, 59, 999);
    return time >= start.getTime() && time <= end.getTime();
  });
}

function getDaysInMonth(year: number, month: number): number {
  return new Date(year, month + 1, 0).getDate();
}

function getFirstDayOfMonth(year: number, month: number): number {
  return new Date(year, month, 1).getDay();
}

const MONTH_NAMES = [
  'January', 'February', 'March', 'April', 'May', 'June',
  'July', 'August', 'September', 'October', 'November', 'December',
];

const DAY_LABELS = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];

export function AvailabilityCalendar({ blockedDates, bookedDates }: AvailabilityCalendarProps) {
  const today = new Date();
  const [viewYear, setViewYear] = useState(today.getFullYear());
  const [viewMonth, setViewMonth] = useState(today.getMonth());

  const daysInMonth = getDaysInMonth(viewYear, viewMonth);
  const firstDay = getFirstDayOfMonth(viewYear, viewMonth);

  const dayStatuses = useMemo(() => {
    const statuses: (DayStatus | null)[] = [];

    // Leading empty cells
    for (let i = 0; i < firstDay; i++) {
      statuses.push(null);
    }

    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(viewYear, viewMonth, day);
      date.setHours(0, 0, 0, 0);

      if (isDateInRanges(date, bookedDates)) {
        statuses.push('booked');
      } else if (isDateInRanges(date, blockedDates)) {
        statuses.push('blocked');
      } else {
        statuses.push('available');
      }
    }

    return statuses;
  }, [viewYear, viewMonth, firstDay, daysInMonth, blockedDates, bookedDates]);

  const goToPrevMonth = () => {
    if (viewMonth === 0) {
      setViewMonth(11);
      setViewYear(y => y - 1);
    } else {
      setViewMonth(m => m - 1);
    }
  };

  const goToNextMonth = () => {
    if (viewMonth === 11) {
      setViewMonth(0);
      setViewYear(y => y + 1);
    } else {
      setViewMonth(m => m + 1);
    }
  };

  const statusStyles: Record<DayStatus, string> = {
    available: 'bg-green-100 text-green-800',
    booked: 'bg-red-100 text-red-700',
    blocked: 'bg-gray-100 text-gray-400',
  };

  const isCurrentMonth = viewYear === today.getFullYear() && viewMonth === today.getMonth();

  return (
    <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <button
          onClick={goToPrevMonth}
          className="p-1.5 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer"
        >
          <ChevronLeft className="w-5 h-5 text-gray-600" />
        </button>
        <h3 className="text-sm font-semibold text-gray-900">
          {MONTH_NAMES[viewMonth]} {viewYear}
        </h3>
        <button
          onClick={goToNextMonth}
          className="p-1.5 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer"
        >
          <ChevronRight className="w-5 h-5 text-gray-600" />
        </button>
      </div>

      {/* Day labels */}
      <div className="grid grid-cols-7 gap-1 mb-1">
        {DAY_LABELS.map(label => (
          <div key={label} className="text-center text-xs font-medium text-gray-400 py-1">
            {label}
          </div>
        ))}
      </div>

      {/* Calendar grid */}
      <div className="grid grid-cols-7 gap-1">
        {dayStatuses.map((status, idx) => {
          if (status === null) {
            return <div key={`empty-${idx}`} />;
          }

          const dayNumber = idx - firstDay + 1;
          const isToday = isCurrentMonth && dayNumber === today.getDate();

          return (
            <div
              key={idx}
              className={`text-center text-xs py-1.5 rounded-lg font-medium
                ${statusStyles[status]}
                ${isToday ? 'ring-2 ring-primary-400 ring-offset-1' : ''}`}
            >
              {dayNumber}
            </div>
          );
        })}
      </div>

      {/* Legend */}
      <div className="flex items-center gap-4 mt-4 pt-3 border-t border-gray-100">
        <div className="flex items-center gap-1.5">
          <div className="w-3 h-3 rounded bg-green-100 border border-green-200" />
          <span className="text-xs text-gray-500">Available</span>
        </div>
        <div className="flex items-center gap-1.5">
          <div className="w-3 h-3 rounded bg-red-100 border border-red-200" />
          <span className="text-xs text-gray-500">Booked</span>
        </div>
        <div className="flex items-center gap-1.5">
          <div className="w-3 h-3 rounded bg-gray-100 border border-gray-200" />
          <span className="text-xs text-gray-500">Blocked</span>
        </div>
      </div>
    </div>
  );
}
