"use client"

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { cn } from "@/lib/utils"
import {
  MAIL_BACKGROUND_PRESETS,
  normalizeMailBackgroundId,
} from "@/lib/mail-settings/constants"
import type { MailBackgroundId } from "@/lib/mail-settings/types"
import { useMailSettingsStore } from "@/lib/stores/mail-settings-store"

export function ThemeSettingsDialog() {
  const open = useMailSettingsStore((s) => s.themeDialogOpen)
  const setOpen = useMailSettingsStore((s) => s.setThemeDialogOpen)
  const backgroundId = useMailSettingsStore((s) => s.backgroundId)
  const setBackgroundId = useMailSettingsStore((s) => s.setBackgroundId)
  const activeBackgroundId = normalizeMailBackgroundId(backgroundId)

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent
        overlayClassName="z-[70]"
        className="z-[70] max-w-md gap-5 border-border bg-background sm:max-w-lg"
      >
        <DialogHeader>
          <DialogTitle className="text-left text-base font-normal text-foreground">
            Arrière-plan
          </DialogTitle>
        </DialogHeader>

        <section>
          <div className="grid grid-cols-3 gap-2 sm:grid-cols-4">
            {MAIL_BACKGROUND_PRESETS.map((preset) => (
              <button
                key={preset.id}
                type="button"
                onClick={() => setBackgroundId(preset.id as MailBackgroundId)}
                className={cn(
                  "flex flex-col items-center gap-1 rounded-lg p-1 transition-colors",
                  activeBackgroundId === preset.id &&
                    "ring-2 ring-[#1a73e8] ring-offset-1 ring-offset-background"
                )}
                title={preset.label}
              >
                <span
                  className="block h-14 w-full rounded-md border border-border bg-cover bg-center"
                  style={
                    preset.background === "none"
                      ? { backgroundColor: "var(--app-canvas)" }
                      : {
                          backgroundColor: preset.fallbackColor,
                          background: preset.background,
                        }
                  }
                />
                <span
                  className={cn(
                    "max-w-full truncate text-[10px]",
                    activeBackgroundId === preset.id
                      ? "font-bold text-foreground dark:text-white"
                      : "text-muted-foreground dark:text-mail-text"
                  )}
                >
                  {preset.label}
                </span>
              </button>
            ))}
          </div>
        </section>
      </DialogContent>
    </Dialog>
  )
}
