"use client"

import { useState, useEffect } from "react"
import { Label } from "@/components/ui/label"
import { Slider } from "@/components/ui/slider"
import { Switch } from "@/components/ui/switch"
import { useTheme } from "next-themes"

export function GrainControl() {
  const [enableGrain, setEnableGrain] = useState(false)
  const [grainOpacity, setGrainOpacity] = useState(0.05)
  const [grainSize, setGrainSize] = useState(0.5)
  const { theme } = useTheme()

  useEffect(() => {
    if (typeof window === "undefined") return

    const root = document.documentElement

    if (enableGrain) {
      // Create SVG noise filter
      const svgNoise = `
        <svg xmlns="http://www.w3.org/2000/svg" width="0" height="0">
          <filter id="noise-filter">
            <feTurbulence type="fractalNoise" baseFrequency="${grainSize}" numOctaves="3" stitchTiles="stitch" />
            <feBlend mode="${theme === "dark" ? "overlay" : "soft-light"}" />
          </filter>
        </svg>
      `

      // Add SVG to document if not already present
      if (!document.getElementById("noise-svg")) {
        const div = document.createElement("div")
        div.id = "noise-svg"
        div.innerHTML = svgNoise
        div.style.position = "absolute"
        div.style.width = "0"
        div.style.height = "0"
        div.style.overflow = "hidden"
        document.body.appendChild(div)
      } else {
        document.getElementById("noise-svg")!.innerHTML = svgNoise
      }

      // Apply grain effect via CSS
      root.style.setProperty("--grain-opacity", grainOpacity.toString())
      root.style.setProperty("--grain-blend-mode", theme === "dark" ? "overlay" : "soft-light")
      root.classList.add("grain-effect")
    } else {
      root.classList.remove("grain-effect")
    }

    return () => {
      // Cleanup
      const noiseSvg = document.getElementById("noise-svg")
      if (noiseSvg && !enableGrain) {
        noiseSvg.remove()
      }
    }
  }, [enableGrain, grainOpacity, grainSize, theme])

  return (
    <div className="p-4">
      <div className="flex items-center justify-between mb-2">
        <h3 className="text-sm font-medium text-muted-foreground">Grain Texture</h3>
        <Switch checked={enableGrain} onCheckedChange={setEnableGrain} id="grain-toggle" />
      </div>

      {enableGrain && (
        <div className="space-y-4 mt-3">
          <div className="space-y-2">
            <div className="flex justify-between">
              <Label htmlFor="grain-opacity" className="text-xs">
                Opacity
              </Label>
              <span className="text-xs text-muted-foreground">{Math.round(grainOpacity * 100)}%</span>
            </div>
            <Slider
              id="grain-opacity"
              min={0.01}
              max={0.2}
              step={0.01}
              value={[grainOpacity]}
              onValueChange={(value) => setGrainOpacity(value[0])}
            />
          </div>

          <div className="space-y-2">
            <div className="flex justify-between">
              <Label htmlFor="grain-size" className="text-xs">
                Grain Size
              </Label>
              <span className="text-xs text-muted-foreground">
                {grainSize < 0.3 ? "Fine" : grainSize < 0.7 ? "Medium" : "Coarse"}
              </span>
            </div>
            <Slider
              id="grain-size"
              min={0.1}
              max={1}
              step={0.1}
              value={[grainSize]}
              onValueChange={(value) => setGrainSize(value[0])}
            />
          </div>
        </div>
      )}
    </div>
  )
}
