import React from 'react';
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
    Sparkles, ChevronDown, Check, Scaling, Monitor, Clock, Layers, Aperture, Film, Volume2, VolumeX, Mic2, UserCircle, Image as ImageIcon
} from 'lucide-react';
import { cn } from '@/utils';

// Re-export from new modular structure
export { ModelSelector } from './selectors/ModelSelector';
export { StyleSelector } from './selectors/StyleSelector';
export { AssetSelector } from './selectors/AssetSelector';

const capitalize = (s: string) => s ? s.charAt(0).toUpperCase() + s.slice(1) : '';

import type { ModelConfig } from '@/types/model';
import { useVideoGenerationOptions } from '@/lib/hooks/useGenerationConfig';
import { getResolutionLevels, getAspectRatiosForResolution } from '@/lib/utils/modelResolutionUtils';
import {
    IMAGE_ASPECT_RATIOS, VIDEO_ASPECT_RATIOS, VIDEO_RESOLUTIONS, IMAGE_RESOLUTIONS,
    IMAGE_COUNTS, VIDEO_COUNTS
} from '../../constants';

export function TooltipButton({ icon, active, onClick, label }: { icon: React.ReactNode, active: boolean, onClick: () => void, label: string }) {
    return (
        <div className="relative group">
            <button
                onClick={onClick}
                className={cn(
                    "p-2.5 rounded-full transition-all duration-200 w-auto h-auto",
                    active
                        ? "bg-white/10 text-foreground shadow-inner hover:bg-white/15"
                        : "text-foreground/40 hover:text-foreground hover:bg-white/5"
                )}
            >
                {icon}
            </button>
            <div className="absolute left-14 top-1/2 -translate-y-1/2 bg-black/90 text-white text-[10px] px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none border border-white/10">
                {label}
            </div>
        </div>
    );
}

export function Badge({ icon, text }: { icon?: React.ReactNode, text: string }) {
    return (
        <div className="flex items-center gap-1.5 bg-black/30 border border-white/5 px-2.5 py-1 rounded-full text-[10px] text-white/60 hover:text-white/90 hover:border-white/10 transition-colors cursor-pointer select-none">
            {icon}
            <span>{text}</span>
        </div>
    );
}

export function ActionButton({ icon, label }: { icon: React.ReactNode, label: string }) {
    return (
        <button className="flex items-center gap-1.5 bg-white/5 hover:bg-white/10 border border-white/5 hover:border-white/10 px-3 py-1.5 rounded-full text-[10px] text-white/70 hover:text-white transition-all h-auto">
            {icon}
            <span>{label}</span>
        </button>
    );
}

export function IconButton({ icon }: { icon: React.ReactNode }) {
    return (
        <button className="p-2 hover:bg-white/10 rounded-full transition-colors text-current w-auto h-auto">
            {icon}
        </button>
    );
}

export function AspectRatioSelector({
    aspectRatio,
    isVideo,
    onSelect,
    selectedModelId,
    models,
    resolution
}: {
    aspectRatio: string,
    isVideo: boolean,
    onSelect: (ratio: string) => void,
    selectedModelId?: string,
    models?: Record<string, ModelConfig>,
    resolution?: string
}) {
    const ratios = React.useMemo(() => {
        if (models && selectedModelId && resolution) {
            const model = models[selectedModelId];
            if (model?.resolutions) {
                return getAspectRatiosForResolution(resolution);
            }
        }
        return isVideo ? VIDEO_ASPECT_RATIOS : IMAGE_ASPECT_RATIOS;
    }, [isVideo, models, selectedModelId, resolution]);

    return (
        <Popover>
            <PopoverTrigger asChild>
                <div className="flex items-center gap-1.5 px-2 py-1 rounded-full hover:bg-white/5 cursor-pointer transition-colors text-[10px] font-bold text-muted-foreground hover:text-cyan-400 group">
                    <Scaling size={10} />
                    <span>{aspectRatio}</span>
                    <ChevronDown size={10} className="opacity-50 group-hover:opacity-100 transition-opacity" />
                </div>
            </PopoverTrigger>
            <PopoverContent
                className="w-24 p-1 bg-black/40 backdrop-blur-xl border-white/10 z-[1000] shadow-2xl rounded-xl interaction-model-popover"
                side="top"
                align="center"
                sideOffset={10}
            >
                <div className="flex flex-col gap-0.5">
                    {ratios.map((ratio) => (
                        <div
                            key={ratio}
                            onClick={() => onSelect(ratio)}
                            className={cn(
                                "px-3 py-2 rounded-lg text-[11px] font-medium cursor-pointer transition-all flex items-center justify-between group",
                                aspectRatio === ratio
                                    ? "bg-blue-500/10 text-blue-400"
                                    : "text-foreground/70 hover:bg-white/5 hover:text-foreground"
                            )}
                        >
                            <span>{ratio}</span>
                            {aspectRatio === ratio && <Check size={12} className="text-blue-400 shrink-0 ml-2" />}
                        </div>
                    ))}
                </div>
            </PopoverContent>
        </Popover>
    );
}

