/**
 * Bundle Builder Preview Component
 *
 * Interactive preview of the bundle widget with lifecycle states.
 *
 * @since 1.9.0
 */

import React, { useMemo, useState } from 'react';
import { AlertCircle, CheckCircle2, Loader2, Package, RefreshCw, Search, ShoppingCart, Shuffle, Star, Trash2 } from 'lucide-react';
import type { PresetGlobalValues, BundleBuilderWidgetSettings } from '../../../types/appearance';
import { resolveValue } from '@shared/utils/resolveAppearance';
import { ToggleSwitch } from '../../common/ToggleSwitch';
import { sprintf, t } from '@/lib/i18n';

interface BundleBuilderPreviewProps {
    globalValues: PresetGlobalValues;
    widgetSettings?: BundleBuilderWidgetSettings | null;
    isRTL?: boolean;
    language?: string;
}

type PreviewScreenState = 'display' | 'loading' | 'empty' | 'error' | 'success';
type PreviewActionState = 'idle' | 'swapping' | 'rebuilding' | 'adding';

const MOCK_PRODUCTS = [
    { id: 1, name: 'Concentrated Face Serum', price: 89, originalPrice: 119, rating: 4.5 },
    { id: 2, name: 'Daily Moisturizer', price: 65, originalPrice: 79, rating: 4.2 },
    { id: 3, name: 'Gentle Face Cleanser', price: 45, originalPrice: 55, rating: 4.8 },
];

