/**
 * Appearance Presets Management Page
 * @since 1.3.0
 */

import { useState, useEffect } from 'react'
import { useAppearanceFontCss } from '../hooks/useAppearanceFontCss'
import { Link } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Edit2, Trash2, Star, Palette, Check, Settings, ChevronDown, ChevronUp, Save, CheckSquare, Square, X } from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardContent } from '@/components/common/Card'
import { QuickBotAssign } from '@/components/common/QuickBotAssign'
import { apiClient } from '@/api/client'
import { t, sprintf } from '@/lib/i18n'
import { useLanguage } from '@/contexts/LanguageContext'
import { GlobalValuesEditor } from '@/components/appearance/GlobalValuesEditor'
import { ChatSimulator } from '@/components/appearance/ChatSimulator'
import { PresetGlobalValues, DEFAULT_GLOBAL_VALUES, ElementSettings, WidgetSettings } from '@/types/appearance'
import { mergeElementSettings, mergeGlobalValues } from '../utils/appearanceMerge'

interface AppearancePreset {
    id: number
    name: string
    slug: string
    description: string | null
    is_default: number
    is_system: number
    language?: string
    primary_color: string
    secondary_color: string
    background_color: string
    header_background: string
    header_text_color: string
    user_message_bg: string
    user_message_text: string
    bot_message_bg: string
    bot_message_text: string
    input_bg: string
    input_border: string
    input_text: string
    button_bg: string
    button_text: string
    bubble_size: string
    bubble_animation: string
    window_border_radius: string
    window_shadow: string
    // New structured fields (Week 21 V2)
    global_values?: PresetGlobalValues | null
    element_settings?: ElementSettings | null
    widget_settings?: WidgetSettings | null
}