export function CountSelector({
    count,
    isVideo,
    onSelect,
    selectedModelId,
    models
}: {
    count: number,
    isVideo: boolean,
    onSelect: (count: number) => void,
    selectedModelId?: string,
    models?: Record<string, ModelConfig>
}) {
    const counts = React.useMemo(() => {
        if (models && selectedModelId) {
            const model = models[selectedModelId];
            if (model?.counts) {
                const { min, max } = model.counts;
                if (min != null && max != null) {
                    const items: number[] = [];
                    for (let i = min; i <= max; i++) items.push(i);
                    return items;
                }
            }
        }
        return isVideo ? VIDEO_COUNTS : IMAGE_COUNTS;
    }, [models, selectedModelId, isVideo]);

    return (
        <Popover>
            <PopoverTrigger asChild>
                <div className="flex items-center gap-1.5 px-2 py-1 rounded-full hover:bg-white/5 cursor-pointer transition-colors text-[10px] font-bold text-muted-foreground hover:text-cyan-400 group">
                    <Layers size={10} />
                    <span>{count}</span>
                    <ChevronDown size={10} className="opacity-50 group-hover:opacity-100 transition-opacity" />
                </div>
            </PopoverTrigger>
            <PopoverContent
                className="w-20 p-1 bg-black/40 backdrop-blur-xl border-white/10 z-[1000] shadow-2xl rounded-xl interaction-model-popover"
                side="top"
                align="center"
                sideOffset={10}
            >
                <div className="flex flex-col gap-0.5">
                    {counts.map((c) => (
                        <div
                            key={c}
                            onClick={() => onSelect(c)}
                            className={cn(
                                "px-3 py-2 rounded-lg text-[11px] font-medium cursor-pointer transition-all flex items-center justify-between group",
                                count === c
                                    ? "bg-blue-500/10 text-blue-400"
                                    : "text-foreground/70 hover:bg-white/5 hover:text-foreground"
                            )}
                        >
                            <span>{c}</span>
                            {count === c && <Check size={12} className="text-blue-400 shrink-0 ml-2" />}
                        </div>
                    ))}
                </div>
            </PopoverContent>
        </Popover>
    );
}