function adjustColor(color: string, amount: number): string {
    const hex = color.replace('#', '');
    const num = parseInt(hex, 16);
    if (isNaN(num)) return color;
    const r = Math.min(255, Math.max(0, (num >> 16) + amount));
    const g = Math.min(255, Math.max(0, ((num >> 8) & 0x00ff) + amount));
    const b = Math.min(255, Math.max(0, (num & 0x0000ff) + amount));
    return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, '0')}`;
}

export const BundleBuilderPreview: React.FC<BundleBuilderPreviewProps> = ({
    globalValues,
    widgetSettings,
    isRTL = true,
    language,
}) => {
    const lang = language || 'he';
    const [screenState, setScreenState] = useState<PreviewScreenState>('display');
    const [actionState, setActionState] = useState<PreviewActionState>('idle');

    const currencySymbol = (window as any).boostbotAdmin?.woocommerce_currency_symbol || (lang === 'he' ? '₪' : '$');
    const totalPrice = MOCK_PRODUCTS.reduce((sum, p) => sum + p.price, 0);
    const originalPrice = MOCK_PRODUCTS.reduce((sum, p) => sum + p.originalPrice, 0);
    const savings = originalPrice - totalPrice;
    const savingsPercent = Math.round((savings / originalPrice) * 100);

    const rv = (field: any, fallback: string) => resolveValue(field, globalValues as any, fallback);
    const headerBg = rv(widgetSettings?.header?.background, '#3BC2D0');
    const primaryButton = widgetSettings?.primaryButton ?? widgetSettings?.button;

    const stateCard = useMemo(() => {
        const base = {
            background: screenState === 'loading'
                ? rv(widgetSettings?.states?.loadingBackground, '#FFFFFF')
                : screenState === 'empty'
                    ? rv(widgetSettings?.states?.emptyBackground, '#FFFFFF')
                    : screenState === 'error'
                        ? rv(widgetSettings?.states?.errorBackground, '#FFFFFF')
                        : rv(widgetSettings?.states?.successBackground, '#FFFFFF'),
            titleColor: rv(widgetSettings?.states?.titleColor, '#111827'),
            descriptionColor: rv(widgetSettings?.states?.descriptionColor, '#6B7280'),
        };

        if (screenState === 'loading') {
            return {
                ...base,
                icon: <Loader2 size={28} className="animate-spin" color={rv(widgetSettings?.states?.loadingIconColor, '#3BC2D0')} />,
                title: t('Preparing your bundle...'),
                description: t('Just a moment'),
            };
        }

        if (screenState === 'empty') {
            return {
                ...base,
                icon: <Search size={28} color={rv(widgetSettings?.states?.emptyIconColor, '#3BC2D0')} />,
                title: t('Empty'),
                description: t('No matching products found. Try broadening your criteria.'),
            };
        }

        if (screenState === 'error') {
            return {
                ...base,
                icon: <AlertCircle size={28} color={rv(widgetSettings?.states?.errorIconColor, '#DC2626')} />,
                title: t('Error'),
                description: t('Something went wrong. Please try again.'),
            };
        }

        return {
            ...base,
            icon: <CheckCircle2 size={28} color={rv(widgetSettings?.states?.successIconColor, '#16A34A')} />,
            title: t('Success'),
            description: t('Bundle added to cart!'),
        };
    }, [rv, screenState, widgetSettings?.states, lang]);

    const renderDisplay = () => (
        <div
            style={{
                background: rv(widgetSettings?.container?.background, '#ffffff'),
                borderRadius: rv(widgetSettings?.container?.borderRadius, '12px'),
                boxShadow: rv(widgetSettings?.container?.shadow, '0 4px 12px rgba(0,0,0,0.12)'),
                border: `1px solid ${rv(widgetSettings?.container?.borderColor, '#E5E7EB')}`,
                overflow: 'hidden',
            }}
        >
            <div
                style={{
                    background: `linear-gradient(135deg, ${headerBg}, ${adjustColor(headerBg, -20)})`,
                    color: rv(widgetSettings?.header?.textColor, '#ffffff'),
                    padding: '12px 16px',
                }}
            >
                <h3 style={{
                    fontWeight: parseInt(rv(widgetSettings?.header?.titleFontWeight, '700'), 10) || 700,
                    fontSize: rv(widgetSettings?.header?.titleFontSize, '16px'),
                    color: rv(widgetSettings?.header?.textColor, '#ffffff'),
                    margin: 0,
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                }}>
                    🎁 {t('The perfect bundle for you!')}
                </h3>
                <p style={{
                    fontSize: rv(widgetSettings?.header?.subtitleFontSize, '12px'),
                    color: rv(widgetSettings?.header?.subtitleColor, 'rgba(255,255,255,0.82)'),
                    margin: '4px 0 0',
                }}>
                    {sprintf(t('%d products selected just for you'), MOCK_PRODUCTS.length)}
                </p>
            </div>

            {actionState !== 'idle' && (
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '8px',
                    padding: '10px 14px',
                    background: rv(widgetSettings?.states?.loadingBackground, '#EFF6FF'),
                    borderBottom: `1px solid ${rv(widgetSettings?.summary?.borderColor, '#E5E7EB')}`,
                    color: rv(widgetSettings?.states?.titleColor, '#1E3A8A'),
                    fontSize: '12px',
                    fontWeight: 600,
                }}>
                    <Loader2 size={14} className="animate-spin" color={rv(widgetSettings?.states?.loadingIconColor, '#3BC2D0')} />
                    <span>
                        {actionState === 'swapping'
                            ? t('Updating bundle...')
                            : actionState === 'rebuilding'
                                ? t('Building your bundle...')
                                : t('Adding...')}
                    </span>
                </div>
            )}

            <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
                {MOCK_PRODUCTS.map((product) => (
                    <div
                        key={product.id}
                        style={{
                            display: 'flex',
                            flexDirection: 'column',
                            gap: '8px',
                            padding: '10px',
                            background: rv(widgetSettings?.productItem?.background, '#f9fafb'),
                            borderRadius: rv(widgetSettings?.productItem?.borderRadius, '8px'),
                            opacity: actionState === 'swapping' && product.id !== 1 ? 0.75 : 1,
                        }}
                    >
                        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                            <div
                                style={{
                                    width: '40px',
                                    height: '40px',
                                    borderRadius: '10px',
                                    background: '#E5E7EB',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    flexShrink: 0,
                                }}
                            >
                                <Package size={16} color="#9ca3af" />
                            </div>
                            <div style={{ flex: 1, minWidth: 0 }}>
                                <p style={{
                                    fontWeight: 600,
                                    fontSize: rv(widgetSettings?.productItem?.nameFontSize, '13px'),
                                    color: rv(widgetSettings?.productItem?.textColor, '#1f2937'),
                                    margin: 0,
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                    whiteSpace: 'nowrap',
                                }}>
                                    {t(product.name)}
                                </p>
                                <div style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '4px',
                                    fontSize: '11px',
                                    color: rv(widgetSettings?.productItem?.mutedTextColor, '#6B7280'),
                                }}>
                                    <Star size={10} fill="#EAB308" color="#EAB308" />
                                    {product.rating.toFixed(1)}
                                </div>
                            </div>
                            <div style={{ textAlign: 'end', flexShrink: 0 }}>
                                <p style={{
                                    fontWeight: 700,
                                    fontSize: rv(widgetSettings?.productItem?.priceFontSize, '13px'),
                                    color: rv(widgetSettings?.productItem?.priceColor, '#3BC2D0'),
                                    margin: 0,
                                }}>
                                    {currencySymbol}{product.price}
                                </p>
                                <p style={{
                                    fontSize: '11px',
                                    color: rv(widgetSettings?.priceDisplay?.originalPriceColor, '#9ca3af'),
                                    textDecoration: 'line-through',
                                    margin: 0,
                                }}>
                                    {currencySymbol}{product.originalPrice}
                                </p>
                            </div>
                        </div>

                        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
                            <button
                                type="button"
                                style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '4px',
                                    padding: '6px 10px',
                                    background: rv(widgetSettings?.swapButton?.background, '#FFFFFF'),
                                    color: rv(widgetSettings?.swapButton?.color, '#334155'),
                                    border: `1px solid ${rv(widgetSettings?.swapButton?.borderColor, '#CBD5E1')}`,
                                    borderRadius: rv(widgetSettings?.swapButton?.borderRadius, '9999px'),
                                    fontSize: rv(widgetSettings?.swapButton?.fontSize, '12px'),
                                    cursor: 'default',
                                }}
                            >
                                {actionState === 'swapping' && product.id === 1 ? <Loader2 size={12} className="animate-spin" /> : <Shuffle size={12} />}
                                <span>{t('Swap')}</span>
                            </button>
                            <button
                                type="button"
                                style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '4px',
                                    padding: '6px 10px',
                                    background: rv(widgetSettings?.removeButton?.background, '#FFF1F2'),
                                    color: rv(widgetSettings?.removeButton?.color, '#BE123C'),
                                    border: `1px solid ${rv(widgetSettings?.removeButton?.borderColor, '#FECDD3')}`,
                                    borderRadius: rv(widgetSettings?.removeButton?.borderRadius, '9999px'),
                                    fontSize: rv(widgetSettings?.removeButton?.fontSize, '12px'),
                                    cursor: 'default',
                                }}
                            >
                                <Trash2 size={12} />
                                <span>{t('Remove')}</span>
                            </button>
                        </div>
                    </div>
                ))}
            </div>

            <div style={{
                borderTop: `1px solid ${rv(widgetSettings?.summary?.borderColor, '#E5E7EB')}`,
                padding: '12px 16px',
                background: rv(widgetSettings?.summary?.background, '#f9fafb'),
            }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                    <span style={{ fontSize: '13px', color: rv(widgetSettings?.summary?.labelColor, '#6b7280') }}>
                        {t('Original price:')}
                    </span>
                    <span style={{
                        fontSize: '13px',
                        color: rv(widgetSettings?.priceDisplay?.originalPriceColor, '#9ca3af'),
                        textDecoration: 'line-through',
                    }}>
                        {currencySymbol}{originalPrice}
                    </span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
                    <span style={{ fontWeight: 700, fontSize: '15px', color: rv(widgetSettings?.summary?.totalLabelColor, '#1f2937') }}>
                        {t('Bundle price:')}
                    </span>
                    <span style={{
                        fontWeight: 800,
                        fontSize: '20px',
                        color: rv(widgetSettings?.priceDisplay?.discountedPriceColor, '#3BC2D0'),
                    }}>
                        {currencySymbol}{totalPrice}
                    </span>
                </div>

                <div
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        gap: '6px',
                        padding: '6px 10px',
                        background: rv(widgetSettings?.priceDisplay?.savingsBackground, '#DCFCE7'),
                        borderRadius: rv(widgetSettings?.priceDisplay?.savingsBorderRadius, '8px'),
                        marginBottom: '10px',
                    }}
                >
                    <span style={{
                        fontWeight: 600,
                        fontSize: '13px',
                        color: rv(widgetSettings?.priceDisplay?.savingsColor, '#15803D'),
                    }}>
                        {t('Save')} {currencySymbol}{savings} ({savingsPercent}%)
                    </span>
                </div>

                <div
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        gap: '6px',
                        padding: '6px 10px',
                        background: rv(widgetSettings?.priceDisplay?.couponBackground, '#F3E8FF'),
                        borderRadius: '10px',
                        marginBottom: '10px',
                        color: rv(widgetSettings?.priceDisplay?.couponColor, '#7E22CE'),
                        fontSize: '12px',
                        fontWeight: 600,
                    }}
                >
                    <span>🎟️</span>
                    <span>{t('Coupon applies automatically')}</span>
                </div>

                <div style={{ display: 'flex', gap: '8px' }}>
                    <button
                        type="button"
                        style={{
                            flex: 1,
                            padding: '10px',
                            background: rv(primaryButton?.background, '#3BC2D0'),
                            color: rv(primaryButton?.color, '#ffffff'),
                            border: `1px solid ${rv(primaryButton?.borderColor, '#3BC2D0')}`,
                            borderRadius: rv(primaryButton?.borderRadius, '8px'),
                            fontWeight: 700,
                            fontSize: rv(primaryButton?.fontSize, '14px'),
                            cursor: 'default',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            gap: '6px',
                        }}
                    >
                        {actionState === 'adding' ? <Loader2 size={16} className="animate-spin" /> : <ShoppingCart size={16} />}
                        {actionState === 'adding' ? t('Adding...') : t('Add to cart')}
                    </button>
                    <button
                        type="button"
                        style={{
                            padding: '10px 12px',
                            background: rv(widgetSettings?.secondaryButton?.background, '#FFFFFF'),
                            color: rv(widgetSettings?.secondaryButton?.color, '#334155'),
                            border: `1px solid ${rv(widgetSettings?.secondaryButton?.borderColor, '#CBD5E1')}`,
                            borderRadius: rv(widgetSettings?.secondaryButton?.borderRadius, '8px'),
                            fontWeight: 600,
                            fontSize: rv(widgetSettings?.secondaryButton?.fontSize, '13px'),
                            cursor: 'default',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            gap: '6px',
                        }}
                    >
                        {actionState === 'rebuilding' ? <Loader2 size={16} className="animate-spin" /> : <RefreshCw size={16} />}
                        {t('Another bundle')}
                    </button>
                </div>
            </div>
        </div>
    );

    return (
        <div style={{ maxWidth: '340px', width: '100%' }} dir={isRTL ? 'rtl' : 'ltr'}>
            <div className="mb-3 rounded-lg border border-gray-200 bg-white p-3">
                <div className="grid grid-cols-2 gap-3">
                    <div className="flex items-center justify-between gap-2">
                        <span className="text-xs text-gray-600">{t('Loading')}</span>
                        <ToggleSwitch
                            checked={screenState === 'loading'}
                            onChange={(checked) => setScreenState(checked ? 'loading' : 'display')}
                            ariaLabel={t('Toggle loading preview')}
                            size="sm"
                        />
                    </div>
                    <div className="flex items-center justify-between gap-2">
                        <span className="text-xs text-gray-600">{t('Empty')}</span>
                        <ToggleSwitch
                            checked={screenState === 'empty'}
                            onChange={(checked) => setScreenState(checked ? 'empty' : 'display')}
                            ariaLabel={t('Toggle empty preview')}
                            size="sm"
                        />
                    </div>
                    <div className="flex items-center justify-between gap-2">
                        <span className="text-xs text-gray-600">{t('Error')}</span>
                        <ToggleSwitch
                            checked={screenState === 'error'}
                            onChange={(checked) => setScreenState(checked ? 'error' : 'display')}
                            ariaLabel={t('Toggle error preview')}
                            size="sm"
                        />
                    </div>
                    <div className="flex items-center justify-between gap-2">
                        <span className="text-xs text-gray-600">{t('Success')}</span>
                        <ToggleSwitch
                            checked={screenState === 'success'}
                            onChange={(checked) => setScreenState(checked ? 'success' : 'display')}
                            ariaLabel={t('Toggle success preview')}
                            size="sm"
                        />
                    </div>
                    <div className="flex items-center justify-between gap-2">
                        <span className="text-xs text-gray-600">{t('Swap state')}</span>
                        <ToggleSwitch
                            checked={actionState === 'swapping'}
                            onChange={(checked) => setActionState(checked ? 'swapping' : 'idle')}
                            ariaLabel={t('Toggle swap preview')}
                            size="sm"
                        />
                    </div>
                    <div className="flex items-center justify-between gap-2">
                        <span className="text-xs text-gray-600">{t('Rebuild state')}</span>
                        <ToggleSwitch
                            checked={actionState === 'rebuilding'}
                            onChange={(checked) => setActionState(checked ? 'rebuilding' : 'idle')}
                            ariaLabel={t('Toggle rebuild preview')}
                            size="sm"
                        />
                    </div>
                    <div className="col-span-2 flex items-center justify-between gap-2">
                        <span className="text-xs text-gray-600">{t('Add to cart state')}</span>
                        <ToggleSwitch
                            checked={actionState === 'adding'}
                            onChange={(checked) => setActionState(checked ? 'adding' : 'idle')}
                            ariaLabel={t('Toggle add to cart preview')}
                            size="sm"
                        />
                    </div>
                </div>
            </div>

            {screenState === 'display' ? (
                renderDisplay()
            ) : (
                <div
                    style={{
                        background: stateCard.background,
                        borderRadius: rv(widgetSettings?.container?.borderRadius, '12px'),
                        boxShadow: rv(widgetSettings?.container?.shadow, '0 4px 12px rgba(0,0,0,0.12)'),
                        border: `1px solid ${rv(widgetSettings?.container?.borderColor, '#E5E7EB')}`,
                        padding: '24px',
                        textAlign: 'center',
                    }}
                >
                    <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full" style={{ background: '#F8FAFC' }}>
                        {stateCard.icon}
                    </div>
                    <h3 style={{ margin: 0, color: stateCard.titleColor, fontSize: rv(widgetSettings?.header?.titleFontSize, '16px') }}>
                        {stateCard.title}
                    </h3>
                    <p style={{ margin: '8px 0 0', color: stateCard.descriptionColor, fontSize: '13px' }}>
                        {stateCard.description}
                    </p>
                </div>
            )}
        </div>
    );
};

export default BundleBuilderPreview;
