import React, { useState } from 'react';
import { Alert, Pressable, Text, View } from 'react-native';
import { createShimmerPlaceholder } from 'react-native-shimmer-placeholder';
import LinearGradient from 'react-native-linear-gradient';
import CountryFlag from 'react-native-country-flag';
import Slider from '@react-native-community/slider';
import { useSharedValue } from 'react-native-reanimated';
import type { SharedValue } from 'react-native-reanimated';
import { ThemedStyleSheet, useTheme } from '../../branding';
import PageHeader from '../../componentsDS/PageHeader';
import type { PageHeaderData } from '../../componentsDS/PageHeader';
import type { LoadingState } from '../../types/types';
import ActivityIndicator from '../../components/ActivityIndicator';
import Pill from '../../componentsDS/Pill';
import FloatingButton from '../../componentsDS/FloatingButton';
import FloatingButtonsContainer from '../../componentsDS/FloatingButtonsContainer';
import Filter from '../../componentsDS/Icons/Filter';
import Search from '../../componentsDS/Icons/Search';
import Checkbox from '../../componentsDS/Checkbox';
import CountryLabel from '../../componentsDS/CountryLabel';
import FollowersLabel from '../../componentsDS/FollowersLabel';
import Position from '../../componentsDS/Position';
import Trend from '../../componentsDS/Trend';
import ModalTitle from '../../componentsDS/ModalTitle';
import OrderLabel from '../../componentsDS/OrderLabel';
import SwitchSelectorComponent from '../../componentsDS/SwitchSelector';
import StoreSelectionButton from '../../componentsDS/StoreSelectionButton';
import SortButton from '../../componentsDS/Buttons/SortButton';
import BrandFilters from '../../componentsDS/BrandFilters';
import SearchBar from '../../componentsDS/SearchBar';
import FreeTextBox from '../../componentsDS/FreeTextBox';
import Cta from '../../componentsDS/Cta';
import type { CtaIconProps } from '../../componentsDS/Cta';
import CtaGroup from '../../componentsDS/CtaGroup';
import Row from '../../componentsDS/Row';
import Star from '../../componentsDS/Icons/Star';
import Edit from '../../componentsDS/Icons/Edit';
import ExternalLink from '../../componentsDS/Icons/ExternalLink';
import Placeholder from '../../componentsDS/Icons/Placeholder';
import SpotifyIcon from '../../components/Icons/MyCatalogStoreIcons/SpotifyIcon';
import SongTile from '../../componentsDS/SongTile';
import Metrics from '../../componentsDS/Metrics';
import TopPlaylistTitle from '../../componentsDS/TopPlaylistTitle';
import Tooltip from '../../componentsDS/Tooltip';
import BottomSheetDeprecated from '../../componentsDS/BottomSheetDeprecated';
import { STREAMS_7_DAYS_SORT, FOLLOWERS_SORT } from '../../constants/sorting';
import type { TOCEntry } from '../../componentsDS/ComponentIndexTOC';
import { COMPONENTS_DOC } from './componentsData';

export type { PropDoc } from './componentsData';
import type { PropDoc } from './componentsData';

export interface DesignSystemVariant {
    name: string;
    render: () => React.ReactNode;
}

export interface DesignSystemEntry extends TOCEntry {
    category: string;
    description: string;
    interactive: () => React.ReactNode;
    variants: DesignSystemVariant[];
    props: PropDoc[];
    usage: string;
}

const ShimmerPlaceholder = createShimmerPlaceholder(LinearGradient);

const switchSelectorOptions = [
    { label: 'period.recent', value: 'recent' },
    { label: 'period.allTime', value: 'allTime' }
];

