import { useState } from 'react';
import { format, isWithinInterval, startOfMonth, endOfMonth, eachDayOfInterval, getDay, parseISO } from 'date-fns';
import { motion } from 'framer-motion';

export default function CalendarSelector({ startDate, endDate, votes, onToggle, readOnly = false }) {
    const start = parseISO(startDate);
    const end = parseISO(endDate);
    const months = eachDayOfInterval({ start: startOfMonth(start), end: endOfMonth(end) })
        .filter(d => d.getDate() === 1);

    const MonthView = ({ monthStart }) => {
        const daysInMonth = eachDayOfInterval({
            start: startOfMonth(monthStart),
            end: endOfMonth(monthStart)
        });
        const startOffset = getDay(monthStart);

        return (
            <div className="mb-8">
                <h3 className="font-bold text-lg mb-4 text-slate-800 capitalize sticky top-0 bg-slate-50/95 backdrop-blur py-2 z-10 border-b border-slate-200/50">
                    {format(monthStart, 'MMMM yyyy')}
                </h3>
                <div className="grid grid-cols-7 gap-1 sm:gap-2">
                    {['S', 'M', 'T', 'W', 'T', 'F', 'S'].map(d => (
                        <div key={d} className="text-center text-xs text-slate-400 font-bold py-2">{d}</div>
                    ))}
                    {Array(startOffset).fill(null).map((_, i) => <div key={`empty-${i}`} />)}
                    {daysInMonth.map(date => {
                        const inRange = isWithinInterval(date, { start, end });
                        const dateStr = format(date, 'yyyy-MM-dd');
                        const status = votes[dateStr];

                        if (!inRange) {
                            return (
                                <div key={dateStr} className="aspect-square flex items-center justify-center text-slate-300 text-sm">
                                    {format(date, 'd')}
                                </div>
                            );
                        }

                        return (
                            <DateCell
                                key={dateStr}
                                date={date}
                                status={status}
                                onToggle={() => !readOnly && onToggle(dateStr)}
                                readOnly={readOnly}
                            />
                        );
                    })}
                </div>
            </div>
        );
    };

    return (
        <div className="w-full select-none">
            {months.map(m => <MonthView key={m.toString()} monthStart={m} />)}
        </div>
    );
}

function DateCell({ date, status, onToggle, readOnly }) {
    let bg = 'bg-white border border-slate-200';
    let text = 'text-slate-600';
    let scale = 1;
    const isAvailable = status === 'available';
    const isUnavailable = status === 'unavailable';

    if (isAvailable) {
        bg = 'bg-primary text-white border-primary shadow-md shadow-primary/30';
        text = 'text-white';
        scale = 1.05;
    } else if (isUnavailable) {
        bg = 'bg-rose-50 border-rose-200';
        text = 'text-rose-400 line-through decoration-2';
        scale = 0.95;
    }

    return (
        <motion.button
            whileTap={!readOnly ? { scale: 0.9 } : {}}
            animate={{ scale }}
            onClick={onToggle}
            className={`
        aspect-square rounded-lg flex items-center justify-center text-sm font-medium transition-all relative
        ${bg} ${text} ${readOnly ? 'cursor-default' : 'cursor-pointer hover:shadow-sm'}
        ${!status && !readOnly ? 'hover:border-primary/50' : ''}
      `}
            disabled={readOnly}
        >
            {format(date, 'd')}
            {isAvailable && (
                <motion.div
                    initial={{ scale: 0 }}
                    animate={{ scale: 1 }}
                    className="absolute -top-1 -right-1 w-2.5 h-2.5 bg-white rounded-full border-2 border-primary"
                />
            )}
        </motion.button>
    );
}
