"use client"

import type React from "react"

import { useState, useRef, useEffect } from "react"
import { useColorPalette } from "@/contexts/color-context"
import { useMaterial } from "@/contexts/material-context"
import { useDesign, availableFonts } from "@/contexts/design-context"
import { useTheme } from "next-themes"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { CheckIcon } from "@heroicons/react/24/outline"
import { ExportButtons } from "./export-buttons"
import { XMarkIcon } from "@heroicons/react/24/outline"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"

// Preset colors for the color picker
const presetColors = [
  { name: "Slack Blue", value: "#1D9BD1" },
  { name: "Discord Blurple", value: "#5865F2" },
  { name: "Spotify Green", value: "#1DB954" },
  { name: "Notion Red", value: "#E03E3E" },
  { name: "Figma Purple", value: "#A259FF" },
  { name: "Linear Pink", value: "#F687B3" },
  { name: "GitHub Green", value: "#2DA44E" },
  { name: "Vercel Cyan", value: "#00B8D9" },
  { name: "Stripe Purple", value: "#635BFF" },
  { name: "Raycast Orange", value: "#FF6363" },
  { name: "Twitter Blue", value: "#1DA1F2" },
  { name: "Tailwind Teal", value: "#0EA5E9" },
]

// Fixed border radius for UI components
const UI_BORDER_RADIUS = "6px"

// Default UI font that won't change with font selection
const UI_FONT = "Inter, sans-serif"

// Common fonts to prioritize
const COMMON_FONTS = [
  { name: "Inter", value: "Inter, sans-serif" },
  { name: "Arial", value: "Arial, sans-serif" },
  { name: "Helvetica", value: "Helvetica, sans-serif" },
  { name: "Roboto", value: "Roboto, sans-serif" },
  { name: "Open Sans", value: "Open Sans, sans-serif" },
  { name: "Poppins", value: "Poppins, sans-serif" },
]