const demoStyles = ThemedStyleSheet.create(({ colors }) => ({
    demoHintText: { color: colors.midnight450, fontSize: 12 },
    triggerText: { color: colors.gray0, padding: 8 },
    optionRow: {
        paddingHorizontal: 16,
        paddingVertical: 14,
        borderBottomWidth: 1,
        borderBottomColor: colors.midnight700,
        flexDirection: 'row' as const,
        justifyContent: 'space-between' as const,
        alignItems: 'center' as const
    },
    optionText: { color: colors.midnight200, fontSize: 16 },
    optionTextSelected: { color: colors.gray0, fontSize: 16 },
    optionCheckmark: { color: colors.gray0, fontSize: 18 },
    typographyContainer: { width: '100%' as const, gap: 8 },
    typographyRow: {
        flexDirection: 'row' as const,
        alignItems: 'baseline' as const,
        gap: 8
    },
    typographyLabel: {
        color: colors.midnight450,
        fontSize: 10,
        fontFamily: 'monospace',
        width: 72
    },
    typographyTextColor: { color: colors.gray0, flex: 1 },
    colourContainer: { width: '100%' as const, gap: 4 },
    colourRow: {
        flexDirection: 'row' as const,
        alignItems: 'center' as const,
        gap: 8
    },
    colourSwatch: {
        width: 32,
        height: 20,
        borderRadius: 4,
        borderWidth: 1,
        borderColor: colors.midnight700
    },
    colourName: {
        color: colors.midnight300,
        fontSize: 11,
        fontFamily: 'monospace',
        width: 90
    },
    colourHex: {
        color: colors.midnight450,
        fontSize: 11,
        fontFamily: 'monospace'
    },
    skeletonContainer: {
        width: '100%' as const,
        alignItems: 'flex-start' as const,
        gap: 10
    },
    skeletonBar: { borderRadius: 4 },
    loaderHint: {
        color: colors.midnight450,
        fontSize: 12,
        textAlign: 'center' as const,
        marginTop: 8
    },
    demoColumn: {
        width: '100%' as const,
        alignItems: 'center' as const,
        gap: 12
    },
    stepperRow: {
        flexDirection: 'row' as const,
        alignItems: 'center' as const,
        gap: 12
    },
    stepperButton: {
        width: 32,
        height: 32,
        borderRadius: 16,
        backgroundColor: colors.midnight700,
        alignItems: 'center' as const,
        justifyContent: 'center' as const
    },
    stepperButtonText: { color: colors.gray0, fontSize: 18, lineHeight: 20 },
    stepperValue: {
        color: colors.midnight300,
        fontSize: 12,
        fontFamily: 'monospace',
        minWidth: 110,
        textAlign: 'center' as const
    },
    trackHeaderBand: {
        width: '100%' as const,
        backgroundColor: colors.midnight900,
        borderRadius: 8,
        overflow: 'hidden' as const
    },
    trackHeaderControls: {
        width: '100%' as const,
        gap: 8,
        marginTop: 16
    },
    trackHeaderStateRow: {
        flexDirection: 'row' as const,
        gap: 8,
        justifyContent: 'center' as const
    },
    trackHeaderStateButton: {
        paddingVertical: 6,
        paddingHorizontal: 14,
        borderRadius: 9999,
        borderWidth: 1,
        borderColor: colors.midnight700
    },
    trackHeaderStateButtonActive: {
        backgroundColor: colors.midnight700,
        borderColor: colors.midnight700
    },
    trackHeaderStateText: { color: colors.midnight300, fontSize: 12 },
    trackHeaderStateTextActive: { color: colors.gray0, fontSize: 12 },
    trackHeaderSliderLabel: {
        color: colors.midnight450,
        fontSize: 11,
        textAlign: 'center' as const
    }
}));

const switchSelectorInlineStyle = { position: 'relative' as const, top: 0 };

const InteractivePill = () => {
    const [selected, setSelected] = useState(false);
    return (
        <Pill
            label="Tap me"
            selected={selected}
            onPress={() => setSelected(v => !v)}
        />
    );
};

const InteractiveFloatingButton = () => {
    const [count, setCount] = useState(0);
    return (
        <FloatingButton
            icon={Filter}
            label="Filters"
            count={count}
            onPress={() => setCount(v => (v + 1) % 4)}
        />
    );
};

interface DemoStepperProps {
    label: string;
    value: number;
    min?: number;
    max?: number;
    onChange: (next: number) => void;
}

const DemoStepper = ({
    label,
    value,
    min = 0,
    max = Infinity,
    onChange
}: DemoStepperProps) => {
    const { theme } = useTheme();
    const s = demoStyles[theme];
    return (
        <View style={s.stepperRow}>
            <Pressable
                style={s.stepperButton}
                onPress={() => onChange(Math.max(min, value - 1))}
                accessibilityLabel={`Decrease ${label}`}
            >
                <Text style={s.stepperButtonText}>−</Text>
            </Pressable>
            <Text style={s.stepperValue}>{`${label}: ${value}`}</Text>
            <Pressable
                style={s.stepperButton}
                onPress={() => onChange(Math.min(max, value + 1))}
                accessibilityLabel={`Increase ${label}`}
            >
                <Text style={s.stepperButtonText}>+</Text>
            </Pressable>
        </View>
    );
};

const InteractiveBadgeCounter = () => {
    const [count, setCount] = useState(1);
    const { theme } = useTheme();
    const s = demoStyles[theme];
    return (
        <View style={s.demoColumn}>
            <FloatingButton icon={Filter} label="Filters" count={count} />
            <DemoStepper label="count" value={count} onChange={setCount} />
        </View>
    );
};

const buildDemoFloatingButtons = (amount: number) =>
    Array.from({ length: amount }, (_, index) => {
        if (index % 4 === 3) {
            return <FloatingButton key={index} icon={Search} />;
        }
        return (
            <FloatingButton
                key={index}
                icon={Filter}
                label={`Filter ${index + 1}`}
                count={index % 3 === 0 ? index + 1 : undefined}
            />
        );
    });

const InteractiveButtonsContainer = () => {
    const [amount, setAmount] = useState(3);
    const { theme } = useTheme();
    const s = demoStyles[theme];
    return (
        <View style={s.demoColumn}>
            <FloatingButtonsContainer>
                {buildDemoFloatingButtons(amount)}
            </FloatingButtonsContainer>
            <DemoStepper
                label="buttons"
                value={amount}
                max={12}
                onChange={setAmount}
            />
        </View>
    );
};

const InteractiveCheckbox = () => {
    const [checked, setChecked] = useState(false);
    return <Checkbox checked={checked} onChange={() => setChecked(v => !v)} />;
};

