"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 { useSidebar } from "@/contexts/sidebar-context"
import { useView } from "@/contexts/view-context"
import { HiMoon, HiSun } from "react-icons/hi"
import { MdCheck, MdExpandMore } from "react-icons/md"
import { RiSideBarFill } from "react-icons/ri"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Button } from "@/components/ui/button"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { useTheme } from "next-themes"

// 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"

export function TopBar() {
  const { primaryColor, setPrimaryColor } = useColorPalette()
  const { materials, selectedMaterial, setSelectedMaterial } = useMaterial()
  const { borderRadius, setBorderRadius, font, setFont } = useDesign()
  const { sidebarVisible, toggleSidebar } = useSidebar()
  const { viewMode, toggleViewMode } = useView()
  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 [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])

  // 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 = (fontOption: any) => {
    if (typeof fontOption === "object") {
      setFont(fontOption.value)
      setSelectedFontName(fontOption.name)
    } else {
      setFont(fontOption)
      setSelectedFontName(fontOption)
    }
  }

  return (
    <div
      className={cn(
        "fixed top-0 right-0 z-30 py-2 flex items-center transition-all duration-300 ease-in-out bg-background",
        sidebarVisible ? "left-64" : "left-0",
      )}
      style={{ borderRadius: 0 }} // No border radius for the top bar container
    >
      {/* Sidebar toggle stays on the left */}
      {/* All other controls are centered in a grid layout */}
      <div className="w-full flex justify-center">
        <div className="flex items-start">
          {/* Color Section */}
          <div className="flex flex-col items-center px-6">
            <div className="text-xs text-muted-foreground mb-2">Color</div>
            <Popover open={isColorPickerOpen} onOpenChange={setIsColorPickerOpen}>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  className="h-10 w-10 p-0 border border-border shadow-sm"
                  style={{ backgroundColor: primaryColor, borderRadius: UI_BORDER_RADIUS }}
                >
                  <span className="sr-only">Pick a color</span>
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-72 p-4" style={{ borderRadius: UI_BORDER_RADIUS }}>
                <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">
                              <MdCheck 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 */}
          <div className="h-16 w-px bg-border self-center" />

          {/* Material Section */}
          <div className="flex flex-col items-center px-6">
            <div className="text-xs text-muted-foreground mb-2">Material</div>
            <div className="flex gap-2">
              {materials.slice(0, 3).map((material) => (
                <button
                  key={material.name}
                  onClick={() => setSelectedMaterial(material)}
                  className={cn(
                    "h-10 w-10 border border-border transition-all",
                    selectedMaterial?.name === material.name && "ring-2 ring-primary ring-offset-1",
                  )}
                  style={{
                    background:
                      material.name === "Glass"
                        ? "linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)"
                        : material.name === "Flat"
                          ? "#ffffff"
                          : "#0f1c3f",
                    borderRadius: UI_BORDER_RADIUS,
                  }}
                  aria-pressed={selectedMaterial?.name === material.name}
                  title={material.name}
                />
              ))}
            </div>
          </div>

          {/* Separator */}
          <div className="h-16 w-px bg-border self-center" />

          {/* Roundedness Section - Direct visualization of border radius */}
          <div className="flex flex-col items-center px-6">
            <div className="text-xs text-muted-foreground mb-2">Roundedness</div>
            <div className="flex gap-2">
              {[0, 6, 12, 20].map((value) => (
                <button
                  key={value}
                  onClick={() => setBorderRadius(value)}
                  className={cn(
                    "h-10 w-10 bg-background-primary border border-border transition-all",
                    borderRadius === value && "ring-2 ring-primary ring-offset-1",
                  )}
                  style={{
                    // Apply the actual border radius value directly to the button
                    borderRadius: `${value}px`,
                  }}
                  aria-pressed={borderRadius === value}
                  title={`${value}px border radius`}
                />
              ))}
            </div>
          </div>

          {/* Separator */}
          <div className="h-16 w-px bg-border self-center" />

          {/* Font Section - Using the default dropdown from styleguide */}
          <div className="flex flex-col items-center px-6">
            <div className="text-xs text-muted-foreground mb-2">Font</div>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="outline"
                  className="h-10 w-40 border-border bg-background flex justify-between items-center"
                  style={{ borderRadius: UI_BORDER_RADIUS }}
                >
                  <span style={{ fontFamily: font }}>{selectedFontName}</span>
                  <MdExpandMore className="h-4 w-4 ml-2" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent
                className="w-40 max-h-60 overflow-y-auto fixed-font"
                style={{ borderRadius: UI_BORDER_RADIUS, fontFamily: "Inter, sans-serif" }}
              >
                {availableFonts.map((fontOption) => {
                  const value = typeof fontOption === "object" ? fontOption.value : fontOption
                  const name = typeof fontOption === "object" ? fontOption.name : fontOption

                  return (
                    <DropdownMenuItem
                      key={value}
                      onClick={() => handleFontSelect(fontOption)}
                      className="text-sm cursor-pointer fixed-font"
                    >
                      <span className="fixed-font" style={{ fontFamily: value, fontSize: "14px" }}>
                        {name}
                      </span>
                    </DropdownMenuItem>
                  )
                })}
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </div>

      {/* Theme Toggle - Hidden in the mockup but keeping it accessible */}
      <div className="absolute right-4 top-2">
        <div
          className="flex h-9 items-center gap-1 border border-border px-1 bg-background"
          style={{ borderRadius: UI_BORDER_RADIUS }}
        >
          <button
            onClick={() => setTheme("light")}
            className={`h-7 w-7 flex items-center justify-center ${
              theme === "light" ? "bg-accent shadow-sm" : "bg-transparent"
            }`}
            style={{ borderRadius: "4px" }} // Slightly smaller radius for inner elements
            aria-label="Light mode"
          >
            <HiSun className="h-4 w-4 text-foreground" />
          </button>
          <button
            onClick={() => setTheme("dark")}
            className={`h-7 w-7 flex items-center justify-center ${
              theme === "dark" ? "bg-accent shadow-sm" : "bg-transparent"
            }`}
            style={{ borderRadius: "4px" }} // Slightly smaller radius for inner elements
            aria-label="Dark mode"
          >
            <HiMoon className="h-4 w-4 text-foreground" />
          </button>
        </div>
      </div>

      {/* Sidebar Toggle */}
      <div className="absolute left-4 top-2">
        <Button
          variant="ghost"
          size="icon"
          onClick={toggleSidebar}
          className="h-9 w-9"
          style={{ borderRadius: UI_BORDER_RADIUS }}
          aria-label="Toggle sidebar"
        >
          <RiSideBarFill className="h-5 w-5" />
        </Button>
      </div>
    </div>
  )
}

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