/**
 * ButtonStyleEditor Component
 * Complete Elementor-style button styling controls
 * Combines typography, colors, border, shadow, padding, and icon settings
 * 
 * Features:
 * - Normal and Hover state tabs
 * - Typography control with global presets
 * - Per-side border width with units
 * - Per-corner border radius with units
 * - Visual box shadow control
 * - Per-side padding with units
 * - Icon settings (position, size, color, spacing)
 * 
 * All labels in Hebrew, RTL layout
 */

import React, { useState } from 'react'
import { t } from '@/lib/i18n'
import { ChevronDown, ChevronUp, Type, Palette, Square, Maximize, Image, Copy, ClipboardPaste } from 'lucide-react'
import { FieldValue, PresetGlobalValues, createCustomValue, createGlobalRef } from '../../types/appearance'
import { BorderWidthEditor, BorderWidthValue } from './BorderWidthEditor'
import { BorderRadiusValue } from './BorderRadiusEditor'
import { BorderRadiusFieldEditor } from './BorderRadiusFieldEditor'
import { ButtonIconEditor, ButtonIconValue } from './ButtonIconEditor'
import { BoxShadowFieldEditor } from './BoxShadowFieldEditor'
import { PaddingEditor, PaddingValue } from './PaddingEditor'
import LinkedFieldEditor from '../appearance/LinkedFieldEditor'
import { TypographyControl, TypographySettings } from '../appearance/TypographyControl'

// Button style value types
export interface ButtonStyleValue {
    // Typography
    typography: {
        fontFamily: FieldValue
        fontSize: FieldValue
        fontWeight: FieldValue
        textTransform: FieldValue
        fontStyle: FieldValue
        textDecoration: FieldValue
        lineHeight: FieldValue
        letterSpacing: FieldValue
    }
    // Normal state colors
    textColor: FieldValue
    backgroundColor: FieldValue
    // Border settings
    borderType: 'none' | 'solid' | 'dashed' | 'dotted'
    borderWidth: BorderWidthValue
    borderColor: FieldValue
    borderRadius: FieldValue | BorderRadiusValue
    // Shadow
    boxShadow: FieldValue
    // Padding
    padding: PaddingValue
    // Icon (optional)
    icon?: ButtonIconValue
    // Hover state
    hover: {
        textColor: FieldValue
        backgroundColor: FieldValue
        borderColor: FieldValue
        boxShadow: FieldValue
        iconColor?: FieldValue
    }
    // Transition
    transitionDuration: string
}

interface ButtonStyleEditorProps {
    value: ButtonStyleValue
    onChange: (value: ButtonStyleValue) => void
    globalValues: PresetGlobalValues
    label?: string
    disabled?: boolean
    showIcon?: boolean
    /** When true, show icon selection in the icon section (IconTemplate composition). */
    showIconPicker?: boolean
    /** When true, hide the icon position selector (for icon-only buttons with no text). */
    hideIconPosition?: boolean
    showTypography?: boolean
    onSaveAsGlobalTypographyScale?: (name: string, values: Record<string, string>) => void
}

// Collapsible section component
interface SectionProps {
    title: string
    icon: React.ReactNode
    children: React.ReactNode
    defaultOpen?: boolean
}