const InteractiveSwitchSelector = () => {
    const [value, setValue] = useState('recent');
    return (
        <SwitchSelectorComponent
            options={switchSelectorOptions}
            value={value}
            onSwitchSelectorPress={setValue}
            style={switchSelectorInlineStyle}
        />
    );
};

const DEMO_STORES = [
    { title: undefined, storeName: undefined },
    { title: 'Spotify', storeName: 'spotify' },
    { title: 'Apple Music', storeName: 'apple_music' },
    { title: 'Amazon Music', storeName: 'amazon_music' },
    { title: 'Tidal', storeName: 'tidal' }
] as const;

const InteractiveStoreSelectionButton = () => {
    const [idx, setIdx] = useState(0);
    const { title, storeName } = DEMO_STORES[idx];
    return (
        <StoreSelectionButton
            title={title}
            storeName={storeName}
            onButtonPress={() => setIdx(i => (i + 1) % DEMO_STORES.length)}
        />
    );
};

const DEMO_SORT_KEYS = [STREAMS_7_DAYS_SORT, FOLLOWERS_SORT] as const;

const InteractiveSortButton = () => {
    const [idx, setIdx] = useState(0);
    return (
        <SortButton
            sortKey={DEMO_SORT_KEYS[idx]}
            onSortPress={() => setIdx(i => (i + 1) % DEMO_SORT_KEYS.length)}
        />
    );
};

const InteractiveBrandFilters = () => {
    const [selectedFilters, setSelectedFilters] = useState<
        { name: string; value: string }[]
    >([]);
    return (
        <BrandFilters
            selectedFilters={selectedFilters}
            onFilterSelect={(brand: { name: string; value: string }) => {
                setSelectedFilters(prev =>
                    prev.some(f => f.value === brand.value)
                        ? prev.filter(f => f.value !== brand.value)
                        : [...prev, brand]
                );
            }}
            hasSMEData={false}
        />
    );
};

const SEARCH_BAR_PLACEHOLDER = 'Search by Country Name or Code';

const InteractiveSearchBar = () => {
    const [query, setQuery] = useState('');
    return (
        <SearchBar
            value={query}
            onChangeText={setQuery}
            placeholder={SEARCH_BAR_PLACEHOLDER}
            onClear={() => setQuery('')}
        />
    );
};

const FREE_TEXT_BOX_LABEL = 'Additional Details (Required)';
const FREE_TEXT_BOX_PLACEHOLDER = 'Add details...';

const InteractiveFreeTextBox = ({
    initialValue = ''
}: {
    initialValue?: string;
}) => {
    const [details, setDetails] = useState(initialValue);
    return (
        <FreeTextBox
            label={FREE_TEXT_BOX_LABEL}
            value={details}
            onChangeText={setDetails}
            placeholder={FREE_TEXT_BOX_PLACEHOLDER}
        />
    );
};

const FilledStar = ({ color, size }: CtaIconProps) => (
    <Star color={color} size={size} filled />
);

const InteractiveCta = () => {
    const [highlighted, setHighlighted] = useState(false);
    return (
        <Cta
            icon={highlighted ? FilledStar : Star}
            label="Favorite"
            highlighted={highlighted}
            onPress={() => setHighlighted(v => !v)}
        />
    );
};

const InteractiveRow = () => {
    const [selected, setSelected] = useState(false);
    return (
        <Row
            variant="multiSelect"
            label="United States"
            selected={selected}
            onPress={() => setSelected(v => !v)}
        />
    );
};

const InteractiveSongTile = () => (
    <SongTile
        songUrl=""
        artistName="The Weeknd"
        songName="Blinding Lights"
        streamQuantity={4200000}
        addedDate="2024-01-15"
        onSongTilePress={() => Alert.alert('Song pressed')}
    />
);

const DemoHint = ({ children }: { children: string }) => {
    const { theme } = useTheme();
    return <Text style={demoStyles[theme].demoHintText}>{children}</Text>;
};

const InteractiveTooltip = () => {
    const [visible, setVisible] = useState(false);
    const { theme } = useTheme();
    return (
        <>
            <Pressable onPress={() => setVisible(true)}>
                <Text style={demoStyles[theme].triggerText}>Show Tooltip</Text>
            </Pressable>
            <Tooltip
                isVisible={visible}
                onClose={() => setVisible(false)}
                title="Did you know?"
                text="This tooltip explains a feature in context."
            />
        </>
    );
};

const SORT_OPTIONS = [
    'Streams (7 days)',
    'Streams (all time)',
    'Followers',
    'Chart position'
];

const InteractiveBottomSheet = () => {
    const [visible, setVisible] = useState(false);
    const [selected, setSelected] = useState('Streams (7 days)');
    const { theme } = useTheme();
    const s = demoStyles[theme];
    return (
        <>
            <Pressable onPress={() => setVisible(true)}>
                <Text style={s.triggerText}>Open Bottom Sheet</Text>
            </Pressable>
            <BottomSheetDeprecated
                isVisible={visible}
                onClose={() => setVisible(false)}
                title="Sort by"
            >
                {SORT_OPTIONS.map(option => (
                    <Pressable
                        key={option}
                        onPress={() => {
                            setSelected(option);
                            setVisible(false);
                        }}
                        style={s.optionRow}
                    >
                        <Text
                            style={
                                option === selected
                                    ? s.optionTextSelected
                                    : s.optionText
                            }
                        >
                            {option}
                        </Text>
                        {option === selected && (
                            <Text style={s.optionCheckmark}>✓</Text>
                        )}
                    </Pressable>
                ))}
            </BottomSheetDeprecated>
        </>
    );
};

