"use client"

import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { AutomationBorderedFieldset } from "@/components/gmail/settings/automation/automation-bordered-fieldset"
import { useAgendaCalendars } from "@/lib/api/hooks/use-calendar-queries"
import type { WebhookAgendaScope } from "@/lib/mail-automation/webhook-config"

export function WebhookAgendaScopeEditor({
  scope,
  onChange,
  enabled,
  className,
}: {
  scope: WebhookAgendaScope
  onChange: (scope: WebhookAgendaScope) => void
  enabled: boolean
  className?: string
}) {
  const { data: calendars = [], isLoading } = useAgendaCalendars()

  if (!enabled) return null

  function toggleCalendar(calendarId: string) {
    const ids = scope.calendar_ids.includes(calendarId)
      ? scope.calendar_ids.filter((id) => id !== calendarId)
      : [...scope.calendar_ids, calendarId]
    onChange({ all_calendars: false, calendar_ids: ids })
  }

  return (
    <AutomationBorderedFieldset
      className={className}
      legend="Périmètre agenda — calendriers"
    >
      <label className="flex items-start gap-2">
        <Checkbox
          checked={scope.all_calendars}
          onCheckedChange={(checked) =>
            onChange({
              all_calendars: checked === true,
              calendar_ids: checked === true ? [] : scope.calendar_ids,
            })
          }
          className="mt-0.5"
        />
        <span className="text-sm">
          Tous les agendas
          <span className="mt-0.5 block text-xs text-muted-foreground">
            Le webhook ne se déclenchera que pour les événements agenda sélectionnés.
          </span>
        </span>
      </label>

      {!scope.all_calendars && (
        <div className="space-y-2 pl-1">
          <Label className="text-xs text-muted-foreground">Agendas autorisés</Label>
          {isLoading ? (
            <p className="text-sm text-muted-foreground">Chargement…</p>
          ) : calendars.length === 0 ? (
            <p className="text-sm text-muted-foreground">Aucun agenda configuré.</p>
          ) : (
            <ul className="space-y-1.5">
              {calendars.map((cal) => (
                <li key={cal.id}>
                  <label className="flex cursor-pointer items-center gap-2 rounded-md border border-border px-2.5 py-2 hover:bg-muted/40">
                    <Checkbox
                      checked={scope.calendar_ids.includes(cal.id)}
                      onCheckedChange={() => toggleCalendar(cal.id)}
                    />
                    <span
                      className="size-2.5 shrink-0 rounded-full"
                      style={{ backgroundColor: cal.color || "#1a73e8" }}
                      aria-hidden
                    />
                    <span className="text-sm">{cal.display_name || cal.id}</span>
                  </label>
                </li>
              ))}
            </ul>
          )}
        </div>
      )}
    </AutomationBorderedFieldset>
  )
}
