/**
 * Box Shadow Control Component
 * 
 * Elementor-style box shadow control with:
 * - Pencil icon to open popover
 * - Color picker with opacity
 * - Horizontal offset (X)
 * - Vertical offset (Y)
 * - Blur radius
 * - Spread radius
 * - Inset toggle
 * 
 * @since 1.5.0
 */

import React, { useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { Pencil, X, Eye, EyeOff } from 'lucide-react';
import { ColorPicker } from '../../common/ColorPicker';
import { t } from '@/lib/i18n';

interface BoxShadowValue {
    enabled: boolean;
    color: string;
    opacity: number;
    horizontal: number;
    vertical: number;
    blur: number;
    spread: number;
    inset: boolean;
}

interface BoxShadowControlProps {
    label: string;
    value: string;
    onChange: (value: string) => void;
    disabled?: boolean;
}

// Parse CSS box-shadow value
function parseBoxShadow(value: string): BoxShadowValue {
    if (!value || value === 'none' || value === '') {
        return {
            enabled: false,
            color: '#000000',
            opacity: 20,
            horizontal: 0,
            vertical: 4,
            blur: 6,
            spread: 0,
            inset: false,
        };
    }
    
    let shadow = value.trim();
    const result: BoxShadowValue = {
        enabled: true,
        color: '#000000',
        opacity: 20,
        horizontal: 0,
        vertical: 4,
        blur: 6,
        spread: 0,
        inset: false,
    };
    
    // 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
    const values = shadow.match(/(-?\d+\.?\d*)(px|rem|em|%)?/g) || [];
    if (values.length >= 1 && values[0]) result.horizontal = parseFloat(values[0]) || 0;
    if (values.length >= 2 && values[1]) result.vertical = parseFloat(values[1]) || 0;
    if (values.length >= 3 && values[2]) result.blur = parseFloat(values[2]) || 0;
    if (values.length >= 4 && values[3]) result.spread = parseFloat(values[3]) || 0;
    
    return result;
}

// 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('');
}

// Convert hex to RGB
function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
    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)
    } : null;
}

// Build CSS box-shadow value
function buildBoxShadow(shadow: BoxShadowValue): string {
    if (!shadow.enabled) return 'none';
    
    const rgb = hexToRgb(shadow.color);
    const color = rgb 
        ? `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${shadow.opacity / 100})`
        : shadow.color;
    
    const inset = shadow.inset ? 'inset ' : '';
    return `${inset}${shadow.horizontal}px ${shadow.vertical}px ${shadow.blur}px ${shadow.spread}px ${color}`;
}