function Section({ title, icon, children, defaultOpen = false }: SectionProps) {
    const [isOpen, setIsOpen] = useState(defaultOpen)

    return (
        <div className="border border-gray-200 rounded-lg" dir="rtl">
            <button
                type="button"
                onClick={() => setIsOpen(!isOpen)}
                className="w-full px-4 py-3 bg-gray-50 hover:bg-gray-100 transition-colors flex items-center justify-between rounded-t-lg"
            >
                <span className="flex items-center gap-2 text-sm font-medium text-gray-700">
                    {icon}
                    {title}
                </span>
                {isOpen ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
            </button>
            {isOpen && (
                <div className="p-4 space-y-4 bg-white rounded-b-lg overflow-visible">
                    {children}
                </div>
            )}
        </div>
    )
}

// Border type options - Hebrew labels
const BORDER_TYPE_OPTIONS: { value: string; labelKey: string }[] = [
    { value: 'none', labelKey: 'None' },
    { value: 'solid', labelKey: 'Solid' },
    { value: 'dashed', labelKey: 'Dashed' },
    { value: 'dotted', labelKey: 'Dotted' },
]

// Transition options - Hebrew labels
const TRANSITION_OPTIONS: { value: string; labelKey: string }[] = [
    { value: '0ms', labelKey: 'None' },
    { value: '150ms', labelKey: 'Fast (150ms)' },
    { value: '200ms', labelKey: 'Normal (200ms)' },
    { value: '300ms', labelKey: 'Slow (300ms)' },
    { value: '500ms', labelKey: 'Very Slow (500ms)' },
]

export function ButtonStyleEditor({
    value,
    onChange,
    globalValues,
    label = t('Button Style'),
    disabled = false,
    showIcon = false,
    showIconPicker = false,
    hideIconPosition = false,
    showTypography = true,
}: ButtonStyleEditorProps) {
    const [activeTab, setActiveTab] = useState<'normal' | 'hover'>('normal')
    const [clipboardTick, setClipboardTick] = useState(0)
    const [feedback, setFeedback] = useState<'copied' | 'pasted' | null>(null)

    const STORAGE_KEY = 'boostbot.buttonStyleClipboard.v1'

    // Note: we keep a tick to refresh clipboard availability across multiple editor instances
    // (paste button is always enabled; paste is best-effort/no-op when empty)
    void clipboardTick

    // Keep paste availability in sync across multiple editors
    React.useEffect(() => {
        const onStorage = (e: StorageEvent) => {
            if (e.key === STORAGE_KEY) setClipboardTick((x) => x + 1)
        }
        const onCustom = () => setClipboardTick((x) => x + 1)
        window.addEventListener('storage', onStorage)
        window.addEventListener('boostbot:buttonStyleClipboardUpdated' as any, onCustom)
        return () => {
            window.removeEventListener('storage', onStorage)
            window.removeEventListener('boostbot:buttonStyleClipboardUpdated' as any, onCustom)
        }
    }, [])

    const handleCopy = async () => {
        try {
            const payload = JSON.stringify(value)
            localStorage.setItem(STORAGE_KEY, payload)
            window.dispatchEvent(new Event('boostbot:buttonStyleClipboardUpdated'))
            setFeedback('copied')
            // Best-effort clipboard copy for sharing between editors/tabs
            if (navigator.clipboard?.writeText) {
                await navigator.clipboard.writeText(payload)
            }
            window.setTimeout(() => setFeedback(null), 1200)
        } catch {
            // no-op (copy is best-effort)
        }
    }

    const isButtonStyleValue = (v: unknown): v is ButtonStyleValue => {
        if (!v || typeof v !== 'object') return false
        const o = v as Record<string, unknown>
        return !!o.typography && !!o.textColor && !!o.backgroundColor && !!o.borderType && !!o.borderWidth && !!o.borderColor && !!o.borderRadius && !!o.boxShadow && !!o.padding && !!o.hover && typeof o.transitionDuration === 'string'
    }

    const handlePaste = async () => {
        try {
            let raw: string | null = null
            raw = localStorage.getItem(STORAGE_KEY)

            if (!raw && navigator.clipboard?.readText) {
                raw = await navigator.clipboard.readText()
            }

            if (!raw) return

            const parsed = JSON.parse(raw) as unknown
            if (!isButtonStyleValue(parsed)) return

            onChange(parsed)
            window.dispatchEvent(new Event('boostbot:buttonStyleClipboardUpdated'))
            setFeedback('pasted')
            window.setTimeout(() => setFeedback(null), 1200)
        } catch {
            // no-op (paste is best-effort)
        }
    }

    const handleChange = <K extends keyof ButtonStyleValue>(
        field: K,
        newValue: ButtonStyleValue[K]
    ) => {
        onChange({
            ...value,
            [field]: newValue,
        })
    }

    // Handle full typography object change from TypographyControl
    const handleFullTypographyChange = (typography: TypographySettings) => {
        onChange({
            ...value,
            typography: {
                fontFamily: typography.fontFamily || value.typography.fontFamily,
                fontSize: typography.fontSize || value.typography.fontSize,
                fontWeight: typography.fontWeight || value.typography.fontWeight,
                textTransform: typography.textTransform || value.typography.textTransform,
                fontStyle: typography.fontStyle || value.typography.fontStyle,
                textDecoration: typography.textDecoration || value.typography.textDecoration,
                lineHeight: typography.lineHeight || value.typography.lineHeight,
                letterSpacing: typography.letterSpacing || value.typography.letterSpacing,
            },
        })
    }

    const handleHoverChange = (
        field: keyof ButtonStyleValue['hover'],
        newValue: FieldValue | string
    ) => {
        onChange({
            ...value,
            hover: {
                ...value.hover,
                [field]: newValue,
            },
        })
    }

    return (
        <div className="space-y-4" dir="rtl">
            {label && (
                <div className="flex items-center justify-between gap-3">
                    <h3 className="text-sm font-semibold text-gray-800">{label}</h3>
                    <div className="flex items-center gap-2">
                        <button
                            type="button"
                            onClick={handleCopy}
                            disabled={disabled}
                            className="inline-flex items-center gap-1.5 px-2 py-1 text-xs rounded border border-gray-200 bg-white hover:bg-gray-50 disabled:opacity-50"
                            title={t('Copy Style')}
                        >
                            <Copy size={14} />
                            {t('Copy')}
                        </button>
                        <button
                            type="button"
                            onClick={handlePaste}
                            disabled={disabled}
                            className="inline-flex items-center gap-1.5 px-2 py-1 text-xs rounded border border-gray-200 bg-white hover:bg-gray-50 disabled:opacity-50"
                            title={t('Paste Style')}
                        >
                            <ClipboardPaste size={14} />
                            {t('Paste')}
                        </button>
                        {feedback && (
                            <span className="text-xs text-gray-500">
                                {feedback === 'copied' ? t('Copied!') : t('Pasted!') }
                            </span>
                        )}
                    </div>
                </div>
            )}

            {/* Normal/Hover Tab Switcher */}
            <div className="flex border-b border-gray-200">
                <button
                    type="button"
                    onClick={() => setActiveTab('normal')}
                    className={`
                        flex-1 py-2 px-4 text-sm font-medium transition-colors
                        ${activeTab === 'normal'
                            ? 'text-primary-600 border-b-2 border-primary-500'
                            : 'text-gray-500 hover:text-gray-700'
                        }
                    `}
                >
                    {t('Normal')}
                </button>
                <button
                    type="button"
                    onClick={() => setActiveTab('hover')}
                    className={`
                        flex-1 py-2 px-4 text-sm font-medium transition-colors
                        ${activeTab === 'hover'
                            ? 'text-primary-600 border-b-2 border-primary-500'
                            : 'text-gray-500 hover:text-gray-700'
                        }
                    `}
                >
                    {t('Hover')}
                </button>
            </div>

            <div className="space-y-3">
                {activeTab === 'normal' ? (
                    /* Normal State Controls */
                    <>
                        {/* Typography Section */}
                        {showTypography && (
                            <Section title={t('Typography')} icon={<Type size={16} />} defaultOpen={false}>
                                <TypographyControl
                                    label={t('Text Styling')}
                                    value={value.typography as TypographySettings}
                                    globalValues={globalValues}
                                    onChange={(typography) => handleFullTypographyChange(typography)}
                                    disabled={disabled}
                                    context="button"
                                />
                            </Section>
                        )}

                        {/* Colors Section */}
                        <Section title={t('Colors')} icon={<Palette size={16} />} defaultOpen={true}>
                            <div className="space-y-3">
                                <LinkedFieldEditor
                                    label={t('Text Color')}
                                    value={value.textColor}
                                    globalValues={globalValues}
                                    onChange={(v) => handleChange('textColor', v)}
                                    fieldType="color"
                                    disabled={disabled}
                                />
                                <LinkedFieldEditor
                                    label={t('Background Color')}
                                    value={value.backgroundColor}
                                    globalValues={globalValues}
                                    onChange={(v) => handleChange('backgroundColor', v)}
                                    fieldType="color"
                                    disabled={disabled}
                                />
                            </div>
                        </Section>

                        {/* Border Section */}
                        <Section title={t('Borders')} icon={<Square size={16} />} defaultOpen={false}>
                            <div className="space-y-4">
                                {/* Border Type */}
                                <div className="space-y-1.5">
                                    <label className="text-xs text-gray-500">{t('Border Type')}</label>
                                    <select
                                        value={value.borderType}
                                        onChange={(e) => handleChange('borderType', e.target.value as ButtonStyleValue['borderType'])}
                                        disabled={disabled}
                                        className="
                                            w-full px-3 py-2 text-sm
                                            border border-gray-300 rounded-md
                                            focus:ring-1 focus:ring-primary-500 focus:border-primary-500
                                            disabled:bg-gray-100 disabled:cursor-not-allowed
                                        "
                                    >
                                        {BORDER_TYPE_OPTIONS.map((opt) => (
                                            <option key={opt.value} value={opt.value}>
                                                {t(opt.labelKey)}
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                {value.borderType !== 'none' && (
                                    <>
                                        <BorderWidthEditor
                                            value={value.borderWidth}
                                            onChange={(v) => handleChange('borderWidth', v)}
                                            label={t('Border Width')}
                                            disabled={disabled}
                                        />
                                        <LinkedFieldEditor
                                            label={t('Border Color')}
                                            value={value.borderColor}
                                            globalValues={globalValues}
                                            onChange={(v) => handleChange('borderColor', v)}
                                            fieldType="color"
                                            disabled={disabled}
                                        />
                                    </>
                                )}

                                <BorderRadiusFieldEditor
                                    label={t('Border Radius')}
                                    value={value.borderRadius as FieldValue | BorderRadiusValue | undefined}
                                    globalValues={globalValues}
                                    onChange={(v) => handleChange('borderRadius', v as unknown as ButtonStyleValue['borderRadius'])}
                                    disabled={disabled}
                                    defaultGlobalRef="effects.borderRadiusMedium"
                                />
                            </div>
                        </Section>

                        {/* Shadow Section */}
                        <Section title={t('Shadow')} icon={<Square size={16} />} defaultOpen={false}>
                            <BoxShadowFieldEditor
                                label={t('Button Shadow')}
                                value={value.boxShadow}
                                globalValues={globalValues}
                                onChange={(v) => handleChange('boxShadow', v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.shadowSmall"
                            />
                        </Section>

                        {/* Padding Section */}
                        <Section title={t('Inner Padding')} icon={<Maximize size={16} />} defaultOpen={false}>
                            <PaddingEditor
                                value={value.padding}
                                onChange={(v) => handleChange('padding', v)}
                                outputMode="object"
                                label={t('Padding')}
                                disabled={disabled}
                            />
                        </Section>

                        {/* Icon Section (optional) - show even if icon not yet defined */}
                        {showIcon && (
                            <Section title={t('Icon')} icon={<Image size={16} />} defaultOpen={false}>
                                <ButtonIconEditor
                                    value={value.icon || {
                                        icon: 'send' as any,
                                        position: 'only',
                                        size: '20px',
                                        color: createGlobalRef('colors.textLight'),
                                        spacing: '0px',
                                        hoverColor: createGlobalRef('colors.textLight'),
                                    }}
                                    onChange={(v) => handleChange('icon', v)}
                                    globalValues={globalValues}
                                    label=""
                                    disabled={disabled}
                                    showHoverColor={false}
                                    showIconPicker={showIconPicker}
                                    hidePosition={hideIconPosition}
                                />
                            </Section>
                        )}

                        {/* Transition Duration */}
                        <div className="pt-2 border-t border-gray-100">
                            <label className="block text-xs text-gray-500 mb-1.5">{t('Transition Duration')}</label>
                            <select
                                value={value.transitionDuration}
                                onChange={(e) => handleChange('transitionDuration', e.target.value)}
                                disabled={disabled}
                                className="
                                    w-full px-3 py-2 text-sm
                                    border border-gray-300 rounded-md
                                    focus:ring-1 focus:ring-primary-500 focus:border-primary-500
                                    disabled:bg-gray-100 disabled:cursor-not-allowed
                                "
                            >
                                {TRANSITION_OPTIONS.map((opt) => (
                                    <option key={opt.value} value={opt.value}>
                                        {t(opt.labelKey)}
                                    </option>
                                ))}
                            </select>
                        </div>
                    </>
                ) : (
                    /* Hover State Controls */
                    <>
                        {/* Hover Colors */}
                        <Section title={t('Hover Colors')} icon={<Palette size={16} />} defaultOpen={true}>
                            <div className="space-y-3">
                                <LinkedFieldEditor
                                    label={t('Text Color (Hover)')}
                                    value={value.hover.textColor}
                                    globalValues={globalValues}
                                    onChange={(v) => handleHoverChange('textColor', v)}
                                    fieldType="color"
                                    disabled={disabled}
                                />
                                <LinkedFieldEditor
                                    label={t('Background Color (Hover)')}
                                    value={value.hover.backgroundColor}
                                    globalValues={globalValues}
                                    onChange={(v) => handleHoverChange('backgroundColor', v)}
                                    fieldType="color"
                                    disabled={disabled}
                                />
                            </div>
                        </Section>

                        {/* Hover Border */}
                        {value.borderType !== 'none' && (
                            <Section title={t('Hover Border')} icon={<Square size={16} />} defaultOpen={false}>
                                <LinkedFieldEditor
                                    label={t('Border Color (Hover)')}
                                    value={value.hover.borderColor}
                                    globalValues={globalValues}
                                    onChange={(v) => handleHoverChange('borderColor', v)}
                                    fieldType="color"
                                    disabled={disabled}
                                />
                            </Section>
                        )}

                        {/* Hover Shadow */}
                        <Section title={t('Hover Shadow')} icon={<Square size={16} />} defaultOpen={false}>
                            <BoxShadowFieldEditor
                                label={t('Hover Shadow')}
                                value={value.hover.boxShadow as any}
                                globalValues={globalValues}
                                onChange={(v) => handleHoverChange('boxShadow', v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.shadowSmall"
                            />
                        </Section>

                        {/* Hover Icon Color (if icon enabled) */}
                        {showIcon && (
                            <Section title={t('Hover Icon')} icon={<Image size={16} />} defaultOpen={false}>
                                <LinkedFieldEditor
                                    label={t('Icon Color (Hover)')}
                                    value={value.hover.iconColor || value.icon?.color || createGlobalRef('colors.textLight')}
                                    globalValues={globalValues}
                                    onChange={(v) => handleHoverChange('iconColor', v)}
                                    fieldType="color"
                                    disabled={disabled}
                                />
                            </Section>
                        )}
                    </>
                )}
            </div>
        </div>
    )
}

/**
 * Create default button style values
 */
export function createDefaultButtonStyle(
    variant: 'primary' | 'secondary' | 'ghost' = 'primary'
): ButtonStyleValue {
    const variants = {
        primary: {
            textColor: createGlobalRef('colors.background'),
            backgroundColor: createGlobalRef('colors.primary'),
            borderColor: createGlobalRef('colors.primary'),
            hoverBackgroundColor: createGlobalRef('colors.secondary'),
            hoverBorderColor: createGlobalRef('colors.secondary'),
        },
        secondary: {
            textColor: createGlobalRef('colors.primary'),
            backgroundColor: createGlobalRef('colors.background'),
            borderColor: createGlobalRef('colors.primary'),
            hoverBackgroundColor: createGlobalRef('colors.primary'),
            hoverBorderColor: createGlobalRef('colors.primary'),
        },
        ghost: {
            textColor: createGlobalRef('colors.text'),
            backgroundColor: createCustomValue('transparent'),
            borderColor: createCustomValue('transparent'),
            hoverBackgroundColor: createGlobalRef('colors.surface'),
            hoverBorderColor: createCustomValue('transparent'),
        },
    }

    const v = variants[variant]

    return {
        typography: {
            fontFamily: createGlobalRef('typography.button.fontFamily'),
            fontSize: createGlobalRef('typography.button.fontSize'),
            fontWeight: createGlobalRef('typography.button.fontWeight'),
            textTransform: createCustomValue('none'),
            fontStyle: createCustomValue('normal'),
            textDecoration: createCustomValue('none'),
            lineHeight: createGlobalRef('typography.button.lineHeight'),
            letterSpacing: createCustomValue('0px'),
        },
        textColor: v.textColor,
        backgroundColor: v.backgroundColor,
        borderType: 'solid',
        borderWidth: {
            top: '1px',
            right: '1px',
            bottom: '1px',
            left: '1px',
        },
        borderColor: v.borderColor,
        borderRadius: {
            topLeft: '8px',
            topRight: '8px',
            bottomRight: '8px',
            bottomLeft: '8px',
        },
        boxShadow: createGlobalRef('effects.shadowSmall'),
        padding: {
            top: '10px',
            right: '20px',
            bottom: '10px',
            left: '20px',
        },
        hover: {
            textColor: createGlobalRef('colors.background'),
            backgroundColor: v.hoverBackgroundColor,
            borderColor: v.hoverBorderColor,
            boxShadow: createGlobalRef('effects.shadowMedium'),
        },
        transitionDuration: '200ms',
    }
}

export default ButtonStyleEditor