const TypographyShowcase = () => {
    const { theme, typography } = useTheme();
    const s = demoStyles[theme];
    const scales = [
        { name: 'h1DS', style: typography.h1DS },
        { name: 'h2DS', style: typography.h2DS },
        { name: 'h3DS', style: typography.h3DS },
        { name: 'body1DS', style: typography.body1DS },
        { name: 'body2DS', style: typography.body2DS },
        { name: 'label1DS', style: typography.label1DS },
        { name: 'label2DS', style: typography.label2DS },
        { name: 'label3DS', style: typography.label3DS }
    ];
    return (
        <View style={s.typographyContainer}>
            {scales.map(scale => (
                <View key={scale.name} style={s.typographyRow}>
                    <Text style={s.typographyLabel}>{scale.name}</Text>
                    <Text style={[scale.style, s.typographyTextColor]}>
                        The quick brown fox
                    </Text>
                </View>
            ))}
        </View>
    );
};

const MIDNIGHT_STEPS = [
    200, 300, 450, 500, 550, 600, 700, 750, 800, 850, 900, 950, 1000
] as const;

const ColourPaletteShowcase = () => {
    const { colors, theme } = useTheme();
    const s = demoStyles[theme];
    return (
        <View style={s.colourContainer}>
            {MIDNIGHT_STEPS.map(step => {
                const key = `midnight${step}` as keyof typeof colors;
                const hex = colors[key];
                if (typeof hex !== 'string') {
                    return null;
                }
                return (
                    <View key={step} style={s.colourRow}>
                        <View
                            style={[s.colourSwatch, { backgroundColor: hex }]}
                        />
                        <Text style={s.colourName}>{`midnight${step}`}</Text>
                        <Text style={s.colourHex}>{hex}</Text>
                    </View>
                );
            })}
        </View>
    );
};

const InteractiveSkeleton = () => {
    const [running, setRunning] = useState(false);
    const { colors, theme } = useTheme();
    const s = demoStyles[theme];
    const shimmerColors = [
        colors.midnight850,
        colors.midnight700,
        colors.midnight850
    ] as [string, string, string];
    return (
        <Pressable onPress={() => setRunning(v => !v)}>
            {running ? (
                <View style={s.skeletonContainer}>
                    <ShimmerPlaceholder
                        width={220}
                        height={16}
                        shimmerColors={shimmerColors}
                        shimmerStyle={s.skeletonBar}
                    />
                    <ShimmerPlaceholder
                        width={160}
                        height={12}
                        shimmerColors={shimmerColors}
                        shimmerStyle={s.skeletonBar}
                    />
                    <ShimmerPlaceholder
                        width={100}
                        height={12}
                        shimmerColors={shimmerColors}
                        shimmerStyle={s.skeletonBar}
                    />
                </View>
            ) : (
                <Text style={s.triggerText}>Tap to play shimmer</Text>
            )}
            <Text style={s.loaderHint}>
                {running ? 'Tap to stop' : 'Animation paused'}
            </Text>
        </Pressable>
    );
};

const InteractiveActivityIndicator = () => {
    const [running, setRunning] = useState(false);
    const { theme } = useTheme();
    const s = demoStyles[theme];
    return (
        <Pressable onPress={() => setRunning(v => !v)}>
            {running ? (
                <ActivityIndicator />
            ) : (
                <Text style={s.triggerText}>Tap to play loader</Text>
            )}
            <Text style={s.loaderHint}>
                {running ? 'Tap to stop' : 'Animation paused'}
            </Text>
        </Pressable>
    );
};

const PAGE_HEADER_DEMO = {
    title: 'Smooth Criminal - 2012 Remaster',
    subtitle: 'Michael Jackson',
    meta: '14 Sep 2012'
};

type PageHeaderState = LoadingState<PageHeaderData>['status'];

const PAGE_HEADER_STATES: PageHeaderState[] = ['data', 'loading', 'error'];

const noop = () => {};

interface DemoHeaderOptions {
    isFavorite?: boolean;
    isDeleted?: boolean;
    interactive?: boolean;
}