export function ResolutionSelector({
    resolution,
    onSelect,
    selectedModelId,
    models
}: {
    resolution: string,
    onSelect: (res: string) => void,
    selectedModelId?: string,
    models?: Record<string, ModelConfig>
}) {
    const resolutions = React.useMemo(() => {
        if (models && selectedModelId) {
            const model = models[selectedModelId];
            if (model?.resolutions) {
                return getResolutionLevels(selectedModelId);
            }
        }
        return VIDEO_RESOLUTIONS;
    }, [models, selectedModelId]);

    return (
        <Popover>
            <PopoverTrigger asChild>
                <div className="flex items-center gap-1.5 px-2 py-1 rounded-full hover:bg-white/5 cursor-pointer transition-colors text-[10px] font-bold text-muted-foreground hover:text-cyan-400 group">
                    <Monitor size={10} />
                    <span>{resolution}</span>
                    <ChevronDown size={10} className="opacity-50 group-hover:opacity-100 transition-opacity" />
                </div>
            </PopoverTrigger>
            <PopoverContent
                className="w-24 p-1 bg-black/40 backdrop-blur-xl border-white/10 z-[1000] shadow-2xl rounded-xl interaction-model-popover"
                side="top"
                align="center"
                sideOffset={10}
            >
                <div className="flex flex-col gap-0.5">
                    {resolutions.map((res: string) => (
                        <div
                            key={res}
                            onClick={() => onSelect(res)}
                            className={cn(
                                "px-3 py-2 rounded-lg text-[11px] font-medium cursor-pointer transition-all flex items-center justify-between group",
                                resolution === res
                                    ? "bg-blue-500/10 text-blue-400"
                                    : "text-foreground/70 hover:bg-white/5 hover:text-foreground"
                            )}
                        >
                            <span>{res}</span>
                            {resolution === res && <Check size={12} className="text-blue-400 shrink-0 ml-2" />}
                        </div>
                    ))}
                </div>
            </PopoverContent>
        </Popover>
    );
}

export function ImageResolutionSelector({
    resolution,
    onSelect,
    selectedModelId,
    models
}: {
    resolution: string,
    onSelect: (res: string) => void,
    selectedModelId?: string,
    models?: Record<string, ModelConfig>
}) {
    const resolutions = React.useMemo(() => {
        if (models && selectedModelId) {
            const model = models[selectedModelId];
            if (model?.resolutions) {
                return getResolutionLevels(selectedModelId);
            }
        }
        return IMAGE_RESOLUTIONS;
    }, [models, selectedModelId]);

    return (
        <Popover>
            <PopoverTrigger asChild>
                <div className="flex items-center gap-1.5 px-2 py-1 rounded-full hover:bg-white/5 cursor-pointer transition-colors text-[10px] font-bold text-muted-foreground hover:text-cyan-400 group">
                    <ImageIcon size={10} aria-hidden />
                    <span>{resolution}</span>
                    <ChevronDown size={10} className="opacity-50 group-hover:opacity-100 transition-opacity" />
                </div>
            </PopoverTrigger>
            <PopoverContent
                className="w-24 p-1 bg-black/40 backdrop-blur-xl border-white/10 z-[1000] shadow-2xl rounded-xl interaction-model-popover"
                side="top"
                align="center"
                sideOffset={10}
            >
                <div className="flex flex-col gap-0.5">
                    {resolutions.map((res: string) => (
                        <div
                            key={res}
                            onClick={() => onSelect(res)}
                            className={cn(
                                "px-3 py-2 rounded-lg text-[11px] font-medium cursor-pointer transition-all flex items-center justify-between group",
                                resolution === res
                                    ? "bg-blue-500/10 text-blue-400"
                                    : "text-foreground/70 hover:bg-white/5 hover:text-foreground"
                            )}
                        >
                            <span>{res}</span>
                            {resolution === res && <Check size={12} className="text-blue-400 shrink-0 ml-2" />}
                        </div>
                    ))}
                </div>
            </PopoverContent>
        </Popover>
    );
}