export function AppearancePresets() {
    const queryClient = useQueryClient()
    const { currentLanguage } = useLanguage()
    const [isGlobalValuesOpen, setIsGlobalValuesOpen] = useState(false)
    const [globalValues, setGlobalValues] = useState<PresetGlobalValues>(DEFAULT_GLOBAL_VALUES)
    const [globalValuesModified, setGlobalValuesModified] = useState(false)
    const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
    const [isSelectionMode, setIsSelectionMode] = useState(false)

    const { data, isLoading } = useQuery({
        queryKey: ['appearance-presets', currentLanguage],
        queryFn: () => apiClient.get<{ data: { presets: AppearancePreset[] } }>('appearance-presets', { language: currentLanguage }),
    })

    // Fetch global values (per-language scoped)
    const { data: globalValuesData, isLoading: isLoadingGlobalValues } = useQuery({
        queryKey: ['appearance-global-values', currentLanguage],
        queryFn: () => apiClient.get<{ data: { global_values: PresetGlobalValues; custom_font_css?: string } }>('appearance-presets/global-values', { language: currentLanguage }),
    })

    const fontCssVersion = useAppearanceFontCss(globalValuesData?.data?.custom_font_css)
    
    // Update local state when global values are fetched (skip if user has unsaved edits)
    useEffect(() => {
        if (globalValuesData?.data?.global_values && !globalValuesModified) {
            setGlobalValues(globalValuesData.data.global_values)
        }
    }, [globalValuesData])

    // Save global values mutation (per-language scoped)
    const saveGlobalValues = useMutation({
        mutationFn: (values: PresetGlobalValues) => 
            apiClient.put(`appearance-presets/global-values?language=${currentLanguage}`, values),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['appearance-global-values', currentLanguage] })
            setGlobalValuesModified(false)
            alert(t('Global settings saved successfully!'))
        },
        onError: (error) => {
            console.error('Failed to save global values:', error)
            alert(t('Error saving global settings'))
        },
    })

    const deletePreset = useMutation({
        mutationFn: (id: number) => apiClient.delete(`appearance-presets/${id}`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['appearance-presets', currentLanguage] })
        },
        onError: (error: any) => {
            console.error('Failed to delete preset:', error)
            const message = error?.message || t('Error deleting appearance preset')
            alert(message)
        },
    })

    const bulkDeletePresets = useMutation({
        mutationFn: (ids: number[]) => apiClient.post('appearance-presets/bulk-delete', { ids }),
        onSuccess: (response: any) => {
            queryClient.invalidateQueries({ queryKey: ['appearance-presets', currentLanguage] })
            setSelectedIds(new Set())
            setIsSelectionMode(false)
            alert(response?.data?.message || t('Items deleted successfully'))
        },
        onError: (error: any) => {
            console.error('Bulk delete failed:', error)
            alert(sprintf(t('Delete error: %s'), error?.message || t('Unknown error')))
        },
    })

    const setDefault = useMutation({
        mutationFn: (id: number) => apiClient.put(`appearance-presets/${id}/default`, {}),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['appearance-presets', currentLanguage] })
        },
        onError: (error) => {
            console.error('Failed to set default:', error)
            alert(t('Error setting default'))
        },
    })

    const presets = data?.data?.presets || []
    
    // Filter out system presets for selection (can't delete them)
    const selectablePresets = presets.filter(p => Number(p.is_system) !== 1)

    const handleDelete = (id: number, name: string, isSystem: boolean) => {
        if (isSystem) {
            alert(t('Cannot delete a system appearance preset'))
            return
        }
        if (confirm(sprintf(t('Are you sure you want to delete "%s"?'), name))) {
            deletePreset.mutate(id)
        }
    }

    const handleSetDefault = (id: number) => {
        setDefault.mutate(id)
    }

    const handleBulkDelete = () => {
        if (selectedIds.size === 0) return
        
        if (confirm(sprintf(t('Are you sure you want to delete %d appearance presets?'), selectedIds.size))) {
            bulkDeletePresets.mutate(Array.from(selectedIds))
        }
    }

    const handleToggleSelection = (id: number) => {
        const newSelected = new Set(selectedIds)
        if (newSelected.has(id)) {
            newSelected.delete(id)
        } else {
            newSelected.add(id)
        }
        setSelectedIds(newSelected)
    }

    const handleSelectAll = () => {
        if (selectedIds.size === selectablePresets.length) {
            setSelectedIds(new Set())
        } else {
            setSelectedIds(new Set(selectablePresets.map(p => p.id)))
        }
    }

    const exitSelectionMode = () => {
        setIsSelectionMode(false)
        setSelectedIds(new Set())
    }

    const handleGlobalValuesChange = (values: PresetGlobalValues) => {
        setGlobalValues(values)
        setGlobalValuesModified(true)
    }

    const handleSaveGlobalValues = () => {
        saveGlobalValues.mutate(globalValues)
    }

    if (isLoading || isLoadingGlobalValues) {
        return (
            <div className="flex items-center justify-center min-h-[400px]">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600" />
            </div>
        )
    }

    return (
        <div className="space-y-6 animate-fade-in">
            <PageHeader
                title={t('Appearance Presets')}
                subtitle={t('Manage ready-made designs for bots')}
            >
                <div className="flex items-center gap-2">
                    {!isSelectionMode ? (
                        <>
                            {selectablePresets.length > 0 && (
                                <button
                                    onClick={() => setIsSelectionMode(true)}
                                    className="flex items-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                                >
                                    <CheckSquare className="w-4 h-4" />
                                    {t('Select Multiple')}
                                </button>
                            )}
                            <Link
                                to="/appearance-presets/new"
                                className="flex items-center gap-2 px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
                            >
                                <Plus className="w-4 h-4" />
                                {t('Add Appearance Preset')}
                            </Link>
                        </>
                    ) : (
                        <>
                            <span className="text-sm text-gray-600">
                                {sprintf(t('%d selected'), selectedIds.size)}
                            </span>
                            <button
                                onClick={handleSelectAll}
                                className="flex items-center gap-2 px-3 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors text-sm"
                            >
                                {selectedIds.size === selectablePresets.length ? t('Deselect All') : t('Select All')}
                            </button>
                            <button
                                onClick={handleBulkDelete}
                                disabled={selectedIds.size === 0 || bulkDeletePresets.isPending}
                                className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                {bulkDeletePresets.isPending ? (
                                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                                ) : (
                                    <Trash2 className="w-4 h-4" />
                                )}
                                {t('Delete Selected')}
                            </button>
                            <button
                                onClick={exitSelectionMode}
                                className="flex items-center gap-2 px-3 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                            >
                                <X className="w-4 h-4" />
                            </button>
                        </>
                    )}
                </div>
            </PageHeader>

            {/* Global Values Section */}
            <Card className="overflow-hidden" data-wizard-id="global-values">
                <button
                    onClick={() => setIsGlobalValuesOpen(!isGlobalValuesOpen)}
                    className="w-full flex items-center justify-between px-6 py-4 bg-gradient-to-l from-primary-50 to-white hover:from-primary-100 transition-colors"
                >
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-lg bg-primary-100 flex items-center justify-center">
                            <Settings className="w-5 h-5 text-primary-600" />
                        </div>
                        <div className="text-right">
                            <h3 className="font-semibold text-gray-900">{t('Global Values')}</h3>
                            <p className="text-sm text-gray-500">{t('Shared settings for all appearance presets')}</p>
                        </div>
                    </div>
                    <div className="flex items-center gap-3">
                        {globalValuesModified && (
                            <span className="px-2 py-1 text-xs font-medium bg-yellow-100 text-yellow-700 rounded-full">
                                {t('Unsaved changes')}
                            </span>
                        )}
                        {isGlobalValuesOpen ? (
                            <ChevronUp className="w-5 h-5 text-gray-400" />
                        ) : (
                            <ChevronDown className="w-5 h-5 text-gray-400" />
                        )}
                    </div>
                </button>

                {isGlobalValuesOpen && (
                    <div className="border-t border-gray-200">
                        <CardContent className="py-6">
                            <GlobalValuesEditor
                                values={globalValues}
                                onChange={handleGlobalValuesChange}
                            />
                            
                            {/* Save Button */}
                            <div className="mt-6 pt-6 border-t border-gray-200 flex justify-end">
                                <button
                                    onClick={handleSaveGlobalValues}
                                    disabled={!globalValuesModified || saveGlobalValues.isPending}
                                    className={`flex items-center gap-2 px-6 py-2.5 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed ${
                                        globalValuesModified
                                            ? 'bg-amber-500 hover:bg-amber-600 animate-pulse'
                                            : 'bg-primary-600 hover:bg-primary-700'
                                    } text-white`}
                                >
                                    {saveGlobalValues.isPending ? (
                                        <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                                    ) : (
                                        <Save className="w-4 h-4" />
                                    )}
                                    {saveGlobalValues.isPending ? t('Saving...') : globalValuesModified ? t('Save Changes') : t('Save Global Values')}
                                </button>
                            </div>
                        </CardContent>
                    </div>
                )}
            </Card>

            {presets.length === 0 ? (
                <Card>
                    <CardContent className="py-16 text-center">
                        <Palette className="w-16 h-16 mx-auto text-gray-300 mb-4" />
                        <h3 className="text-lg font-medium text-gray-900 mb-2">
                            {t('No Appearance Presets')}
                        </h3>
                        <p className="text-gray-500 mb-6">
                            {t('Create your first appearance preset to start designing your bots')}
                        </p>
                        <Link
                            to="/appearance-presets/new"
                            className="inline-flex items-center gap-2 px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
                        >
                            <Plus className="w-4 h-4" />
                            {t('Create Appearance Preset')}
                        </Link>
                    </CardContent>
                </Card>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {presets.map((preset) => (
                        <PresetCard
                            key={`${preset.id}-${fontCssVersion}`}
                            preset={preset}
                            systemGlobalValues={globalValues}
                            onDelete={() => handleDelete(preset.id, preset.name, Number(preset.is_system) === 1)}
                            onSetDefault={() => handleSetDefault(preset.id)}
                            isSettingDefault={setDefault.isPending}
                            isSelectionMode={isSelectionMode}
                            isSelected={selectedIds.has(preset.id)}
                            onToggleSelection={() => handleToggleSelection(preset.id)}
                        />
                    ))}
                </div>
            )}
        </div>
    )
}

