import { useState, useRef, useEffect, useCallback } from 'react'
import { t } from '@/lib/i18n'
import { createPortal } from 'react-dom'
import {
    User, Users, UserCheck,
    Phone, PhoneCall, PhoneIncoming,
    Video, Camera, Monitor,
    MapPin, Home, Building,
    Calendar, Clock, Coffee,
    MessageCircle, Mail, Send,
    Star, Heart, Zap,
    Briefcase, ShoppingBag, Gift,
    ChevronDown,
    type LucideIcon,
} from 'lucide-react'
import type { MeetingTypeIconName } from '@/types/widget'

// Icon mapping - Lucide React icons (SVG, fully customizable colors)
const ICON_MAP: Record<MeetingTypeIconName, LucideIcon> = {
    'user': User,
    'users': Users,
    'user-check': UserCheck,
    'phone': Phone,
    'phone-call': PhoneCall,
    'phone-incoming': PhoneIncoming,
    'video': Video,
    'camera': Camera,
    'monitor': Monitor,
    'map-pin': MapPin,
    'home': Home,
    'building': Building,
    'calendar': Calendar,
    'clock': Clock,
    'coffee': Coffee,
    'message-circle': MessageCircle,
    'mail': Mail,
    'send': Send,
    'star': Star,
    'heart': Heart,
    'zap': Zap,
    'briefcase': Briefcase,
    'shopping-bag': ShoppingBag,
    'gift': Gift,
}

// All available icons as flat list
const ALL_ICONS: MeetingTypeIconName[] = [
    'user', 'users', 'user-check',
    'phone', 'phone-call', 'phone-incoming',
    'video', 'camera', 'monitor',
    'map-pin', 'home', 'building',
    'calendar', 'clock', 'coffee',
    'message-circle', 'mail', 'send',
    'star', 'heart', 'zap',
    'briefcase', 'shopping-bag', 'gift',
]

interface IconPickerProps {
    value: MeetingTypeIconName
    onChange: (icon: MeetingTypeIconName) => void
    disabled?: boolean
}

export function IconPicker({ value, onChange, disabled = false }: IconPickerProps) {
    const [isOpen, setIsOpen] = useState(false)
    const [position, setPosition] = useState({ top: 0, left: 0 })
    const buttonRef = useRef<HTMLButtonElement>(null)
    const popoverRef = useRef<HTMLDivElement>(null)

    const SelectedIcon = ICON_MAP[value] || User

    // Calculate position
    const updatePosition = useCallback(() => {
        if (!buttonRef.current) return
        
        const rect = buttonRef.current.getBoundingClientRect()
        const popoverWidth = 300
        const popoverHeight = 350
        
        // Calculate best position
        let top = rect.bottom + 4
        let left = rect.left
        
        // Check if popover goes off right edge
        if (left + popoverWidth > window.innerWidth) {
            left = rect.right - popoverWidth
        }
        
        // Check if popover goes off bottom
        if (top + popoverHeight > window.innerHeight) {
            top = rect.top - popoverHeight - 4
        }
        
        // Ensure minimum left position
        if (left < 8) left = 8
        
        setPosition({ top, left })
    }, [])

    // Update position when opening
    useEffect(() => {
        if (isOpen) {
            updatePosition()
            window.addEventListener('scroll', updatePosition, true)
            window.addEventListener('resize', updatePosition)
        }
        return () => {
            window.removeEventListener('scroll', updatePosition, true)
            window.removeEventListener('resize', updatePosition)
        }
    }, [isOpen, updatePosition])

    // Close on click outside
    useEffect(() => {
        if (!isOpen) return

        const handleClickOutside = (e: MouseEvent) => {
            const target = e.target as Node
            if (buttonRef.current?.contains(target)) return
            if (popoverRef.current?.contains(target)) return
            setIsOpen(false)
        }

        // Add listener after a short delay
        const timeoutId = setTimeout(() => {
            document.addEventListener('mousedown', handleClickOutside)
        }, 50)

        return () => {
            clearTimeout(timeoutId)
            document.removeEventListener('mousedown', handleClickOutside)
        }
    }, [isOpen])

    const handleSelect = (icon: MeetingTypeIconName) => {
        onChange(icon)
        setIsOpen(false)
    }

    const handleButtonClick = (e: React.MouseEvent) => {
        e.preventDefault()
        e.stopPropagation()
        if (!disabled) {
            setIsOpen(prev => !prev)
        }
    }

    return (
        <>
            <button
                ref={buttonRef}
                type="button"
                onClick={handleButtonClick}
                disabled={disabled}
                className={`
                    flex items-center justify-center gap-2 px-3 py-2 
                    border border-gray-300 rounded-lg bg-white
                    hover:border-primary-400 hover:bg-gray-50
                    focus:ring-2 focus:ring-primary-500 focus:border-primary-500
                    transition-colors
                    ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
                `}
            >
                <SelectedIcon className="w-5 h-5 text-primary-600" />
                <ChevronDown className={`w-4 h-4 text-gray-400 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
            </button>

            {isOpen && createPortal(
                <div
                    ref={popoverRef}
                    style={{
                        position: 'fixed',
                        top: position.top,
                        left: position.left,
                        width: '260px',
                        maxHeight: '320px',
                        overflowY: 'auto',
                        zIndex: 999999, // High z-index to be above WordPress admin modals
                        backgroundColor: '#ffffff',
                        border: '1px solid #e5e7eb',
                        borderRadius: '12px',
                        boxShadow: '0 10px 40px rgba(0, 0, 0, 0.15)',
                        padding: '12px',
                    }}
                >
                    <div style={{ 
                        fontSize: '14px', 
                        fontWeight: 500, 
                        color: '#374151', 
                        marginBottom: '12px',
                        paddingBottom: '8px',
                        borderBottom: '1px solid #e5e7eb',
                    }}                    >
                        {t('Choose Icon')}
                    </div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
                        {ALL_ICONS.map((iconName) => {
                            const Icon = ICON_MAP[iconName]
                            const isSelected = value === iconName
                            return (
                                <button
                                    key={iconName}
                                    type="button"
                                    onClick={(e) => {
                                        e.preventDefault()
                                        e.stopPropagation()
                                        handleSelect(iconName)
                                    }}
                                    style={{
                                        padding: '10px',
                                        borderRadius: '8px',
                                        border: 'none',
                                        cursor: 'pointer',
                                        backgroundColor: isSelected ? '#dbeafe' : '#f9fafb',
                                        color: isSelected ? '#1d4ed8' : '#4b5563',
                                        outline: isSelected ? '2px solid #3b82f6' : 'none',
                                        transition: 'all 0.15s ease',
                                    }}
                                    onMouseEnter={(e) => {
                                        if (!isSelected) {
                                            e.currentTarget.style.backgroundColor = '#f3f4f6'
                                        }
                                    }}
                                    onMouseLeave={(e) => {
                                        if (!isSelected) {
                                            e.currentTarget.style.backgroundColor = '#f9fafb'
                                        }
                                    }}
                                    title={iconName}
                                >
                                    <Icon size={20} />
                                </button>
                            )
                        })}
                    </div>
                </div>,
                document.body
            )}
        </>
    )
}

// Export icon map for use elsewhere
export { ICON_MAP }
export type { MeetingTypeIconName }