export function DurationSelector({
    duration,
    onSelect,
    selectedModelId,
    models
}: {
    duration: string,
    onSelect: (dur: string) => void,
    selectedModelId?: string,
    models?: Record<string, ModelConfig>
}) {
    const { config: videoConfig } = useVideoGenerationOptions();

    const durations = React.useMemo(() => {
        if (models && selectedModelId) {
            const model = models[selectedModelId];
            if (model?.durations) {
                const cfg = model.durations;

                if (cfg.values && Array.isArray(cfg.values)) {
                    return cfg.values.map((d: number) => `${d}s`);
                }

                if (cfg.min != null && cfg.max != null) {
                    const items: string[] = [];
                    for (let i = cfg.min; i <= cfg.max; i++) {
                        items.push(`${i}s`);
                    }
                    return items;
                }

                if (Array.isArray(cfg)) {
                    return cfg.map((d: string | number) => String(d).endsWith('s') ? String(d) : `${d}s`);
                }
            }
        }

        // 默认值
        return ['5s', '10s', '15s'];
    }, [models, selectedModelId, videoConfig]);

    return (
        <Popover>
            <PopoverTrigger asChild>
                <div className="flex items-center gap-1.5 px-2 py-1 rounded-full hover:bg-white/5 cursor-pointer transition-colors text-[10px] font-bold text-muted-foreground hover:text-cyan-400 group">
                    <Clock size={10} />
                    <span>{duration}</span>
                    <ChevronDown size={10} className="opacity-50 group-hover:opacity-100 transition-opacity" />
                </div>
            </PopoverTrigger>
            <PopoverContent
                className="w-20 p-1 bg-black/40 backdrop-blur-xl border-white/10 z-[1000] shadow-2xl rounded-xl interaction-model-popover"
                side="top"
                align="center"
                sideOffset={10}
            >
                <div className="flex flex-col gap-0.5 max-h-48 overflow-y-auto custom-scrollbar">
                    {durations.map((dur: string) => (
                        <div
                            key={dur}
                            onClick={() => onSelect(dur)}
                            className={cn(
                                "px-3 py-2 rounded-lg text-[11px] font-medium cursor-pointer transition-all flex items-center justify-between group",
                                duration === dur
                                    ? "bg-blue-500/10 text-blue-400"
                                    : "text-foreground/70 hover:bg-white/5 hover:text-foreground"
                            )}
                        >
                            <span>{dur}</span>
                            {duration === dur && <Check size={12} className="text-blue-400 shrink-0 ml-2" />}
                        </div>
                    ))}
                </div>
            </PopoverContent>
        </Popover>
    );
}

const CAMERA_CONTROLS = [
    { value: 'none', label: '自动' },
    { value: 'down_back', label: '下压后退' },
    { value: 'forward_up', label: '推进上仰' },
    { value: 'right_turn_forward', label: '右旋推进' },
    { value: 'left_turn_forward', label: '左旋推进' },
];

export function CameraControlSelector({
    cameraControl,
    onSelect
}: {
    cameraControl?: string,
    onSelect: (value: string | undefined) => void
}) {
    const currentLabel = CAMERA_CONTROLS.find(c => c.value === cameraControl)?.label || '运镜';

    return (
        <Popover>
            <PopoverTrigger asChild>
                <div className="flex items-center gap-1.5 px-2 py-1 rounded-full hover:bg-white/5 cursor-pointer transition-colors text-[10px] font-bold text-muted-foreground hover:text-cyan-400 group">
                    <Aperture size={10} />
                    <span>{currentLabel}</span>
                    <ChevronDown size={10} className="opacity-50 group-hover:opacity-100 transition-opacity" />
                </div>
            </PopoverTrigger>
            <PopoverContent
                className="w-28 p-1 bg-black/40 backdrop-blur-xl border-white/10 z-[1000] shadow-2xl rounded-xl interaction-model-popover"
                side="top"
                align="center"
                sideOffset={10}
            >
                <div className="flex flex-col gap-0.5">
                    {CAMERA_CONTROLS.map((opt) => (
                        <div
                            key={opt.value}
                            onClick={() => onSelect(opt.value === 'none' ? undefined : opt.value)}
                            className={cn(
                                "px-3 py-2 rounded-lg text-[11px] font-medium cursor-pointer transition-all flex items-center justify-between group",
                                (cameraControl || 'none') === opt.value
                                    ? "bg-blue-500/10 text-blue-400"
                                    : "text-foreground/70 hover:bg-white/5 hover:text-foreground"
                            )}
                        >
                            <span>{opt.label}</span>
                            {(cameraControl || 'none') === opt.value && <Check size={12} className="text-blue-400 shrink-0 ml-2" />}
                        </div>
                    ))}
                </div>
            </PopoverContent>
        </Popover>
    );
}

