"use client"

import Link from "next/link"
import { X } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet"
import { AgendaSettingsFields } from "@/components/agenda/agenda-settings-fields"
import { ThemeSettingsDialog } from "@/components/gmail/quick-settings/theme-settings-dialog"
import { useAgendaSettingsStore } from "@/lib/agenda/agenda-store"
import { useMailSettingsStore } from "@/lib/stores/mail-settings-store"
import { MAIL_SETTINGS_BASE_PATH } from "@/lib/mail-settings/settings-nav"
import { cn } from "@/lib/utils"

export function AgendaQuickSettingsPanel() {
  const open = useAgendaSettingsStore((s) => s.quickSettingsOpen)
  const setOpen = useAgendaSettingsStore((s) => s.setQuickSettingsOpen)
  const themeDialogOpen = useMailSettingsStore((s) => s.themeDialogOpen)
  const setThemeDialogOpen = useMailSettingsStore((s) => s.setThemeDialogOpen)

  return (
    <Sheet open={open} onOpenChange={(next) => !next && setOpen(false)}>
      <SheetContent
        side="right"
        hideClose
        overlayClassName={cn("bg-black/20", themeDialogOpen && "hidden")}
        aria-label="Configuration rapide Agenda"
        aria-describedby={undefined}
        className="w-full gap-0 border-border bg-mail-surface p-0 text-foreground sm:max-w-[360px]"
        onInteractOutside={(e) => {
          if (themeDialogOpen) e.preventDefault()
        }}
        onEscapeKeyDown={(e) => {
          if (themeDialogOpen) e.preventDefault()
        }}
      >
        <header className="flex shrink-0 items-center justify-between gap-2 px-4 pt-5 pb-3">
          <SheetTitle className="text-base font-normal text-foreground dark:text-white">
            Configuration rapide
          </SheetTitle>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="size-9 text-muted-foreground"
            aria-label="Fermer"
            onClick={() => setOpen(false)}
          >
            <X className="size-5" />
          </Button>
        </header>

        <div className="min-h-0 flex-1 overflow-y-auto pb-6">
          <div className="px-4 pb-4">
            <Button
              variant="outline"
              className="h-10 w-full rounded-full border-[#1a73e8] text-[#1a73e8] hover:bg-[#e8f0fe]/50 dark:border-[#9aa0a6] dark:text-white dark:hover:bg-[#3c4043]/50"
              asChild
            >
              <Link href={`${MAIL_SETTINGS_BASE_PATH}/agenda`} onClick={() => setOpen(false)}>
                Voir tous les paramètres
              </Link>
            </Button>
          </div>
          <AgendaSettingsFields onOpenThemeDialog={() => setThemeDialogOpen(true)} />
        </div>
      </SheetContent>
    </Sheet>
  )
}

export function AgendaQuickSettingsRoot() {
  return (
    <>
      <AgendaQuickSettingsPanel />
      <ThemeSettingsDialog />
    </>
  )
}
