"use client";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useCalendar } from "./CalendarContext";
import { CheckSquare, Square, Calendar } from "lucide-react";

export function CalendarSelector() {
  const {
    calendars,
    selectedCalendars,
    toggleCalendar,
    selectAllCalendars,
    deselectAllCalendars,
  } = useCalendar();

  if (calendars.length === 0) {
    return null;
  }

  const allSelected = selectedCalendars.length === calendars.length;
  const someSelected = selectedCalendars.length > 0 && !allSelected;

  return (
    <Card>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-base flex items-center gap-2">
            <Calendar className="w-4 h-4" />
            Calendars
          </CardTitle>
          <div className="flex gap-1">
            <Button
              variant="ghost"
              size="sm"
              onClick={selectAllCalendars}
              className="h-7 text-xs"
              disabled={allSelected}
            >
              <CheckSquare className="w-3 h-3 mr-1" />
              All
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={deselectAllCalendars}
              className="h-7 text-xs"
              disabled={selectedCalendars.length === 0}
            >
              <Square className="w-3 h-3 mr-1" />
              None
            </Button>
          </div>
        </div>
      </CardHeader>
      <CardContent className="pt-0">
        <ScrollArea className="h-[200px] pr-4">
          <div className="space-y-2">
            {calendars.map((calendar) => (
              <label
                key={calendar.id}
                className="flex items-center gap-3 p-2 rounded-lg hover:bg-accent cursor-pointer transition-colors"
              >
                <Checkbox
                  checked={selectedCalendars.includes(calendar.id)}
                  onCheckedChange={() => toggleCalendar(calendar.id)}
                />
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium truncate">
                    {calendar.summary}
                    {calendar.primary && (
                      <span className="ml-2 text-xs text-muted-foreground">
                        (Primary)
                      </span>
                    )}
                  </p>
                </div>
              </label>
            ))}
          </div>
        </ScrollArea>
        <p className="text-xs text-muted-foreground mt-3">
          {selectedCalendars.length} of {calendars.length} selected
        </p>
      </CardContent>
    </Card>
  );
}