const renderDemoPageHeader = (
    progress: SharedValue<number>,
    state: PageHeaderState,
    {
        isFavorite = false,
        isDeleted = false,
        interactive
    }: DemoHeaderOptions = {}
) => {
    const alertOr = (message: string) =>
        interactive ? () => Alert.alert(message) : noop;
    const handlers = {
        onBackPress: alertOr('Back pressed'),
        onStarPress: alertOr('Star pressed'),
        onContentPress: alertOr('Content pressed')
    };

    const buildLoadingState = (): LoadingState<PageHeaderData> => {
        if (state === 'error') {
            return { status: 'error', error: new Error('Demo error') };
        }
        if (state === 'loading') {
            return { status: 'loading' };
        }
        return {
            status: 'data',
            data: {
                title: PAGE_HEADER_DEMO.title,
                subtitle: PAGE_HEADER_DEMO.subtitle,
                meta: PAGE_HEADER_DEMO.meta,
                isDeleted,
                isFavorite
            }
        };
    };

    return (
        <PageHeader
            progress={progress}
            loadingState={buildLoadingState()}
            {...handlers}
        />
    );
};

interface PageHeaderPreviewProps {
    state: PageHeaderState;
    collapsed?: boolean;
    isFavorite?: boolean;
    isDeleted?: boolean;
}

const PageHeaderStatePreview = ({
    state,
    collapsed,
    isFavorite,
    isDeleted
}: PageHeaderPreviewProps) => {
    const { theme } = useTheme();
    const s = demoStyles[theme];
    const progress = useSharedValue(collapsed ? 1 : 0);
    return (
        <View style={s.trackHeaderBand}>
            {renderDemoPageHeader(progress, state, { isFavorite, isDeleted })}
        </View>
    );
};

const InteractivePageHeader = () => {
    const { theme, colors } = useTheme();
    const s = demoStyles[theme];
    const [state, setState] = useState<PageHeaderState>('data');
    const [isFavorite, setIsFavorite] = useState(false);
    const [isDeleted, setIsDeleted] = useState(false);
    const [collapsePct, setCollapsePct] = useState(0);
    const progress = useSharedValue(0);

    const toggles = [
        {
            label: isFavorite ? 'Favorite ★' : 'Favorite ☆',
            active: isFavorite,
            handlePress: () => setIsFavorite(v => !v)
        },
        {
            label: 'Deleted',
            active: isDeleted,
            handlePress: () => setIsDeleted(v => !v)
        }
    ];

    return (
        <View style={s.typographyContainer}>
            <View style={s.trackHeaderBand}>
                {renderDemoPageHeader(progress, state, {
                    isFavorite,
                    isDeleted,
                    interactive: true
                })}
            </View>
            <View style={s.trackHeaderControls}>
                <View style={s.trackHeaderStateRow}>
                    {PAGE_HEADER_STATES.map(option => {
                        const active = state === option;
                        return (
                            <Pressable
                                key={option}
                                onPress={() => setState(option)}
                                style={[
                                    s.trackHeaderStateButton,
                                    active && s.trackHeaderStateButtonActive
                                ]}
                            >
                                <Text
                                    style={
                                        active
                                            ? s.trackHeaderStateTextActive
                                            : s.trackHeaderStateText
                                    }
                                >
                                    {option}
                                </Text>
                            </Pressable>
                        );
                    })}
                </View>
                {state === 'data' && (
                    <View style={s.trackHeaderStateRow}>
                        {toggles.map(toggle => (
                            <Pressable
                                key={toggle.label}
                                onPress={toggle.handlePress}
                                style={[
                                    s.trackHeaderStateButton,
                                    toggle.active &&
                                        s.trackHeaderStateButtonActive
                                ]}
                            >
                                <Text
                                    style={
                                        toggle.active
                                            ? s.trackHeaderStateTextActive
                                            : s.trackHeaderStateText
                                    }
                                >
                                    {toggle.label}
                                </Text>
                            </Pressable>
                        ))}
                    </View>
                )}
                <Slider
                    minimumValue={0}
                    maximumValue={1}
                    value={0}
                    onValueChange={value => {
                        progress.value = value;
                        setCollapsePct(Math.round(value * 100));
                    }}
                    minimumTrackTintColor={colors.gray0}
                    maximumTrackTintColor={colors.midnight700}
                    thumbTintColor={colors.gray0}
                />
                <Text style={s.trackHeaderSliderLabel}>
                    {`Collapse ${collapsePct}% · drag to test expanded ↔ collapsed`}
                </Text>
            </View>
        </View>
    );
};

interface InteractiveEntry {
    interactive: () => React.ReactNode;
    variants: DesignSystemVariant[];
}