export const BoxShadowControl: React.FC<BoxShadowControlProps> = ({
    label,
    value,
    onChange,
    disabled = false,
}) => {
    const [isOpen, setIsOpen] = useState(false);
    const [shadow, setShadow] = useState<BoxShadowValue>(parseBoxShadow(value));
    const popoverRef = useRef<HTMLDivElement>(null);
    const triggerRef = useRef<HTMLButtonElement>(null);
    const [popoverPosition, setPopoverPosition] = useState({ top: 0, left: 0 });
    
    // Calculate popover position when opening
    const updatePopoverPosition = useCallback(() => {
        if (triggerRef.current) {
            const rect = triggerRef.current.getBoundingClientRect();
            const popoverHeight = 550;
            const popoverWidth = 320; // w-80
            const viewportHeight = window.innerHeight;
            const viewportWidth = window.innerWidth;

            // Viewport-based fixed positioning is the most reliable anchor to the trigger.
            // (Avoid page scroll math; WP admin can have nested scrollers/transforms.)
            let top = rect.bottom + 8;
            if (top + popoverHeight > viewportHeight - 16) {
                top = rect.top - popoverHeight - 8;
            }

            const maxTop = Math.max(16, viewportHeight - popoverHeight - 16);
            top = Math.min(Math.max(16, top), maxTop);

            // RTL-friendly: align popover's right edge to trigger's right edge by default.
            let left = rect.right - popoverWidth;
            const maxLeft = Math.max(16, viewportWidth - popoverWidth - 16);
            left = Math.min(Math.max(16, left), maxLeft);

            setPopoverPosition({ top, left });
        }
    }, []);
    
    // Sync with external value changes
    useEffect(() => {
        setShadow(parseBoxShadow(value));
    }, [value]);
    
    // Close popover when clicking outside
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (popoverRef.current && !popoverRef.current.contains(event.target as Node) &&
                triggerRef.current && !triggerRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        };
        
        if (isOpen) {
            document.addEventListener('mousedown', handleClickOutside);
            updatePopoverPosition();
            window.addEventListener('scroll', updatePopoverPosition, true);
            window.addEventListener('resize', updatePopoverPosition);
        }
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
            window.removeEventListener('scroll', updatePopoverPosition, true);
            window.removeEventListener('resize', updatePopoverPosition);
        };
    }, [isOpen, updatePopoverPosition]);
    
    // Update shadow and emit change
    const updateShadow = (updates: Partial<BoxShadowValue>) => {
        const newShadow = { ...shadow, ...updates };
        // UX: if user disabled the shadow via preset "ללא", any subsequent manual change
        // (sliders/color/presets) should automatically re-enable the shadow.
        if (
            shadow.enabled === false &&
            updates.enabled === undefined &&
            Object.keys(updates).some((k) => k !== 'enabled')
        ) {
            newShadow.enabled = true;
        }
        setShadow(newShadow);
        onChange(buildBoxShadow(newShadow));
    };

    // IMPORTANT: admin Tailwind utilities are scoped with `important: '.boostbot-admin'`
    // so portals must render inside the `.boostbot-admin` subtree (not directly under <body>)
    // otherwise utilities like `p-4`, `rounded-lg`, etc. won't apply.
    const portalContainer =
        (document.querySelector('.boostbot-admin') as HTMLElement | null) ||
        (document.getElementById('boostbot-admin-root') as HTMLElement | null) ||
        document.body;
    
    return (
        <div className="box-shadow-control relative" dir="rtl">
            <div className="flex items-center justify-between mb-1">
                <label className="text-xs text-gray-600 font-medium">{label}</label>
            </div>
            
            {/* Control Row */}
            <div className="flex items-center gap-2">
                {/* Toggle Button */}
                <button
                    type="button"
                    onClick={() => updateShadow({ enabled: !shadow.enabled })}
                    disabled={disabled}
                    className={`p-2 rounded-lg border transition-colors ${
                        shadow.enabled 
                            ? 'bg-primary-50 border-primary-300 text-primary-600' 
                            : 'bg-gray-50 border-gray-200 text-gray-400'
                    }`}
                    title={shadow.enabled ? t('Remove shadow') : t('Add shadow')}
                >
                    {shadow.enabled ? <Eye size={14} /> : <EyeOff size={14} />}
                </button>
                
                {/* Preview & Edit Button */}
                <button
                    ref={triggerRef}
                    type="button"
                    onClick={() => {
                        if (!shadow.enabled) {
                            updateShadow({ enabled: true });
                        }
                        setIsOpen(!isOpen);
                    }}
                    disabled={disabled}
                    className={`flex-1 flex items-center justify-between px-3 py-2 rounded-lg border transition-colors ${
                        shadow.enabled 
                            ? 'bg-white border-gray-200 hover:border-primary-300' 
                            : 'bg-gray-50 border-gray-200 hover:border-gray-300'
                    }`}
                >
                    <div 
                        className="w-8 h-8 bg-primary-500 rounded"
                        style={{ 
                            boxShadow: shadow.enabled ? buildBoxShadow(shadow) : 'none',
                        }}
                    />
                    <span className="text-sm text-gray-500 mx-2">
                        {shadow.enabled ? t('Shadow active') : t('No shadow')}
                    </span>
                    <Pencil size={14} className="text-gray-400" />
                </button>
            </div>
            
            {/* Popover - using very high z-index to be above WordPress admin elements */}
            {isOpen && createPortal(
                <div 
                    ref={popoverRef}
                    className="w-80 bg-white rounded-lg shadow-xl border border-gray-200 p-4 animate-fade-in"
                    dir="rtl"
                    style={{
                        position: 'fixed',
                        top: popoverPosition.top,
                        left: popoverPosition.left,
                        zIndex: 999999, // Very high to be above WordPress admin modals
                        backgroundColor: '#FFFFFF',
                        opacity: 1,
                    }}
                >
                    {/* Header */}
                    <div className="flex items-center justify-between mb-4">
                        <h4 className="text-sm font-semibold text-gray-900">{t('Shadow settings')}</h4>
                        <button
                            type="button"
                            onClick={() => setIsOpen(false)}
                            className="p-1 text-gray-400 hover:text-gray-600 rounded"
                        >
                            <X size={16} />
                        </button>
                    </div>
                    
                    {/* Preview */}
                    <div className="mb-4 p-6 bg-gray-100 rounded-lg flex items-center justify-center">
                        <div 
                            className="w-16 h-16 bg-primary-500 rounded-lg"
                            style={{ boxShadow: buildBoxShadow(shadow) }}
                        />
                    </div>
                    
                    {/* Color & Opacity */}
                    <div className="mb-4">
                        <label className="text-xs text-gray-500 mb-1.5 block">{t('Shadow color')}</label>
                        <div className="space-y-3">
                            <ColorPicker
                                value={shadow.color}
                                onChange={(color) => updateShadow({ color })}
                                disabled={disabled}
                            />
                            <div className="w-24">
                                <label className="text-xs text-gray-500 mb-1 block">{t('Opacity')}</label>
                                <input
                                    type="number"
                                    min={0}
                                    max={100}
                                    value={shadow.opacity}
                                    onChange={(e) => updateShadow({ opacity: parseInt(e.target.value) || 0 })}
                                    disabled={disabled}
                                    className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded-md"
                                />
                            </div>
                        </div>
                    </div>
                    
                    {/* Horizontal Offset */}
                    <div className="mb-3">
                        <div className="flex items-center justify-between mb-1">
                            <label className="text-xs text-gray-500">{t('Horizontal offset (X)')}</label>
                            <span className="text-xs text-gray-400">{shadow.horizontal}px</span>
                        </div>
                        <input
                            type="range"
                            min={-30}
                            max={30}
                            step={1}
                            value={shadow.horizontal}
                            onChange={(e) => updateShadow({ horizontal: parseInt(e.target.value) })}
                            disabled={disabled}
                            className="w-full h-1.5 bg-gray-200 rounded-full appearance-none cursor-pointer"
                        />
                    </div>
                    
                    {/* Vertical Offset */}
                    <div className="mb-3">
                        <div className="flex items-center justify-between mb-1">
                            <label className="text-xs text-gray-500">{t('Vertical offset (Y)')}</label>
                            <span className="text-xs text-gray-400">{shadow.vertical}px</span>
                        </div>
                        <input
                            type="range"
                            min={-30}
                            max={30}
                            step={1}
                            value={shadow.vertical}
                            onChange={(e) => updateShadow({ vertical: parseInt(e.target.value) })}
                            disabled={disabled}
                            className="w-full h-1.5 bg-gray-200 rounded-full appearance-none cursor-pointer"
                        />
                    </div>
                    
                    {/* Blur */}
                    <div className="mb-3">
                        <div className="flex items-center justify-between mb-1">
                            <label className="text-xs text-gray-500">{t('Blur')}</label>
                            <span className="text-xs text-gray-400">{shadow.blur}px</span>
                        </div>
                        <input
                            type="range"
                            min={0}
                            max={50}
                            step={1}
                            value={shadow.blur}
                            onChange={(e) => updateShadow({ blur: parseInt(e.target.value) })}
                            disabled={disabled}
                            className="w-full h-1.5 bg-gray-200 rounded-full appearance-none cursor-pointer"
                        />
                    </div>
                    
                    {/* Spread */}
                    <div className="mb-3">
                        <div className="flex items-center justify-between mb-1">
                            <label className="text-xs text-gray-500">{t('Spread')}</label>
                            <span className="text-xs text-gray-400">{shadow.spread}px</span>
                        </div>
                        <input
                            type="range"
                            min={-20}
                            max={30}
                            step={1}
                            value={shadow.spread}
                            onChange={(e) => updateShadow({ spread: parseInt(e.target.value) })}
                            disabled={disabled}
                            className="w-full h-1.5 bg-gray-200 rounded-full appearance-none cursor-pointer"
                        />
                    </div>
                    
                    {/* Inset Toggle */}
                    <div className="mb-4 flex items-center gap-2">
                        <input
                            type="checkbox"
                            id="inset-toggle"
                            checked={shadow.inset}
                            onChange={(e) => updateShadow({ inset: e.target.checked })}
                            disabled={disabled}
                            className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                        />
                        <label htmlFor="inset-toggle" className="text-sm text-gray-600">{t('Inner shadow (Inset)')}</label>
                    </div>
                    
                    {/* Quick Presets */}
                    <div className="border-t border-gray-200 pt-3">
                        <label className="text-xs text-gray-500 mb-2 block">{t('Quick presets')}</label>
                        <div className="grid grid-cols-3 gap-2">
                            <button
                                type="button"
                                onClick={() => updateShadow({ horizontal: 0, vertical: 1, blur: 2, spread: 0, opacity: 10 })}
                                className="py-1.5 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors"
                            >
                                {t('Subtle')}
                            </button>
                            <button
                                type="button"
                                onClick={() => updateShadow({ horizontal: 0, vertical: 4, blur: 6, spread: -1, opacity: 15 })}
                                className="py-1.5 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors"
                            >
                                {t('Medium')}
                            </button>
                            <button
                                type="button"
                                onClick={() => updateShadow({ horizontal: 0, vertical: 10, blur: 15, spread: -3, opacity: 20 })}
                                className="py-1.5 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors"
                            >
                                {t('Strong')}
                            </button>
                            <button
                                type="button"
                                onClick={() => updateShadow({ horizontal: 0, vertical: 20, blur: 25, spread: -5, opacity: 25 })}
                                className="py-1.5 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors"
                            >
                                {t('Dramatic')}
                            </button>
                            <button
                                type="button"
                                onClick={() => updateShadow({ horizontal: 0, vertical: 2, blur: 4, spread: 0, opacity: 30, inset: true })}
                                className="py-1.5 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors"
                            >
                                {t('Inner')}
                            </button>
                            <button
                                type="button"
                                onClick={() => updateShadow({ enabled: false })}
                                className="py-1.5 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors"
                            >
                                {t('None')}
                            </button>
                        </div>
                    </div>
                </div>,
                portalContainer
            )}
        </div>
    );
};

export default BoxShadowControl;