interface PresetCardProps {
    preset: AppearancePreset
    systemGlobalValues?: PresetGlobalValues
    onDelete: () => void
    onSetDefault: () => void
    isSettingDefault?: boolean
    isSelectionMode?: boolean
    isSelected?: boolean
    onToggleSelection?: () => void
}

function PresetCard({ preset, systemGlobalValues, onDelete, onSetDefault, isSettingDefault, isSelectionMode, isSelected, onToggleSelection }: PresetCardProps) {
    const { currentLanguage } = useLanguage()
    const isRTL = currentLanguage === 'he'

    // Resolve _links: if a preset color is linked to a system global value, use the system value
    const resolveLinkedColors = () => {
        const links = (preset.global_values as any)?._links?.colors || {};
        const resolved: Record<string, string> = {};
        const fallback = systemGlobalValues || DEFAULT_GLOBAL_VALUES;
        for (const [key, ref] of Object.entries(links)) {
            if (typeof ref !== 'string' || !ref) continue;
            const parts = (ref as string).split('.');
            let cur: any = fallback;
            for (const p of parts) {
                if (!cur || typeof cur !== 'object') { cur = undefined; break; }
                cur = cur[p];
            }
            if (typeof cur === 'string') resolved[key] = cur;
        }
        return resolved;
    };
    const linkedColors = resolveLinkedColors();

    const globalValues = mergeGlobalValues(preset.global_values, systemGlobalValues, linkedColors)

    const mergedSettings = mergeElementSettings(preset.element_settings)

    const elementSettings: ElementSettings = {
        ...mergedSettings,
        header: {
            ...mergedSettings.header,
            title: preset.name,
            subtitle: t(mergedSettings.header.subtitle || 'Online'),
        },
        chatWindow: {
            ...mergedSettings.chatWindow,
            width: { type: 'custom', value: '300px' },
            height: { type: 'custom', value: '400px' },
        },
        inputArea: {
            ...mergedSettings.inputArea,
            placeholder: t(mergedSettings.inputArea.placeholder || 'Type a message...'),
        },
    }
    
    const canSelect = Number(preset.is_system) !== 1
    
    return (
        <Card className={`relative group hover:shadow-xl transition-all duration-300 overflow-hidden ${isSelected ? 'ring-2 ring-primary-500' : ''}`}>
            {/* Selection Checkbox */}
            {isSelectionMode && canSelect && (
                <button
                    onClick={onToggleSelection}
                    className="absolute top-3 left-3 z-10 w-6 h-6 flex items-center justify-center rounded bg-white shadow-md hover:bg-gray-50 transition-colors"
                >
                    {isSelected ? (
                        <CheckSquare className="w-5 h-5 text-primary-600" />
                    ) : (
                        <Square className="w-5 h-5 text-gray-400" />
                    )}
                </button>
            )}
            
            {/* Preset Name Header - Always visible at top */}
            <div className="px-4 py-3 border-b border-gray-100 bg-white">
                <div className="flex flex-col gap-1">
                    <h3 className="font-semibold text-gray-900 text-base">
                        {preset.name}
                    </h3>
                    <div className="flex items-center gap-2 flex-wrap">
                        {Number(preset.is_default) === 1 && (
                            <>
                                <div className="flex items-center gap-1 px-2 py-1 bg-yellow-100 text-yellow-700 text-xs font-medium rounded-full">
                                    <Star className="w-3 h-3 fill-yellow-500" />
                                    {t('Default')}
                                </div>
                                <span className="px-2 py-1 bg-indigo-100 text-indigo-700 text-xs font-medium rounded-full">
                                    {t('Global Template')}
                                </span>
                            </>
                        )}
                        {Number(preset.is_system) === 1 && (
                            <span className="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">
                                {t('System')}
                            </span>
                        )}
                    </div>
                </div>
            </div>
            
            {/* Chat Simulator Preview - Scaled to fit card */}
            <div 
                className="bg-gray-100 overflow-hidden"
                style={{ 
                    height: '320px',
                    position: 'relative',
                }}
            >
                <div
                    style={{
                        transform: 'scale(0.55)',
                        transformOrigin: 'top center',
                        position: 'absolute',
                        top: '8px',
                        left: '50%',
                        marginLeft: '-150px',
                        width: '300px',
                    }}
                >
                    <ChatSimulator
                        globalValues={globalValues}
                        elementSettings={elementSettings}
                        scale={1}
                        isRTL={isRTL}
                        presetLanguage={preset.language || currentLanguage}
                    />
                </div>
            </div>

            <CardContent className="pt-3 pb-3">
                {/* Description */}
                {preset.description && (
                    <p className="text-xs text-gray-500 line-clamp-2 mb-3">
                        {preset.description}
                    </p>
                )}

                {/* Color Swatches */}
                <div className="flex gap-1 mb-3">
                    {[
                        { color: preset.primary_color, label: t('Primary') },
                        { color: preset.secondary_color, label: t('Secondary') },
                        { color: preset.user_message_bg, label: t('User Message') },
                        { color: preset.bot_message_bg, label: t('Bot Message') },
                    ]
                        .filter(item => item.color)
                        .map((item, idx) => (
                            <div
                                key={idx}
                                className="w-6 h-6 rounded-full border-2 border-white shadow-md cursor-help transition-transform hover:scale-110"
                                style={{ backgroundColor: item.color }}
                                title={`${item.label}: ${item.color}`}
                            />
                        ))}
                </div>

                {/* Actions */}
                <div className="flex gap-2">
                    <Link
                        to={`/appearance-presets/${preset.id}`}
                        className="flex-1 flex items-center justify-center gap-1 px-3 py-1.5 text-xs border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                        <Edit2 className="w-3 h-3" />
                        {t('Edit')}
                    </Link>

                    {Number(preset.is_default) !== 1 && (
                        <button
                            onClick={onSetDefault}
                            disabled={isSettingDefault}
                            className="px-2 py-1.5 text-xs border border-gray-300 rounded-lg hover:bg-yellow-50 hover:border-yellow-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                            title={t('Set as Default')}
                        >
                            {isSettingDefault ? (
                                <div className="w-3 h-3 border-2 border-yellow-500 border-t-transparent rounded-full animate-spin" />
                            ) : (
                                <Check className="w-3 h-3" />
                            )}
                        </button>
                    )}

                    <QuickBotAssign
                        entityType="appearance-preset"
                        entityId={preset.id}
                    />

                    {Number(preset.is_system) !== 1 && (
                        <button
                            onClick={onDelete}
                            className="px-2 py-1.5 text-xs border border-gray-300 rounded-lg text-red-600 hover:bg-red-50 hover:border-red-300 transition-colors"
                            title={t('Delete')}
                        >
                            <Trash2 className="w-3 h-3" />
                        </button>
                    )}
                </div>
            </CardContent>
        </Card>
    )
}