const INTERACTIVE_MAP: Record<string, InteractiveEntry> = {
    typography: { interactive: () => <TypographyShowcase />, variants: [] },
    colours: { interactive: () => <ColourPaletteShowcase />, variants: [] },
    'page-header': {
        interactive: () => <InteractivePageHeader />,
        variants: [
            {
                name: 'Data',
                render: () => <PageHeaderStatePreview state="data" />
            },
            {
                name: 'Data / Collapsed',
                render: () => <PageHeaderStatePreview state="data" collapsed />
            },
            {
                name: 'Favorite / Off',
                render: () => (
                    <PageHeaderStatePreview state="data" isFavorite={false} />
                )
            },
            {
                name: 'Favorite / On',
                render: () => <PageHeaderStatePreview state="data" isFavorite />
            },
            {
                name: 'Deleted',
                render: () => <PageHeaderStatePreview state="data" isDeleted />
            },
            {
                name: 'Deleted / Collapsed',
                render: () => (
                    <PageHeaderStatePreview state="data" isDeleted collapsed />
                )
            },
            {
                name: 'Loading',
                render: () => <PageHeaderStatePreview state="loading" />
            },
            {
                name: 'Loading / Collapsed',
                render: () => (
                    <PageHeaderStatePreview state="loading" collapsed />
                )
            },
            {
                name: 'Error',
                render: () => <PageHeaderStatePreview state="error" />
            },
            {
                name: 'Error / Collapsed',
                render: () => <PageHeaderStatePreview state="error" collapsed />
            }
        ]
    },
    pill: {
        interactive: () => <InteractivePill />,
        variants: [
            { name: 'Default', render: () => <Pill label="Default" /> },
            {
                name: 'Selected',
                render: () => <Pill label="Selected" selected />
            },
            {
                name: 'With chevron',
                render: () => <Pill label="Filter" chevronDown />
            },
            { name: 'Search', render: () => <Pill search /> },
            { name: 'Right chevron', render: () => <Pill rightChevron /> },
            { name: 'Double chevron', render: () => <Pill doubleChevron /> }
        ]
    },
    'floating-button': {
        interactive: () => <InteractiveFloatingButton />,
        variants: [
            {
                name: 'Icon only',
                render: () => <FloatingButton icon={Search} />
            },
            {
                name: 'Icon + label',
                render: () => <FloatingButton icon={Filter} label="Filters" />
            },
            {
                name: 'Icon + label + badge',
                render: () => <InteractiveBadgeCounter />
            },
            {
                name: 'Container',
                render: () => <InteractiveButtonsContainer />
            }
        ]
    },
    checkbox: {
        interactive: () => <InteractiveCheckbox />,
        variants: [
            { name: 'Unchecked', render: () => <Checkbox checked={false} /> },
            { name: 'Checked', render: () => <Checkbox checked /> }
        ]
    },
    'country-label': {
        interactive: () => <CountryLabel countryCode="US" />,
        variants: [
            {
                name: 'With country',
                render: () => <CountryLabel countryCode="US" />
            },
            { name: 'Global', render: () => <CountryLabel /> }
        ]
    },
    'followers-label': {
        interactive: () => <FollowersLabel followersCount={1200000} />,
        variants: [
            {
                name: 'With count',
                render: () => <FollowersLabel followersCount={1200000} />
            },
            {
                name: 'Zero',
                render: () => <FollowersLabel followersCount={0} />
            }
        ]
    },
    position: {
        interactive: () => <Position position={3} />,
        variants: [
            {
                name: 'Top 10',
                render: () => <Position position={3} />
            },
            {
                name: 'High',
                render: () => <Position position={42} />
            }
        ]
    },
    trend: {
        interactive: () => <Trend trendValue={12} />,
        variants: [
            { name: 'Up', render: () => <Trend trendValue={12} /> },
            { name: 'Down', render: () => <Trend trendValue={-5} /> },
            { name: 'Neutral', render: () => <Trend trendValue={0} /> },
            {
                name: 'New entry',
                render: () => <Trend isNewlyEntered={true} />
            }
        ]
    },
    'modal-title': {
        interactive: () => <ModalTitle title="Select Market" />,
        variants: [
            {
                name: 'Default',
                render: () => <ModalTitle title="Select Market" />
            }
        ]
    },
    'order-label': {
        interactive: () => (
            <OrderLabel
                label={1}
                containerStyle={{ position: 'relative', top: 0, left: 0 }}
            />
        ),
        variants: [
            {
                name: 'Numeric',
                render: () => (
                    <OrderLabel
                        label={1}
                        containerStyle={{
                            position: 'relative',
                            top: 0,
                            left: 0
                        }}
                    />
                )
            },
            {
                name: 'String',
                render: () => (
                    <OrderLabel
                        label="NEW"
                        containerStyle={{
                            position: 'relative',
                            top: 0,
                            left: 0
                        }}
                    />
                )
            }
        ]
    },
    'switch-selector': {
        interactive: () => <InteractiveSwitchSelector />,
        variants: [
            {
                name: 'Recent selected',
                render: () => (
                    <SwitchSelectorComponent
                        options={switchSelectorOptions}
                        value="recent"
                        style={switchSelectorInlineStyle}
                    />
                )
            },
            {
                name: 'All Time selected',
                render: () => (
                    <SwitchSelectorComponent
                        options={switchSelectorOptions}
                        value="allTime"
                        style={switchSelectorInlineStyle}
                    />
                )
            }
        ]
    },
    'store-selection-button': {
        interactive: () => <InteractiveStoreSelectionButton />,
        variants: [
            {
                name: 'Default (no store)',
                render: () => <StoreSelectionButton onButtonPress={() => {}} />
            },
            {
                name: 'With store',
                render: () => (
                    <StoreSelectionButton
                        title="Spotify"
                        storeName="spotify"
                        onButtonPress={() => {}}
                    />
                )
            }
        ]
    },
    'sort-button': {
        interactive: () => <InteractiveSortButton />,
        variants: [
            {
                name: 'Streams 7 days',
                render: () => (
                    <SortButton
                        sortKey={STREAMS_7_DAYS_SORT}
                        onSortPress={() => {}}
                    />
                )
            },
            {
                name: 'Followers',
                render: () => (
                    <SortButton
                        sortKey={FOLLOWERS_SORT}
                        onSortPress={() => {}}
                    />
                )
            },
            {
                name: 'Disabled',
                render: () => (
                    <SortButton
                        sortKey={STREAMS_7_DAYS_SORT}
                        disabled={true}
                        onSortPress={() => {}}
                    />
                )
            }
        ]
    },
    'brand-filters': {
        interactive: () => <InteractiveBrandFilters />,
        variants: [
            {
                name: 'AWAL + Orchard',
                render: () => (
                    <BrandFilters
                        selectedFilters={[]}
                        onFilterSelect={() => {}}
                        hasSMEData={false}
                    />
                )
            },
            {
                name: 'SME + Orchard',
                render: () => (
                    <BrandFilters
                        selectedFilters={[]}
                        onFilterSelect={() => {}}
                        hasSMEData={true}
                    />
                )
            }
        ]
    },
    'search-bar': {
        interactive: () => <InteractiveSearchBar />,
        variants: [
            {
                name: 'Empty',
                render: () => (
                    <SearchBar
                        value=""
                        onChangeText={() => {}}
                        placeholder={SEARCH_BAR_PLACEHOLDER}
                        editable={false}
                    />
                )
            },
            {
                name: 'Populated',
                render: () => (
                    <SearchBar
                        value="Sad But True"
                        onChangeText={() => {}}
                        placeholder={SEARCH_BAR_PLACEHOLDER}
                        editable={false}
                    />
                )
            }
        ]
    },
    'free-text-box': {
        interactive: () => <InteractiveFreeTextBox />,
        variants: [
            {
                name: 'Empty',
                render: () => <InteractiveFreeTextBox initialValue="" />
            },
            {
                name: 'Populated',
                render: () => (
                    <InteractiveFreeTextBox initialValue="Great show, needs a louder mix." />
                )
            }
        ]
    },
    cta: {
        interactive: () => <InteractiveCta />,
        variants: [
            {
                name: 'Default',
                render: () => (
                    <Cta icon={Filter} label="Report" onPress={() => {}} />
                )
            },
            {
                name: 'Highlighted',
                render: () => (
                    <Cta
                        icon={FilledStar}
                        label="Favorite"
                        highlighted
                        onPress={() => {}}
                    />
                )
            }
        ]
    },
    'cta-group': {
        interactive: () => (
            <CtaGroup>
                <Cta icon={Filter} label="Report" onPress={() => {}} />
                <Cta
                    icon={FilledStar}
                    label="Favorite"
                    highlighted
                    onPress={() => {}}
                />
            </CtaGroup>
        ),
        variants: [
            {
                name: 'Two tiles',
                render: () => (
                    <CtaGroup>
                        <Cta icon={Filter} label="Report" onPress={() => {}} />
                        <Cta
                            icon={FilledStar}
                            label="Favorite"
                            highlighted
                            onPress={() => {}}
                        />
                    </CtaGroup>
                )
            }
        ]
    },
    row: {
        interactive: () => <InteractiveRow />,
        variants: [
            {
                name: 'Single select — selected',
                render: () => (
                    <Row
                        variant="singleSelect"
                        label="Item Name"
                        disclaimer="Disclaimer"
                        icon={<CountryFlag isoCode="US" size={13} />}
                        selected
                    />
                )
            },
            {
                name: 'Single select — unselected',
                render: () => (
                    <Row
                        variant="singleSelect"
                        label="Item Name"
                        disclaimer="Disclaimer"
                        icon={<CountryFlag isoCode="US" size={13} />}
                    />
                )
            },
            {
                name: 'Multi select — selected',
                render: () => (
                    <Row
                        variant="multiSelect"
                        label="Item Name"
                        disclaimer="Disclaimer"
                        icon={<CountryFlag isoCode="US" size={13} />}
                        selected
                    />
                )
            },
            {
                name: 'Multi select — unselected',
                render: () => (
                    <Row
                        variant="multiSelect"
                        label="Item Name"
                        disclaimer="Disclaimer"
                        icon={<CountryFlag isoCode="US" size={13} />}
                    />
                )
            },
            {
                name: 'Starred — selected',
                render: () => (
                    <Row
                        variant="starred"
                        label="Item Name"
                        disclaimer="Disclaimer"
                        icon={<CountryFlag isoCode="US" size={13} />}
                        selected
                    />
                )
            },
            {
                name: 'Starred — unselected',
                render: () => (
                    <Row
                        variant="starred"
                        label="Item Name"
                        disclaimer="Disclaimer"
                        icon={<CountryFlag isoCode="US" size={13} />}
                    />
                )
            },
            {
                name: 'Status — highlighted',
                render: () => (
                    <Row
                        variant="status"
                        label="Item Name"
                        disclaimer="Disclaimer"
                        icon={<SpotifyIcon />}
                        statusLabel="Status"
                        statusHighlighted
                    />
                )
            },
            {
                name: 'Status — waiting',
                render: () => (
                    <Row
                        variant="status"
                        label="Item Name"
                        disclaimer="Disclaimer"
                        icon={<SpotifyIcon />}
                        statusLabel="Waiting"
                    />
                )
            },
            {
                name: 'Action / Category',
                render: () => (
                    <Row
                        variant="actionCategory"
                        label="Action / Category"
                        disclaimer="Disclaimer"
                        icon={<Star size={24} />}
                        indicator="Indicator"
                    />
                )
            },
            {
                name: 'Entity link',
                render: () => (
                    <Row
                        variant="entityLink"
                        label="Action / Category"
                        disclaimer="Disclaimer"
                        icon={<Placeholder size={48} />}
                        indicator="Indicator"
                    />
                )
            },
            {
                name: 'Quick actions',
                render: () => (
                    <Row
                        variant="quickActions"
                        label="Quick Actions"
                        disclaimer="Disclaimer"
                        icon={<Star size={24} />}
                        quickActions={[
                            { icon: <Edit />, onPress: () => {} },
                            { icon: <ExternalLink />, onPress: () => {} }
                        ]}
                    />
                )
            },
            {
                name: 'Inline editing',
                render: () => (
                    <Row
                        variant="inlineEditing"
                        icon={<Star size={24} />}
                        inputValue="https://open.spotify.com/artist/4q3ewBCX7sLwd24euuV69X"
                        onInputChangeText={() => {}}
                        disclaimer="You can copy the URL directly from their Spotify profile."
                    />
                )
            },
            {
                name: 'Toggle — on',
                render: () => (
                    <Row
                        variant="toggle"
                        label="Item Name"
                        disclaimer="Disclaimer"
                        icon={<CountryFlag isoCode="US" size={13} />}
                        selected
                    />
                )
            },
            {
                name: 'Toggle — off',
                render: () => (
                    <Row
                        variant="toggle"
                        label="Item Name"
                        disclaimer="Disclaimer"
                        icon={<CountryFlag isoCode="US" size={13} />}
                    />
                )
            },
            {
                name: 'Skeleton 48',
                render: () => <Row variant="skeleton" />
            },
            {
                name: 'Skeleton 56',
                render: () => <Row variant="skeleton" skeletonSize={56} />
            }
        ]
    },
    'song-tile': {
        interactive: () => <InteractiveSongTile />,
        variants: [
            {
                name: 'Full info',
                render: () => (
                    <SongTile
                        songUrl=""
                        artistName="The Weeknd"
                        songName="Blinding Lights"
                        streamQuantity={4200000}
                        addedDate="2024-01-15"
                        onSongTilePress={() => {}}
                    />
                )
            },
            {
                name: 'Without streams',
                render: () => (
                    <SongTile
                        songUrl=""
                        artistName="The Weeknd"
                        songName="Blinding Lights"
                        addedDate="2024-01-15"
                        isStreamsVisible={false}
                        onSongTilePress={() => {}}
                    />
                )
            }
        ]
    },
    metrics: {
        interactive: () => (
            <Metrics
                countryCode="US"
                followersCount={850000}
                positionValue={5}
                trendValue={3}
            />
        ),
        variants: [
            {
                name: 'With all data',
                render: () => (
                    <Metrics
                        countryCode="US"
                        followersCount={850000}
                        positionValue={5}
                        trendValue={3}
                    />
                )
            },
            {
                name: 'Newly entered',
                render: () => (
                    <Metrics isNewlyEntered={true} followersCount={12000} />
                )
            },
            {
                name: 'Minimal',
                render: () => <Metrics />
            }
        ]
    },
    'top-playlist-title': {
        interactive: () => (
            <TopPlaylistTitle
                title="Today's Top Hits"
                onInfoPress={() => Alert.alert('Info')}
            />
        ),
        variants: [
            {
                name: 'Without info icon',
                render: () => <TopPlaylistTitle title="Today's Top Hits" />
            },
            {
                name: 'With info icon',
                render: () => (
                    <TopPlaylistTitle
                        title="Today's Top Hits"
                        onInfoPress={() => Alert.alert('Info')}
                    />
                )
            }
        ]
    },
    tooltip: {
        interactive: () => <InteractiveTooltip />,
        variants: [
            {
                name: 'Trigger',
                render: () => (
                    <DemoHint>
                        Tap &quot;Show Tooltip&quot; in the live preview above.
                    </DemoHint>
                )
            }
        ]
    },
    'bottom-sheet-deprecated': {
        interactive: () => <InteractiveBottomSheet />,
        variants: [
            {
                name: 'Trigger',
                render: () => (
                    <DemoHint>
                        Tap &quot;Open Bottom Sheet&quot; in the live preview
                        above.
                    </DemoHint>
                )
            }
        ]
    },
    'activity-indicator': {
        interactive: () => <InteractiveActivityIndicator />,
        variants: []
    },
    'skeleton-row': {
        interactive: () => <InteractiveSkeleton />,
        variants: []
    }
};

export const COMPONENTS: DesignSystemEntry[] = COMPONENTS_DOC.map(
    doc =>
        ({
            ...doc,
            ...(INTERACTIVE_MAP[doc.id] ?? {
                interactive: () => null,
                variants: []
            })
        } as DesignSystemEntry)
);