export function ShotTypeToggle({
    shotType,
    onToggle
}: {
    shotType?: 'single' | 'multi',
    onToggle: (value: 'single' | 'multi') => void
}) {
    const isMulti = shotType === 'multi';
    return (
        <div
            onClick={() => onToggle(isMulti ? 'single' : 'multi')}
            className="flex items-center gap-1.5 px-2 py-1 rounded-full hover:bg-white/5 cursor-pointer transition-colors text-[10px] font-bold text-muted-foreground hover:text-cyan-400"
            title={isMulti ? '多镜头叙事' : '单镜头'}
        >
            <Film size={10} />
            <span>{isMulti ? '多镜头' : '单镜头'}</span>
        </div>
    );
}

export function AudioToggle({
    enableAudio,
    onToggle
}: {
    enableAudio?: boolean,
    onToggle: (value: boolean) => void
}) {
    const isEnabled = enableAudio !== false;
    return (
        <div
            onClick={() => onToggle(!isEnabled)}
            className="flex items-center gap-1.5 px-2 py-1 rounded-full hover:bg-white/5 cursor-pointer transition-colors text-[10px] font-bold text-muted-foreground hover:text-cyan-400"
            title={isEnabled ? '有声视频' : '无声视频'}
        >
            {isEnabled ? <Volume2 size={10} /> : <VolumeX size={10} />}
            <span>{isEnabled ? '有声' : '静音'}</span>
        </div>
    );
}

export function VoiceSelector({
    voice,
    voices,
    onSelect
}: {
    voice?: string,
    voices: { value: string; label: string; gender?: string; desc?: string }[],
    onSelect: (value: string) => void
}) {
    const currentVoice = voices.find(v => v.value === voice);
    const displayName = currentVoice?.label || '默认音色';

    if (!voices.length) return null;

    return (
        <Popover>
            <PopoverTrigger asChild>
                <div className="flex items-center gap-1.5 px-2 py-1 rounded-full hover:bg-white/5 cursor-pointer transition-colors text-[10px] font-bold text-muted-foreground hover:text-cyan-400 group">
                    <Mic2 size={10} />
                    <span className="truncate max-w-[80px]">{displayName}</span>
                    <ChevronDown size={10} className="opacity-50 group-hover:opacity-100 transition-opacity" />
                </div>
            </PopoverTrigger>
            <PopoverContent
                className="w-44 p-1 bg-black/40 backdrop-blur-xl border-white/10 z-[1000] shadow-2xl rounded-xl interaction-model-popover"
                side="top"
                align="center"
                sideOffset={10}
            >
                <div className="max-h-[280px] overflow-y-auto custom-scrollbar flex flex-col gap-0.5">
                    {voices.map((v) => (
                        <div
                            key={v.value}
                            onClick={() => onSelect(v.value)}
                            className={cn(
                                "px-3 py-2 rounded-lg text-[11px] cursor-pointer transition-all group",
                                voice === v.value
                                    ? "bg-blue-500/10 text-blue-400"
                                    : "text-foreground/70 hover:bg-white/5 hover:text-foreground"
                            )}
                        >
                            <div className="flex items-start justify-between gap-2">
                                <div className="flex-1 min-w-0">
                                    <div className="flex items-center gap-1.5 mb-0.5">
                                        {v.gender && (
                                            <span className="shrink-0 flex items-center justify-center" title={v.gender === '男' || v.gender === 'male' ? '男' : '女'}>
                                                <UserCircle
                                                    size={16}
                                                    className={cn(
                                                        v.gender === '男' || v.gender === 'male'
                                                            ? "text-blue-400"
                                                            : "text-pink-400"
                                                    )}
                                                />
                                            </span>
                                        )}
                                        <span className="font-medium truncate">{v.label}</span>
                                    </div>
                                    {v.desc && (
                                        <p className="text-[9px] text-muted-foreground/60 line-clamp-2 leading-relaxed">
                                            {v.desc}
                                        </p>
                                    )}
                                </div>
                                {voice === v.value && (
                                    <Check size={12} className="text-blue-400 shrink-0 mt-0.5" />
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            </PopoverContent>
        </Popover>
    );
}
