/**
 * Shadow Editor Component
 * A detailed editor for CSS box-shadow with all parameters
 */

import { NumberWithUnitInput } from './NumberWithUnitInput'
import { ColorPicker } from './ColorPicker'
import { useState, useEffect } from 'react'
import { t } from '@/lib/i18n'

interface ShadowValue {
    offsetX: string
    offsetY: string
    blur: string
    spread: string
    color: string
    opacity: number
    inset: boolean
}

interface ShadowEditorProps {
    value: string
    onChange: (value: string) => void
    label?: string
    disabled?: boolean
    className?: string
    showInset?: boolean
}

const DEFAULT_SHADOW: ShadowValue = {
    offsetX: '0px',
    offsetY: '4px',
    blur: '6px',
    spread: '0px',
    color: '#000000',
    opacity: 20,
    inset: false,
}

/**
 * Parse CSS box-shadow string into ShadowValue object
 * Supports: "0px 4px 6px 0px rgba(0,0,0,0.2)" or "inset 0px 4px 6px 0px #000"
 */
function parseShadow(input: string): ShadowValue {
    if (!input || input === 'none') {
        return DEFAULT_SHADOW
    }

    const result = { ...DEFAULT_SHADOW }
    let shadow = input.trim()

    // Check for inset
    if (shadow.startsWith('inset')) {
        result.inset = true
        shadow = shadow.replace('inset', '').trim()
    }

    // Parse rgba/rgb color
    const rgbaMatch = shadow.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/)
    if (rgbaMatch) {
        const r = parseInt(rgbaMatch[1])
        const g = parseInt(rgbaMatch[2])
        const b = parseInt(rgbaMatch[3])
        const a = parseFloat(rgbaMatch[4] || '1')
        result.color = rgbToHex(r, g, b)
        result.opacity = Math.round(a * 100)
        shadow = shadow.replace(rgbaMatch[0], '').trim()
    } else {
        // Parse hex color
        const hexMatch = shadow.match(/#([0-9a-fA-F]{3,8})\b/)
        if (hexMatch) {
            result.color = hexMatch[0]
            result.opacity = 100
            shadow = shadow.replace(hexMatch[0], '').trim()
        }
    }

    // Parse offset values (remaining should be like "0px 4px 6px 0px")
    const values = shadow.match(/(-?\d+\.?\d*)(px|rem|em|%)?/g) || []
    const v0 = values[0] || '0px'
    const v1 = values[1] || '0px'
    const v2 = values[2] || '0px'
    const v3 = values[3] || '0px'
    if (values.length >= 1) result.offsetX = v0.includes('px') || v0.includes('rem') ? v0 : `${v0}px`
    if (values.length >= 2) result.offsetY = v1.includes('px') || v1.includes('rem') ? v1 : `${v1}px`
    if (values.length >= 3) result.blur = v2.includes('px') || v2.includes('rem') ? v2 : `${v2}px`
    if (values.length >= 4) result.spread = v3.includes('px') || v3.includes('rem') ? v3 : `${v3}px`

    return result
}

/**
 * Convert ShadowValue to CSS box-shadow string
 */
function stringifyShadow(shadow: ShadowValue): string {
    const { offsetX, offsetY, blur, spread, color, opacity, inset } = shadow
    
    // Convert hex to rgba with opacity
    const rgba = hexToRgba(color, opacity / 100)
    
    const parts = [
        inset ? 'inset' : '',
        offsetX,
        offsetY,
        blur,
        spread,
        rgba,
    ].filter(Boolean)
    
    return parts.join(' ')
}

/**
 * Convert hex color to rgba string
 */
function hexToRgba(hex: string, alpha: number): string {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    if (result) {
        const r = parseInt(result[1], 16)
        const g = parseInt(result[2], 16)
        const b = parseInt(result[3], 16)
        return `rgba(${r}, ${g}, ${b}, ${alpha})`
    }
    
    // Short hex
    const shortResult = /^#?([a-f\d])([a-f\d])([a-f\d])$/i.exec(hex)
    if (shortResult) {
        const r = parseInt(shortResult[1] + shortResult[1], 16)
        const g = parseInt(shortResult[2] + shortResult[2], 16)
        const b = parseInt(shortResult[3] + shortResult[3], 16)
        return `rgba(${r}, ${g}, ${b}, ${alpha})`
    }
    
    return `rgba(0, 0, 0, ${alpha})`
}

