import { useEffect, useState } from "react"
import { Check, Palette } from "lucide-react"

import { Button } from "~/components/ui/button"
import {
  Popover,
  PopoverContent,
  PopoverDescription,
  PopoverHeader,
  PopoverTitle,
  PopoverTrigger,
} from "~/components/ui/popover"
import { cn } from "~/lib/utils"

export const backgrounds = [
  { id: "none", label: "None" },
  { id: "pearl", label: "Pearl" },
  { id: "linen", label: "Linen" },
  { id: "mist", label: "Mist" },
  { id: "dawn", label: "Dawn" },
  { id: "seafoam", label: "Seafoam" },
  { id: "aurora", label: "Aurora" },
  { id: "sunset", label: "Sunset" },
  { id: "meadow", label: "Meadow" },
  { id: "midnight", label: "Midnight" },
  { id: "blush", label: "Blush" },
  { id: "noir", label: "Noir" },
] as const

export type BackgroundId = (typeof backgrounds)[number]["id"]

const STORAGE_KEY = "crema-bg"
const DEFAULT_BG: BackgroundId = "none"

function isBackgroundId(value: string | null): value is BackgroundId {
  return !!value && backgrounds.some((b) => b.id === value)
}

function applyBg(id: BackgroundId) {
  if (id === "none") {
    delete document.body.dataset.bg
  } else {
    document.body.dataset.bg = id
  }
}

export function BackgroundPicker() {
  const [current, setCurrent] = useState<BackgroundId>(DEFAULT_BG)

  useEffect(() => {
    const stored = localStorage.getItem(STORAGE_KEY)
    const next = isBackgroundId(stored) ? stored : DEFAULT_BG
    setCurrent(next)
    applyBg(next)
  }, [])

  const select = (id: BackgroundId) => {
    setCurrent(id)
    applyBg(id)
    localStorage.setItem(STORAGE_KEY, id)
  }

  return (
    <Popover>
      <PopoverTrigger
        render={
          <Button
            data-action="appbar-background"
            variant="ghost"
            size="icon-sm"
            aria-label="Change background"
          >
            <Palette />
          </Button>
        }
      />
      <PopoverContent align="end" className="w-64">
        <PopoverHeader>
          <PopoverTitle>Background</PopoverTitle>
          <PopoverDescription>Pick an atmosphere.</PopoverDescription>
        </PopoverHeader>
        <div className="grid grid-cols-3 gap-2">
          {backgrounds.map((bg) => {
            const active = current === bg.id
            return (
              <button
                key={bg.id}
                type="button"
                onClick={() => select(bg.id)}
                aria-pressed={active}
                className={cn(
                  "group relative flex aspect-square flex-col justify-end overflow-hidden rounded-lg ring-1 ring-border transition-all duration-fast ease-standard hover:ring-foreground/30 focus-visible:ring-2 focus-visible:ring-ring",
                  bg.id === "none" ? "bg-background" : `bg-variant-${bg.id}`,
                  active && "ring-2 ring-primary"
                )}
              >
                {active && (
                  <span className="absolute top-1 right-1 flex size-4 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-e1">
                    <Check className="size-3" />
                  </span>
                )}
                <span className="rounded-b-lg bg-background/70 px-1.5 py-1 text-center text-[10px] font-medium tracking-tight backdrop-blur-sm">
                  {bg.label}
                </span>
              </button>
            )
          })}
        </div>
      </PopoverContent>
    </Popover>
  )
}
