"use client"

import React, { useState, useCallback, useRef, useEffect } from "react"
import { motion } from "framer-motion"
import { Card, CardContent } from "../ui/card"
import { Button } from "../ui/button"
import { Input } from "../ui/input"
import { Label } from "../ui/label"
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs"
import { cn } from "../../lib/utils"
import { Lock, Sparkles, Palette, Copy, Check, RotateCcw } from "lucide-react"
import { useSubscription } from "../../hooks/use-subscription"

interface ColorPickerProps {
  value?: string
  onChange?: (color: string) => void
  disabled?: boolean
  showPresets?: boolean
  showAlpha?: boolean
  showInput?: boolean
  showCopy?: boolean
  presetColors?: string[]
  className?: string
  size?: "sm" | "default" | "lg"
}

interface HSV {
  h: number
  s: number
  v: number
  a: number
}

interface RGB {
  r: number
  g: number
  b: number
  a: number
}

const ColorPickerInternal: React.FC<ColorPickerProps> = ({
  value = "#3b82f6",
  onChange,
  disabled = false,
  showPresets = true,
  showAlpha = true,
  showInput = true,
  showCopy = true,
  presetColors = [
    "#ef4444", "#f97316", "#f59e0b", "#eab308", "#84cc16", "#22c55e",
    "#10b981", "#14b8a6", "#06b6d4", "#0ea5e9", "#3b82f6", "#6366f1",
    "#8b5cf6", "#a855f7", "#d946ef", "#ec4899", "#f43f5e", "#000000",
    "#404040", "#737373", "#a3a3a3", "#d4d4d4", "#f5f5f5", "#ffffff"
  ],
  className,
  size = "default"
}) => {
  const [currentColor, setCurrentColor] = useState(value)
  const [hsv, setHsv] = useState<HSV>({ h: 0, s: 100, v: 100, a: 1 })
  const [inputValue, setInputValue] = useState(value)
  const [copied, setCopied] = useState(false)
  const [isDragging, setIsDragging] = useState<'hue' | 'saturation' | 'alpha' | null>(null)
  
  const saturationRef = useRef<HTMLDivElement>(null)
  const hueRef = useRef<HTMLDivElement>(null)
  const alphaRef = useRef<HTMLDivElement>(null)

  const sizeClasses = {
    sm: "w-8 h-8",
    default: "w-10 h-10", 
    lg: "w-12 h-12"
  }

  // Convert color utilities
  const hexToRgb = (hex: string): RGB => {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16),
      a: 1
    } : { r: 0, g: 0, b: 0, a: 1 }
  }

  const rgbToHex = (r: number, g: number, b: number): string => {
    return "#" + [r, g, b].map(x => {
      const hex = Math.round(x).toString(16)
      return hex.length === 1 ? "0" + hex : hex
    }).join("")
  }

  const rgbToHsv = (rgb: RGB): HSV => {
    const r = rgb.r / 255
    const g = rgb.g / 255  
    const b = rgb.b / 255
    
    const max = Math.max(r, g, b)
    const min = Math.min(r, g, b)
    const diff = max - min
    
    let h = 0
    if (diff !== 0) {
      if (max === r) h = ((g - b) / diff) % 6
      else if (max === g) h = (b - r) / diff + 2
      else h = (r - g) / diff + 4
    }
    h = Math.round(h * 60)
    if (h < 0) h += 360
    
    const s = max === 0 ? 0 : (diff / max) * 100
    const v = max * 100
    
    return { h, s, v, a: rgb.a }
  }

  const hsvToRgb = (hsv: HSV): RGB => {
    const h = hsv.h / 60
    const s = hsv.s / 100
    const v = hsv.v / 100
    
    const c = v * s
    const x = c * (1 - Math.abs((h % 2) - 1))
    const m = v - c
    
    let r = 0, g = 0, b = 0
    
    if (h >= 0 && h < 1) [r, g, b] = [c, x, 0]
    else if (h >= 1 && h < 2) [r, g, b] = [x, c, 0]
    else if (h >= 2 && h < 3) [r, g, b] = [0, c, x]
    else if (h >= 3 && h < 4) [r, g, b] = [0, x, c]
    else if (h >= 4 && h < 5) [r, g, b] = [x, 0, c]
    else if (h >= 5 && h < 6) [r, g, b] = [c, 0, x]
    
    return {
      r: Math.round((r + m) * 255),
      g: Math.round((g + m) * 255),
      b: Math.round((b + m) * 255),
      a: hsv.a
    }
  }

  const updateColor = useCallback((newHsv: HSV) => {
    setHsv(newHsv)
    const rgb = hsvToRgb(newHsv)
    const hex = rgbToHex(rgb.r, rgb.g, rgb.b)
    setCurrentColor(hex)
    setInputValue(hex)
    onChange?.(hex)
  }, [onChange])

  useEffect(() => {
    const rgb = hexToRgb(currentColor)
    const newHsv = rgbToHsv(rgb)
    setHsv(newHsv)
  }, [currentColor])

  const handleSaturationChange = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    if (!saturationRef.current) return
    
    const rect = saturationRef.current.getBoundingClientRect()
    const x = Math.max(0, Math.min(rect.width, e.clientX - rect.left))
    const y = Math.max(0, Math.min(rect.height, e.clientY - rect.top))
    
    const s = (x / rect.width) * 100
    const v = 100 - (y / rect.height) * 100
    
    updateColor({ ...hsv, s, v })
  }, [hsv, updateColor])

  const handleHueChange = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    if (!hueRef.current) return
    
    const rect = hueRef.current.getBoundingClientRect()
    const x = Math.max(0, Math.min(rect.width, e.clientX - rect.left))
    const h = (x / rect.width) * 360
    
    updateColor({ ...hsv, h })
  }, [hsv, updateColor])

  const handleAlphaChange = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    if (!alphaRef.current) return
    
    const rect = alphaRef.current.getBoundingClientRect()
    const x = Math.max(0, Math.min(rect.width, e.clientX - rect.left))
    const a = x / rect.width
    
    updateColor({ ...hsv, a })
  }, [hsv, updateColor])

  const handleInputChange = (value: string) => {
    setInputValue(value)
    if (/^#[0-9A-F]{6}$/i.test(value)) {
      setCurrentColor(value)
      onChange?.(value)
    }
  }

  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(currentColor)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch (err) {
      console.error("Failed to copy color:", err)
    }
  }

  const handlePresetClick = (color: string) => {
    setCurrentColor(color)
    setInputValue(color)
    onChange?.(color)
  }

  const resetColor = () => {
    setCurrentColor(value)
    setInputValue(value)
    onChange?.(value)
  }

  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          className={cn(
            sizeClasses[size],
            "p-1 border-2 border-muted-foreground/20 hover:border-muted-foreground/40",
            disabled && "opacity-50 cursor-not-allowed",
            className
          )}
          disabled={disabled}
        >
          <div
            className="w-full h-full rounded-sm"
            style={{ backgroundColor: currentColor }}
          />
        </Button>
      </PopoverTrigger>
      
      <PopoverContent className="w-80 p-4" side="bottom" align="start">
        <div className="space-y-4">
          {/* Saturation/Brightness Picker */}
          <div className="space-y-2">
            <Label>Color</Label>
            <div
              ref={saturationRef}
              className="relative w-full h-48 rounded-lg cursor-crosshair overflow-hidden"
              style={{
                background: `linear-gradient(to right, white, hsl(${hsv.h}, 100%, 50%)),
                           linear-gradient(to top, black, transparent)`
              }}
              onMouseDown={(e) => {
                setIsDragging('saturation')
                handleSaturationChange(e)
              }}
              onMouseMove={(e) => isDragging === 'saturation' && handleSaturationChange(e)}
            >
              <div
                className="absolute w-4 h-4 border-2 border-white rounded-full shadow-lg transform -translate-x-2 -translate-y-2 pointer-events-none"
                style={{
                  left: `${hsv.s}%`,
                  top: `${100 - hsv.v}%`
                }}
              />
            </div>
          </div>

          {/* Hue Slider */}
          <div className="space-y-2">
            <Label>Hue</Label>
            <div
              ref={hueRef}
              className="relative w-full h-4 rounded-lg cursor-pointer"
              style={{
                background: "linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"
              }}
              onMouseDown={(e) => {
                setIsDragging('hue')
                handleHueChange(e)
              }}
              onMouseMove={(e) => isDragging === 'hue' && handleHueChange(e)}
            >
              <div
                className="absolute w-4 h-4 bg-white border-2 border-gray-300 rounded-full shadow-lg transform -translate-x-2 -translate-y-0 pointer-events-none"
                style={{ left: `${(hsv.h / 360) * 100}%` }}
              />
            </div>
          </div>

          {/* Alpha Slider */}
          {showAlpha && (
            <div className="space-y-2">
              <Label>Opacity</Label>
              <div
                ref={alphaRef}
                className="relative w-full h-4 rounded-lg cursor-pointer"
                style={{
                  background: `linear-gradient(to right, transparent, ${currentColor}),
                             repeating-linear-gradient(45deg, #ccc 0, #ccc 2px, #fff 2px, #fff 4px)`
                }}
                onMouseDown={(e) => {
                  setIsDragging('alpha')
                  handleAlphaChange(e)
                }}
                onMouseMove={(e) => isDragging === 'alpha' && handleAlphaChange(e)}
              >
                <div
                  className="absolute w-4 h-4 bg-white border-2 border-gray-300 rounded-full shadow-lg transform -translate-x-2 -translate-y-0 pointer-events-none"
                  style={{ left: `${hsv.a * 100}%` }}
                />
              </div>
            </div>
          )}

          {/* Color Input and Copy */}
          {showInput && (
            <div className="flex gap-2">
              <div className="flex-1">
                <Label htmlFor="color-input">Hex</Label>
                <Input
                  id="color-input"
                  value={inputValue}
                  onChange={(e) => handleInputChange(e.target.value)}
                  placeholder="#000000"
                  className="font-mono"
                />
              </div>
              
              {showCopy && (
                <div className="flex flex-col gap-2">
                  <Label>&nbsp;</Label>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={copyToClipboard}
                    className="px-3"
                  >
                    {copied ? (
                      <Check className="h-4 w-4 text-green-500" />
                    ) : (
                      <Copy className="h-4 w-4" />
                    )}
                  </Button>
                </div>
              )}
              
              <div className="flex flex-col gap-2">
                <Label>&nbsp;</Label>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={resetColor}
                  className="px-3"
                >
                  <RotateCcw className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}

          {/* Preset Colors */}
          {showPresets && (
            <div className="space-y-2">
              <Label>Presets</Label>
              <div className="grid grid-cols-8 gap-2">
                {presetColors.map((color, index) => (
                  <motion.button
                    key={color}
                    className="w-8 h-8 rounded-md border-2 border-muted-foreground/20 hover:border-muted-foreground/40 transition-colors"
                    style={{ backgroundColor: color }}
                    onClick={() => handlePresetClick(color)}
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.95 }}
                    initial={{ opacity: 0, scale: 0 }}
                    animate={{ opacity: 1, scale: 1 }}
                    transition={{ delay: index * 0.02 }}
                  />
                ))}
              </div>
            </div>
          )}
        </div>
      </PopoverContent>
    </Popover>
  )

  // Mouse up handler for the entire document
  useEffect(() => {
    const handleMouseUp = () => setIsDragging(null)
    document.addEventListener('mouseup', handleMouseUp)
    return () => document.removeEventListener('mouseup', handleMouseUp)
  }, [])
}

export const ColorPicker: React.FC<ColorPickerProps> = ({ className, ...props }) => {
  // Check if we're in docs mode or have pro access
  const { hasProAccess, isLoading } = useSubscription()
  
  // In docs mode, always show the component
  
  // If not in docs mode and no pro access, show upgrade prompt
  if (!isLoading && !hasProAccess) {
    return (
      <Card className={cn("w-fit", className)}>
        <CardContent className="py-6 text-center">
          <div className="space-y-4">
            <div className="rounded-full bg-purple-100 dark:bg-purple-900/30 p-3 w-fit mx-auto">
              <Lock className="h-6 w-6 text-purple-600 dark:text-purple-400" />
            </div>
            <div>
              <h3 className="font-semibold text-sm mb-2">Pro Feature</h3>
              <p className="text-muted-foreground text-xs mb-4">
                Color Picker is available exclusively to MoonUI Pro subscribers.
              </p>
              <a href="/pricing">
                <Button size="sm">
                  <Sparkles className="mr-2 h-4 w-4" />
                  Upgrade to Pro
                </Button>
              </a>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return <ColorPickerInternal className={className} {...props} />
}

export type { ColorPickerProps }