export function RightSidebar() {
  const { primaryColor, setPrimaryColor } = useColorPalette()
  const { materials, selectedMaterial, setSelectedMaterial } = useMaterial()
  const { borderRadius, setBorderRadius, font, setFont } = useDesign()
  const [isColorPickerOpen, setIsColorPickerOpen] = useState(false)
  const [inputColor, setInputColor] = useState(primaryColor)
  const colorInputRef = useRef<HTMLInputElement>(null)
  const { setTheme, theme } = useTheme()
  const [mounted, setMounted] = useState(false)
  const [renderedFonts, setRenderedFonts] = useState<Set<string>>(new Set())

  const [selectedFontName, setSelectedFontName] = useState(() => {
    // Find the font name based on the current font value
    const fontObj = availableFonts.find((f) => typeof f === "object" && f.value === font)
    return fontObj ? fontObj.name : "Inter"
  })

  // Handle mounting for theme
  useEffect(() => {
    setMounted(true)
  }, [])

  // Update input color when primary color changes
  useEffect(() => {
    setInputColor(primaryColor)
  }, [primaryColor])

  // Initialize with common fonts
  const initializedRef = useRef(false)

  // Initialize with common fonts - using a ref to ensure it only runs once
  const hasInitializedRef = useRef(false)

  useEffect(() => {
    if (mounted && !hasInitializedRef.current) {
      hasInitializedRef.current = true

      // Set default border radius only once
      setBorderRadius(6)

      // Initialize fonts
      const initialFonts = new Set<string>()
      COMMON_FONTS.forEach((font) => {
        initialFonts.add(typeof font === "object" ? font.value : font)
      })

      // Add the currently selected font
      initialFonts.add(font)
      setRenderedFonts(initialFonts)
    }
  }, [mounted]) // Only depend on mounted state

  // Function to handle color change from the color picker
  const handleColorPickerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newColor = e.target.value
    setInputColor(newColor)
    setPrimaryColor(newColor)
  }

  // Function to handle color input change
  const handleColorInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newColor = e.target.value
    setInputColor(newColor)

    // Validate if it's a valid hex color
    if (/^#([0-9A-F]{3}){1,2}$/i.test(newColor)) {
      setPrimaryColor(newColor)
    }
  }

  // Function to handle color input blur
  const handleColorInputBlur = () => {
    // Ensure the color is valid, if not revert to the current primary color
    if (!/^#([0-9A-F]{3}){1,2}$/i.test(inputColor)) {
      setInputColor(primaryColor)
    } else {
      setPrimaryColor(inputColor)
    }
  }

  // Function to handle preset color selection
  const handlePresetColorSelect = (color: string) => {
    setInputColor(color)
    setPrimaryColor(color)
  }

  // Function to handle font selection
  const handleFontSelect = (value: string) => {
    // Find the font object by value
    const fontObj = availableFonts.find((f) => typeof f === "object" && f.value === value)
    if (fontObj && typeof fontObj === "object") {
      setFont(fontObj.value)
      setSelectedFontName(fontObj.name)
    } else {
      setFont(value)
      setSelectedFontName(value)
    }
  }

  // Get theme-aware selection border color
  const getSelectionBorderColor = (opacity = 0.9) => {
    return theme === "dark" ? `rgba(255, 255, 255, ${opacity})` : `rgba(0, 0, 0, ${opacity})`
  }

  // Get theme-aware hover border color with 36% opacity
  const getHoverBorderColor = () => {
    return theme === "dark" ? "rgba(255, 255, 255, 0.36)" : "rgba(0, 0, 0, 0.36)"
  }

  // Get theme-aware selection background color
  const getSelectionBackgroundColor = () => {
    return theme === "dark" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.05)"
  }

  // Material tile border radius - consistent value for all material tiles
  const MATERIAL_TILE_RADIUS = "8px"

  if (!mounted) {
    return null
  }

  // Function to handle color picker button click
  const handleColorPickerClick = () => {
    setIsColorPickerOpen(!isColorPickerOpen)
  }

  const Separator = () => <div className="h-px w-full separator-custom my-4"></div>

  return (
    <div
      className="h-full bg-background-primary right-sidebar flex flex-col overflow-hidden"
      style={{ fontFamily: UI_FONT, height: "100%", maxHeight: "100%", paddingTop: 0 }}
    >
      {/* Close button for mobile */}
      <button
        className="absolute top-4 right-4 md:hidden"
        onClick={() => {
          const sidebar = document.querySelector(".right-sidebar")
          const overlay = document.querySelector(".right-sidebar-overlay")
          const content = document.querySelector(".main-content")

          if (sidebar) sidebar.classList.remove("visible")
          if (overlay) overlay.classList.remove("visible")
          if (content) content.classList.remove("mobile-adjusted-content")
        }}
      >
        <XMarkIcon className="h-5 w-5" />
      </button>

      {/* Rest of the sidebar content */}
      <div className="flex flex-col justify-between h-full overflow-y-auto pl-8 pr-0">
        <div className="flex-grow">
          {/* Properties Card */}
          <Card className="w-full right-sidebar-card">
            <CardContent className="p-4">
              {/* Color Section */}
              <div className="mb-4">
                <h3 className="text-sm font-medium text-muted-foreground mb-2">Color</h3>
                <Popover>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      className="h-10 w-10 p-0 border border-border shadow-sm rounded-xl"
                      style={{ backgroundColor: primaryColor }}
                      onClick={handleColorPickerClick}
                    >
                      <span className="sr-only">Pick a color</span>
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent
                    className="w-72 p-4 z-50"
                    style={{ borderRadius: UI_BORDER_RADIUS, fontFamily: UI_FONT }}
                  >
                    <div className="space-y-4">
                      <div
                        className="relative w-full h-32 border overflow-hidden"
                        style={{ borderRadius: UI_BORDER_RADIUS }}
                      >
                        <input
                          ref={colorInputRef}
                          type="color"
                          value={inputColor}
                          onChange={handleColorPickerChange}
                          className="absolute inset-0 w-full h-full opacity-100 cursor-pointer"
                        />
                      </div>
                      <div className="flex items-center gap-2">
                        <div
                          className="w-8 h-8 border"
                          style={{ backgroundColor: inputColor, borderRadius: UI_BORDER_RADIUS }}
                        />
                        <input
                          type="text"
                          value={inputColor}
                          onChange={handleColorInputChange}
                          onBlur={handleColorInputBlur}
                          className="flex-1 px-2 py-1 text-sm border"
                          style={{ borderRadius: UI_BORDER_RADIUS }}
                        />
                      </div>

                      <div className="space-y-2">
                        <div className="text-xs font-medium text-muted-foreground">Preset Colors</div>
                        <div className="grid grid-cols-6 gap-2">
                          {presetColors.map((color) => (
                            <button
                              key={color.value}
                              className="relative w-9 h-9 border border-border overflow-hidden group"
                              style={{ backgroundColor: color.value, borderRadius: UI_BORDER_RADIUS }}
                              onClick={() => handlePresetColorSelect(color.value)}
                              title={color.name}
                            >
                              {primaryColor.toLowerCase() === color.value.toLowerCase() && (
                                <div className="absolute inset-0 flex items-center justify-center bg-black/20">
                                  <CheckIcon className="h-4 w-4 text-white" />
                                </div>
                              )}
                              <div className="absolute inset-0 flex items-center justify-center bg-black/20 opacity-0 group-hover:opacity-100 transition-opacity">
                                <span className="text-[8px] font-medium text-white">{color.name}</span>
                              </div>
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>
                  </PopoverContent>
                </Popover>
              </div>

              {/* Separator */}
              <Separator />

              {/* Material Section */}
              <div className="mb-4">
                <h3 className="text-sm font-medium text-muted-foreground mb-2">Material</h3>
                <div className="flex gap-2">
                  {materials.map((material) => {
                    // Determine background and styling based on material type and current theme
                    const isGlass = material.name === "Glass"
                    const isSelected = selectedMaterial?.name === material.name

                    // Get theme-aware styling
                    const bgColor =
                      theme === "dark"
                        ? isGlass
                          ? "rgba(17, 17, 17, 0.7)"
                          : "#111111"
                        : isGlass
                          ? "rgba(255, 255, 255, 0.7)"
                          : "#ffffff"

                    return (
                      <button
                        key={material.name}
                        onClick={() => setSelectedMaterial(material)}
                        className={cn(
                          "relative h-10 w-10 transition-all overflow-hidden group",
                          isSelected ? "shadow-md" : "border border-border",
                        )}
                        style={{
                          borderRadius: MATERIAL_TILE_RADIUS,
                          border: isSelected ? `2px solid ${getSelectionBorderColor()}` : undefined,
                          boxShadow: isSelected ? `0 0 0 1px ${getSelectionBackgroundColor()}` : undefined,
                          transition: "all 0.2s ease-in-out",
                        }}
                        aria-pressed={isSelected}
                        title={material.name}
                      >
                        {/* Background pattern for glass material */}
                        {isGlass && (
                          <div
                            className="absolute inset-0 opacity-10"
                            style={{
                              backgroundImage:
                                theme === "dark"
                                  ? "url('/subtle-dark-pattern.png')"
                                  : "url('/subtle-light-pattern.png')",
                              backgroundSize: "cover",
                              borderRadius: MATERIAL_TILE_RADIUS,
                            }}
                          />
                        )}

                        {/* Card preview */}
                        <div
                          className="absolute inset-0 flex items-center justify-center"
                          style={{
                            background: bgColor,
                            backdropFilter: isGlass ? "blur(8px)" : "none",
                            WebkitBackdropFilter: isGlass ? "blur(8px)" : "none",
                            borderRadius: MATERIAL_TILE_RADIUS,
                          }}
                        >
                          {/* Mini card content representation */}
                          <div className="w-10 h-8 flex flex-col justify-center items-center scale-75">
                            <div
                              className="w-8 h-1 mb-1 rounded-sm"
                              style={{
                                background: theme === "dark" ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.3)",
                              }}
                            />
                            <div
                              className="w-6 h-1 rounded-sm"
                              style={{
                                background: theme === "dark" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.2)",
                              }}
                            />
                          </div>
                        </div>

                        {/* Material name label */}
                        <div
                          className="absolute bottom-0 inset-x-0 text-[8px] text-center py-0.5"
                          style={{
                            background: theme === "dark" ? "rgba(0, 0, 0, 0.5)" : "rgba(255, 255, 255, 0.5)",
                            color: theme === "dark" ? "rgba(255, 255, 255, 0.8)" : "rgba(0, 0, 0, 0.8)",
                            backdropFilter: "blur(4px)",
                            borderBottomLeftRadius: MATERIAL_TILE_RADIUS,
                            borderBottomRightRadius: MATERIAL_TILE_RADIUS,
                          }}
                        >
                          {material.name}
                        </div>

                        {/* Hover effect - using group hover instead of CSS hover */}
                        {!isSelected && (
                          <div
                            className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                            style={{
                              boxShadow: `inset 0 0 0 2px ${getHoverBorderColor()}`,
                              borderRadius: MATERIAL_TILE_RADIUS,
                            }}
                          />
                        )}
                      </button>
                    )
                  })}
                </div>
              </div>

              {/* Separator */}
              <Separator />

              {/* Roundedness Section */}
              <div className="mb-4">
                <h3 className="text-sm font-medium text-muted-foreground mb-2">Roundedness</h3>
                <div className="flex gap-2">
                  {[0, 6, 12, 20].map((value) => (
                    <Card
                      key={value}
                      onClick={() => setBorderRadius(value)}
                      className={cn(
                        "h-8 w-10 cursor-pointer transition-all relative group",
                        borderRadius === value ? "shadow-md" : "border border-border",
                      )}
                      style={{
                        borderRadius: `${value}px`,
                        border: borderRadius === value ? `2px solid ${getSelectionBorderColor()}` : undefined,
                        boxShadow: borderRadius === value ? `0 0 0 1px ${getSelectionBackgroundColor()}` : undefined,
                        transition: "all 0.2s ease-in-out",
                      }}
                    >
                      {/* Number value label */}
                      <div className="absolute inset-0 flex items-center justify-center">
                        <span className="text-xs font-medium text-muted-foreground">
                          {value === 0 ? "0" : (value / 16).toFixed(1)}
                        </span>
                      </div>

                      {/* Hover effect - using group hover instead of CSS hover */}
                      {borderRadius !== value && (
                        <div
                          className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                          style={{
                            boxShadow: `inset 0 0 0 2px ${getHoverBorderColor()}`,
                            borderRadius: `${value}px`,
                          }}
                        />
                      )}
                    </Card>
                  ))}
                </div>
              </div>

              {/* Separator */}
              <Separator />

              {/* Font Section */}
              <div>
                <h3 className="text-sm font-medium text-muted-foreground mb-2">Font</h3>
                <Select value={font} onValueChange={handleFontSelect}>
                  <SelectTrigger className="w-full h-10">
                    <SelectValue placeholder="Select a font" style={{ fontFamily: font }}>
                      {selectedFontName}
                    </SelectValue>
                  </SelectTrigger>
                  <SelectContent>
                    <div className="py-1">
                      {/* Common fonts first */}
                      <div className="px-3 py-2 text-xs font-semibold text-muted-foreground">Common Fonts</div>
                      {COMMON_FONTS.map((fontOption) => {
                        const value = typeof fontOption === "object" ? fontOption.value : fontOption
                        const name = typeof fontOption === "object" ? fontOption.name : fontOption

                        return (
                          <SelectItem key={value} value={value} style={{ fontFamily: value }}>
                            {name}
                          </SelectItem>
                        )
                      })}

                      {/* Divider */}
                      <Separator />

                      {/* All other fonts */}
                      <div className="px-3 py-2 text-xs font-semibold text-muted-foreground">All Fonts</div>
                      {availableFonts
                        .filter(
                          (f) =>
                            !COMMON_FONTS.some(
                              (cf) =>
                                (typeof f === "object" ? f.value : f) === (typeof cf === "object" ? cf.value : cf),
                            ),
                        )
                        .map((fontOption) => {
                          const value = typeof fontOption === "object" ? fontOption.value : fontOption
                          const name = typeof fontOption === "object" ? fontOption.name : fontOption

                          return (
                            <SelectItem key={value} value={value} style={{ fontFamily: value }}>
                              {name}
                            </SelectItem>
                          )
                        })}
                    </div>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Export Buttons at the bottom */}
        <div className="py-4">
          <ExportButtons />
        </div>
      </div>
    </div>
  )
}

function cn(...classes: (string | boolean | undefined)[]) {
  return classes.filter(Boolean).join(" ")
}