/**
 * Convert RGB to hex
 */
function rgbToHex(r: number, g: number, b: number): string {
    return '#' + [r, g, b].map(x => {
        const hex = x.toString(16)
        return hex.length === 1 ? '0' + hex : hex
    }).join('')
}

export function ShadowEditor({
    value,
    onChange,
    label,
    disabled = false,
    className = '',
    showInset = true,
}: ShadowEditorProps) {
    const [shadow, setShadow] = useState<ShadowValue>(() => parseShadow(value))

    useEffect(() => {
        setShadow(parseShadow(value))
    }, [value])

    const handleChange = (updates: Partial<ShadowValue>) => {
        const newShadow = { ...shadow, ...updates }
        setShadow(newShadow)
        onChange(stringifyShadow(newShadow))
    }

    const handleRemoveShadow = () => {
        onChange('none')
    }

    const isNone = value === 'none' || !value

    return (
        <div className={`space-y-3 ${className}`}>
            {label && (
                <div className="flex items-center justify-between">
                    <label className="text-sm font-medium text-gray-700">
                        {label}
                    </label>
                    {!isNone && (
                        <button
                            type="button"
                            onClick={handleRemoveShadow}
                            disabled={disabled}
                            className="text-xs text-gray-500 hover:text-red-500 transition-colors"
                        >
                            {t('Remove Shadow')}
                        </button>
                    )}
                </div>
            )}

            {/* Preview */}
            <div className="flex justify-center py-4">
                <div
                    className="w-24 h-16 bg-white rounded-lg border border-gray-200 transition-shadow duration-200"
                    style={{ boxShadow: isNone ? 'none' : stringifyShadow(shadow) }}
                />
            </div>

            {/* Controls */}
            <div className="grid grid-cols-2 gap-3">
                {/* X Offset */}
                <NumberWithUnitInput
                    value={shadow.offsetX}
                    onChange={(v) => handleChange({ offsetX: v })}
                    label={t('Horizontal Offset')}
                    disabled={disabled}
                />

                {/* Y Offset */}
                <NumberWithUnitInput
                    value={shadow.offsetY}
                    onChange={(v) => handleChange({ offsetY: v })}
                    label={t('Vertical Offset')}
                    disabled={disabled}
                />

                {/* Blur */}
                <NumberWithUnitInput
                    value={shadow.blur}
                    onChange={(v) => handleChange({ blur: v })}
                    label={t('Blur')}
                    disabled={disabled}
                />

                {/* Spread */}
                <NumberWithUnitInput
                    value={shadow.spread}
                    onChange={(v) => handleChange({ spread: v })}
                    label={t('Spread')}
                    disabled={disabled}
                />
            </div>

            {/* Color and opacity */}
            <div className="flex items-end gap-3">
                <div className="flex-1">
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                        {t('Color')}
                    </label>
                    <ColorPicker
                        value={shadow.color}
                        onChange={(v) => handleChange({ color: v })}
                        disabled={disabled}
                    />
                </div>

                <div className="w-24">
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                        {t('Opacity')}
                    </label>
                    <div className="flex items-center gap-1">
                        <input
                            type="range"
                            min={0}
                            max={100}
                            value={shadow.opacity}
                            onChange={(e) => handleChange({ opacity: parseInt(e.target.value) })}
                            disabled={disabled}
                            className="flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
                        />
                        <span className="text-xs text-gray-500 w-8 text-left">
                            {shadow.opacity}%
                        </span>
                    </div>
                </div>
            </div>

            {/* Inset toggle */}
            {showInset && (
                <label className="flex items-center gap-2 cursor-pointer">
                    <input
                        type="checkbox"
                        checked={shadow.inset}
                        onChange={(e) => handleChange({ inset: e.target.checked })}
                        disabled={disabled}
                        className="w-4 h-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                    />
                    <span className="text-sm text-gray-700">{t('Inner Shadow (inset)')}</span>
                </label>
            )}
        </div>
    )
}

export default ShadowEditor

