"use client"

import { useColorPalette } from "@/contexts/color-context"
import { useTheme } from "next-themes"
import { Copy, Check } from "lucide-react"
import { useState, useEffect } from "react"
import { SectionHeading } from "@/components/ui/section-heading"
import { semanticColors } from "@/utils/semantic-colors"

// Function to get computed CSS variable value
function getCssVariableValue(cssVar: string) {
  return typeof window !== "undefined" ? getComputedStyle(document.documentElement).getPropertyValue(cssVar) : ""
}

// Percolate-aligned code field component for key-value pairs
interface CodeFieldProps {
  variable: string
  value: string
}

function CodeField({ variable, value }: CodeFieldProps) {
  const [copiedVariable, setCopiedVariable] = useState(false)
  const [copiedValue, setCopiedValue] = useState(false)

  const copyToClipboard = (text: string, type: "variable" | "value") => {
    navigator.clipboard.writeText(text).then(() => {
      if (type === "variable") {
        setCopiedVariable(true)
        setTimeout(() => setCopiedVariable(false), 2000)
      } else {
        setCopiedValue(true)
        setTimeout(() => setCopiedValue(false), 2000)
      }
    })
  }

  return (
    <div className="group bg-background-primary border border-border rounded-lg px-3 py-2.5 hover:border-border/60 transition-colors duration-150">
      <div className="font-mono text-sm flex items-center justify-between">
        <div className="flex items-center gap-3 flex-1 min-w-0">
          {/* Variable */}
          <div className="flex items-center gap-1.5 group/var">
            <span className="text-foreground select-all font-medium">{variable}</span>
            <button
              onClick={() => copyToClipboard(variable, "variable")}
              className="opacity-0 group-hover/var:opacity-100 transition-opacity duration-150 p-0.5 hover:bg-muted rounded"
              title="Copy variable"
            >
              {copiedVariable ? (
                <Check className="h-3 w-3 text-green-600 dark:text-green-400" />
              ) : (
                <Copy className="h-3 w-3 text-muted-foreground hover:text-foreground" />
              )}
            </button>
          </div>

          {/* Separator */}
          <span className="text-muted-foreground">:</span>

          {/* Value */}
          <div className="flex items-center gap-1.5 group/val flex-1 min-w-0">
            <span className="text-muted-foreground select-all truncate">{value}</span>
            <button
              onClick={() => copyToClipboard(value, "value")}
              className="opacity-0 group-hover/val:opacity-100 transition-opacity duration-150 p-0.5 hover:bg-muted rounded flex-shrink-0"
              title="Copy value"
            >
              {copiedValue ? (
                <Check className="h-3 w-3 text-green-600 dark:text-green-400" />
              ) : (
                <Copy className="h-3 w-3 text-muted-foreground hover:text-foreground" />
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

// Add minimal prop to the component
interface ColorSectionProps {
  minimal?: boolean
}

export function ColorSection({ minimal = false }: ColorSectionProps) {
  const [mounted, setMounted] = useState(false)
  const { theme, resolvedTheme } = useTheme()
  const [copiedColor, setCopiedColor] = useState<string | null>(null)

  // Use a try-catch to handle potential context errors
  const colorContext = useColorPalette()

  // Set mounted state after hydration
  useEffect(() => {
    setMounted(true)
  }, [])

  const copyToClipboard = (text: string, colorName: string) => {
    if (typeof navigator !== "undefined") {
      navigator.clipboard.writeText(text).then(() => {
        setCopiedColor(colorName)
        setTimeout(() => setCopiedColor(null), 2000)
      })
    }
  }

  // Get current theme for semantic colors
  const currentTheme = (resolvedTheme || theme) as "light" | "dark"
  const themeKey = currentTheme === "dark" ? "dark" : "light"

  // If not mounted yet, show a loading state
  if (!mounted) {
    return <div>Loading color section...</div>
  }

  // If minimal is true, return a simplified version
  if (minimal) {
    return (
      <div>
        <h3 className="text-xl font-medium mb-4">Color System</h3>
        <div className="grid grid-cols-5 gap-2">
          {["primary", "secondary", "accent", "success", "warning"].map((color) => (
            <div key={color} className="flex flex-col items-center">
              <div className="w-10 h-10 rounded-full mb-2" style={{ backgroundColor: `var(--${color})` }} />
              <span className="text-xs text-muted-foreground capitalize">{color.replace("-", " ")}</span>
            </div>
          ))}
        </div>
      </div>
    )
  }

  return (
    <section id="color" className="scroll-mt-16 space-y-12">
      <SectionHeading
        title="Color"
        description="The color system defines the visual language of your interface. The primary color defines the brand identity, while the semantic colors provide consistent feedback and status indicators."
      />

      {/* Primary Color System */}
      <div className="space-y-8">
        <div>
          <h3 className="text-xl font-semibold mb-2">Primary Color System</h3>
          <p className="text-muted-foreground text-sm mb-8">
            The main brand color and its automatically generated palette of shades from 50 to 900
          </p>
        </div>

        {/* Primary Color Swatch */}
        <div
          className="h-32 w-full rounded-lg shadow-md flex flex-col justify-center items-center cursor-pointer relative group transition-all duration-200 hover:shadow-lg"
          style={{ backgroundColor: colorContext.primaryColor }}
          onClick={() => copyToClipboard(colorContext.primaryColor, "primary")}
        >
          <div className="text-white text-xl font-bold mb-2">Primary</div>
          <div className="text-white/90 font-mono">{colorContext.primaryColor}</div>

          {copiedColor === "primary" && (
            <div className="absolute inset-0 flex items-center justify-center bg-black/40 text-white backdrop-blur-sm rounded-lg">
              <span className="text-sm font-medium flex items-center gap-2">
                <Check className="h-4 w-4" /> Copied to clipboard
              </span>
            </div>
          )}

          <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity rounded-lg">
            <div className="bg-black/30 text-white text-sm font-medium py-1.5 px-3 rounded-md backdrop-blur-sm flex items-center gap-2">
              <Copy className="h-4 w-4" /> Click to copy
            </div>
          </div>
        </div>

        {/* Primary Color Shades */}
        <div className="space-y-6">
          <h4 className="text-lg font-medium">Primary Color Shades</h4>
          <div className="grid grid-cols-2 md:grid-cols-5 lg:grid-cols-10">
            {[50, 100, 200, 300, 400, 500, 600, 700, 800, 900].map((shade) => (
              <div key={shade} className="space-y-2">
                <div
                  className={`h-16 w-full cursor-pointer transition-all duration-200 hover:shadow-md hover:-translate-y-0.5 relative group ${
                    shade === 50 ? "rounded-l-lg" : shade === 900 ? "rounded-r-lg" : ""
                  }`}
                  style={{ backgroundColor: `hsl(var(--primary-${shade}))` }}
                  onClick={() => copyToClipboard(`hsl(var(--primary-${shade}))`, `primary-${shade}`)}
                >
                  {copiedColor === `primary-${shade}` && (
                    <div className="absolute inset-0 flex items-center justify-center bg-black/40 text-white backdrop-blur-sm rounded-lg">
                      <span className="text-xs font-medium flex items-center gap-1">
                        <Check className="h-3 w-3" /> Copied!
                      </span>
                    </div>
                  )}

                  <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity rounded-lg">
                    <div className="bg-black/30 text-white text-xs font-medium py-1 px-2 rounded backdrop-blur-sm flex items-center gap-1">
                      <Copy className="h-3 w-3" /> Copy
                    </div>
                  </div>
                </div>

                <div className="text-center">
                  <div className="text-sm font-medium text-foreground">{shade}</div>
                  <div className="text-xs text-muted-foreground font-mono">primary-{shade}</div>
                </div>
              </div>
            ))}
          </div>

          <div className="p-4 rounded-lg border bg-muted/30">
            <p className="text-sm text-muted-foreground">
              <strong className="text-foreground">Usage:</strong> Use these shades for consistent color variations.
              Lighter shades (50-400) work well for backgrounds and subtle accents, while darker shades (600-900) are
              ideal for text and prominent elements.
            </p>
          </div>
        </div>

        {/* CSS Variables */}
        <div className="space-y-6">
          <h4 className="text-lg font-medium">CSS Variables</h4>
          <div className="grid grid-cols-1 gap-3">
            <CodeField variable="--primary" value="hsl(var(--primary))" />
            <CodeField variable="--primary-foreground" value="hsl(var(--primary-foreground))" />
          </div>
        </div>
      </div>

      {/* Semantic Colors Section - Enhanced */}
      <div className="space-y-8">
        <div>
          <h3 className="text-xl font-semibold mb-2">Semantic Colors</h3>
          <p className="text-muted-foreground text-sm mb-8">
            Bold, vibrant colors for alerts, badges, and status indicators. Designed for maximum impact and clarity.
          </p>
        </div>

        {/* Enhanced Grid of Semantic Colors */}
        <div className="grid grid-cols-1 md:grid-cols-5 gap-6">
          {(["success", "warning", "error", "info", "neutral"] as const).map((semantic) => {
            const colors = semanticColors[semantic][themeKey]
            return (
              <div key={semantic} className="space-y-3">
                <div
                  className="h-24 w-full rounded-lg cursor-pointer transition-all duration-200 hover:shadow-lg hover:-translate-y-1 relative group border-2"
                  style={{
                    backgroundColor: colors.background,
                    borderColor: colors.border,
                  }}
                  onClick={() => copyToClipboard(colors.background, semantic)}
                >
                  {/* Icon/Accent Color Dot */}
                  <div
                    className="absolute top-3 right-3 w-4 h-4 rounded-full"
                    style={{ backgroundColor: colors.foreground }}
                  />

                  {copiedColor === semantic && (
                    <div className="absolute inset-0 flex items-center justify-center bg-black/40 text-white backdrop-blur-sm rounded-lg">
                      <span className="text-sm font-medium flex items-center gap-2">
                        <Check className="h-4 w-4" /> Copied!
                      </span>
                    </div>
                  )}

                  <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity rounded-lg">
                    <div className="bg-black/30 text-white text-sm font-medium py-1.5 px-3 rounded backdrop-blur-sm flex items-center gap-2">
                      <Copy className="h-4 w-4" /> Copy
                    </div>
                  </div>
                </div>

                <div className="text-center">
                  <h4 className="font-semibold capitalize text-base" style={{ color: colors.text }}>
                    {semantic}
                  </h4>
                  <p className="text-xs text-muted-foreground mt-1">
                    {semantic === "success" && "Positive feedback & confirmations"}
                    {semantic === "warning" && "Caution & important notices"}
                    {semantic === "error" && "Errors & critical alerts"}
                    {semantic === "info" && "Information & neutral updates"}
                    {semantic === "neutral" && "Default & secondary states"}
                  </p>
                </div>

                {/* Color Values */}
                <div className="text-center space-y-1">
                  <code className="text-xs text-muted-foreground font-mono block">bg: {colors.background}</code>
                  <code className="text-xs text-muted-foreground font-mono block">border: {colors.border}</code>
                </div>
              </div>
            )
          })}
        </div>

        {/* Enhanced Usage Note */}
        <div className="p-6 rounded-lg border-2 border-dashed border-border bg-muted/20">
          <h4 className="font-semibold mb-3">Usage Guidelines</h4>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-muted-foreground">
            <div>
              <strong className="text-foreground">Background:</strong> Use{" "}
              <code className="text-xs">--semantic-{"{color}"}-bg</code> for card backgrounds and containers
            </div>
            <div>
              <strong className="text-foreground">Border:</strong> Use{" "}
              <code className="text-xs">--semantic-{"{color}"}-border</code> for borders and dividers
            </div>
            <div>
              <strong className="text-foreground">Text:</strong> Use{" "}
              <code className="text-xs">--semantic-{"{color}"}-text</code> for readable text content
            </div>
            <div>
              <strong className="text-foreground">Accent:</strong> Use{" "}
              <code className="text-xs">--semantic-{"{color}"}-fg</code> for icons and highlights
            </div>
          </div>
        </div>
      </div>
    </section>
  )
}
