"use client"

import { ComponentContainer } from "@/components/ui/component-container"
import { Badge } from "@/components/ui/badge"
import { Alert, AlertIcon, AlertContent, AlertTitle, AlertDescription } from "@/components/ui/alert-compound"
import { semanticColors, type SemanticColorName } from "@/utils/semantic-colors"
import { useTheme } from "next-themes"
import { useState, useEffect } from "react"
import {
  CheckCircleIcon,
  ExclamationTriangleIcon,
  XCircleIcon,
  InformationCircleIcon,
  MinusCircleIcon,
} from "@heroicons/react/24/outline"

const semanticIcons = {
  success: CheckCircleIcon,
  warning: ExclamationTriangleIcon,
  error: XCircleIcon,
  info: InformationCircleIcon,
  neutral: MinusCircleIcon,
}

const semanticDescriptions = {
  success: "Operation completed successfully",
  warning: "Please review before proceeding",
  error: "An error occurred during processing",
  info: "Additional information available",
  neutral: "Standard notification message",
}

export default function SemanticColorsSection() {
  const { theme, resolvedTheme } = useTheme()
  const [mounted, setMounted] = useState(false)
  const [currentTheme, setCurrentTheme] = useState<"light" | "dark">("light")

  // Handle mounting to avoid hydration mismatch
  useEffect(() => {
    setMounted(true)
  }, [])

  // Update current theme when theme changes or becomes available
  useEffect(() => {
    if (mounted) {
      // Determine the actual theme being used
      const actualTheme = resolvedTheme || theme

      // If we still don't have a theme, check the document class or default to light
      if (!actualTheme) {
        const isDarkMode = document.documentElement.classList.contains("dark")
        setCurrentTheme(isDarkMode ? "dark" : "light")
      } else {
        setCurrentTheme(actualTheme === "dark" ? "dark" : "light")
      }
    }
  }, [mounted, theme, resolvedTheme])

  // Don't render until mounted to avoid hydration issues
  if (!mounted) {
    return (
      <ComponentContainer
        title="Semantic Colors"
        description="A carefully crafted color palette for alerts, badges, and status indicators. Bold, distinctive colors that embody the Percolate design language."
      >
        <div className="space-y-12">
          <div className="animate-pulse">
            <div className="h-32 bg-muted rounded-lg"></div>
          </div>
        </div>
      </ComponentContainer>
    )
  }

  const isDark = currentTheme === "dark"

  return (
    <ComponentContainer
      title="Semantic Colors"
      description="A carefully crafted color palette for alerts, badges, and status indicators. Bold, distinctive colors that embody the Percolate design language."
    >
      <div className="space-y-12">
        {/* Color Palette Overview */}
        <div>
          <h3 className="text-lg font-semibold mb-6">Final Color Palette</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6">
            {Object.entries(semanticColors).map(([name, color]) => {
              const colorName = name as SemanticColorName
              const themeColors = color[isDark ? "dark" : "light"]

              return (
                <div key={name} className="space-y-3">
                  <div className="text-sm font-medium capitalize text-center">{name}</div>
                  <div className="space-y-2">
                    {/* Background Color */}
                    <div
                      className="h-12 rounded-lg border shadow-sm flex items-center justify-center"
                      style={{
                        backgroundColor: themeColors.background,
                        borderColor: themeColors.border,
                      }}
                    >
                      <span className="text-xs font-medium" style={{ color: themeColors.text }}>
                        Background
                      </span>
                    </div>
                    {/* Foreground Color */}
                    <div
                      className="h-8 rounded-md flex items-center justify-center"
                      style={{ backgroundColor: themeColors.foreground }}
                    >
                      <span className="text-xs font-medium text-white">Foreground</span>
                    </div>
                    {/* Border Color */}
                    <div
                      className="h-6 rounded border-2"
                      style={{ borderColor: themeColors.border, backgroundColor: "transparent" }}
                      title="Border Color"
                    />
                  </div>
                  <div className="text-xs text-muted-foreground text-center font-mono">{themeColors.background}</div>
                </div>
              )
            })}
          </div>
        </div>

        {/* Live Badge Examples */}
        <div>
          <h3 className="text-lg font-semibold mb-6">Semantic Badges in Action</h3>
          <div className="space-y-4">
            <div className="flex flex-wrap gap-4">
              {Object.keys(semanticColors).map((name) => {
                const colorName = name as SemanticColorName
                return (
                  <Badge key={name} variant={colorName} size="md">
                    {name.charAt(0).toUpperCase() + name.slice(1)}
                  </Badge>
                )
              })}
            </div>

            <div className="mt-6">
              <h4 className="text-sm font-medium mb-3">Different Sizes</h4>
              <div className="flex flex-wrap items-center gap-4">
                <Badge variant="success" size="sm">
                  Small Success
                </Badge>
                <Badge variant="warning" size="md">
                  Medium Warning
                </Badge>
                <Badge variant="error" size="lg">
                  Large Error
                </Badge>
              </div>
            </div>
          </div>
        </div>

        {/* Live Alert Examples */}
        <div>
          <h3 className="text-lg font-semibold mb-6">Semantic Alerts in Action</h3>
          <div className="space-y-4">
            {Object.keys(semanticColors).map((name) => {
              const colorName = name as SemanticColorName
              const Icon = semanticIcons[colorName]
              const variant = colorName === "error" ? "destructive" : colorName

              return (
                <Alert key={name} variant={variant as any}>
                  <AlertIcon icon={<Icon className="h-4 w-4" />} />
                  <AlertContent>
                    <AlertTitle>{name.charAt(0).toUpperCase() + name.slice(1)} Alert</AlertTitle>
                    <AlertDescription>
                      {semanticDescriptions[colorName]} This demonstrates the actual colors applied to alert components.
                    </AlertDescription>
                  </AlertContent>
                </Alert>
              )
            })}
          </div>
        </div>

        {/* Real-World Usage Examples */}
        <div>
          <h3 className="text-lg font-semibold mb-6">Real-World Usage</h3>
          <div className="space-y-6">
            <div className="p-6 border rounded-lg bg-card">
              <div className="flex items-center justify-between mb-4">
                <span className="text-sm font-medium">Deployment Status</span>
                <Badge variant="success">Live</Badge>
              </div>
              <div className="text-sm text-muted-foreground mb-4">
                Your application has been successfully deployed and is now accessible to users.
              </div>
              <Alert variant="success">
                <AlertIcon icon={<CheckCircleIcon className="h-4 w-4" />} />
                <AlertContent>
                  <AlertTitle>Deployment Complete</AlertTitle>
                  <AlertDescription>
                    All services are running normally. Your application is live at https://your-app.com
                  </AlertDescription>
                </AlertContent>
              </Alert>
            </div>

            <div className="p-6 border rounded-lg bg-card">
              <div className="flex items-center justify-between mb-4">
                <span className="text-sm font-medium">System Health</span>
                <div className="flex gap-2">
                  <Badge variant="success" size="sm">
                    API
                  </Badge>
                  <Badge variant="warning" size="sm">
                    Database
                  </Badge>
                  <Badge variant="error" size="sm">
                    Cache
                  </Badge>
                </div>
              </div>
              <div className="text-sm text-muted-foreground mb-4">
                Monitor the real-time status of your application services.
              </div>
              <Alert variant="warning">
                <AlertIcon icon={<ExclamationTriangleIcon className="h-4 w-4" />} />
                <AlertContent>
                  <AlertTitle>Performance Warning</AlertTitle>
                  <AlertDescription>
                    Database response times are elevated. Consider scaling your database resources.
                  </AlertDescription>
                </AlertContent>
              </Alert>
            </div>

            <div className="p-6 border rounded-lg bg-card">
              <div className="flex items-center justify-between mb-4">
                <span className="text-sm font-medium">User Notifications</span>
                <div className="flex gap-2">
                  <Badge variant="info" size="sm">
                    3 New
                  </Badge>
                  <Badge variant="neutral" size="sm">
                    12 Read
                  </Badge>
                </div>
              </div>
              <div className="text-sm text-muted-foreground mb-4">
                Recent activity and system notifications for your account.
              </div>
              <Alert variant="info">
                <AlertIcon icon={<InformationCircleIcon className="h-4 w-4" />} />
                <AlertContent>
                  <AlertTitle>New Feature Available</AlertTitle>
                  <AlertDescription>
                    Advanced analytics dashboard is now available. Explore detailed insights about your application
                    performance.
                  </AlertDescription>
                </AlertContent>
              </Alert>
            </div>
          </div>
        </div>

        {/* Color Theory */}
        <div>
          <h3 className="text-lg font-semibold mb-6">Design Philosophy</h3>
          <div className="prose prose-sm max-w-none text-muted-foreground">
            <p className="mb-4">
              Our semantic color palette is designed with <strong>bold, distinctive colors</strong> that embody the
              Percolate design language. Each color is carefully chosen to be{" "}
              <strong>modern, impactful, and memorable</strong> while maintaining excellent accessibility standards.
            </p>
            <ul className="space-y-2">
              <li>
                <strong>Success:</strong> Fresh lime and vibrant forest green convey growth and achievement
              </li>
              <li>
                <strong>Warning:</strong> Golden cream and bold orange create urgency without alarm
              </li>
              <li>
                <strong>Error:</strong> Soft rose and bold crimson communicate issues clearly
              </li>
              <li>
                <strong>Info:</strong> Sky blue and royal blue inspire trust and clarity
              </li>
              <li>
                <strong>Neutral:</strong> Cool gray and indigo provide balanced, professional messaging
              </li>
            </ul>
            <p className="mt-4">
              All colors are optimized for both light and dark themes, ensuring consistent visual hierarchy and
              accessibility across all viewing conditions.
            </p>
          </div>
        </div>
      </div>
    </ComponentContainer>
  )
}
