import React, { memo, useMemo, useState } from 'react';
import { Plus, History, BookOpen, Wand2, ArrowRight, Loader2, X } from 'lucide-react';
import { Button } from "@/components/ui/button";
import { cn } from '@/utils';
import { ActionButton, IconButton } from './Selectors';
import { GenerationSettings, GenerationType } from './types';
import { 
    ModelSelector, ResolutionSelector, ImageResolutionSelector, AspectRatioSelector, 
    DurationSelector, CountSelector, StyleSelector,
    CameraControlSelector, ShotTypeToggle, AudioToggle, VoiceSelector
} from './Selectors';
import { useStyles } from '@lib/hooks/useConfig';
import { StyleConfig } from '@/types';
import type { ModelConfig } from '@/types/model';

interface InputFooterProps {
    isGenerating: boolean;
    canGenerate: boolean;
    onGenerate: () => void;
    /** 当前任务 ID（仅编辑态生图/生视频时有），用于取消 */
    currentTaskId?: string;
    /** 取消当前任务（仅当 currentTaskId 存在时有效） */
    onCancel?: () => void;
    activeTab: GenerationType;
    settings: GenerationSettings;
    availableModels: Record<string, any>;
    lyricsModels?: Record<string, ModelConfig>;
    musicModels?: Record<string, ModelConfig>;
    onUpdateSettings: (s: GenerationSettings) => void;
    isEditMode?: boolean;
    editNodeType?: string;
}

export const InputFooter = memo(({ 
    isGenerating, canGenerate, onGenerate,
    currentTaskId, onCancel,
    activeTab, settings, availableModels, onUpdateSettings,
    lyricsModels = {}, musicModels = {},
    isEditMode = false, editNodeType
}: InputFooterProps) => {
    const isVideo = activeTab === 'video';
    const isAudio = activeTab === 'audio';
    const isMusic = activeTab === 'music';
    const isImage = activeTab === 'image';
    const { data: stylesData } = useStyles();
    const styles = (stylesData?.styles || []) as StyleConfig[];

    // Get current model config for capability-based controls
    const currentModelConfig = useMemo(() => {
        if (!settings.model || !availableModels) return null;
        return availableModels[settings.model];
    }, [settings.model, availableModels]);

    const capabilities = currentModelConfig?.capabilities;
    const [isHoveringCancel, setIsHoveringCancel] = useState(false);
    const showCancelOnHover = isGenerating && currentTaskId;

    // Get voices for audio models
    const voices = useMemo(() => {
        if (!isAudio || !currentModelConfig?.voices) return [];
        return (currentModelConfig.voices as any[]).map((v: any) => ({
            value: v.value || v.id,
            label: v.label || v.name || v.value || v.id,
            gender: v.gender,
            desc: v.desc
        }));
    }, [isAudio, currentModelConfig]);

    return (
        <div className="mt-auto flex items-center justify-between pt-2">
            {/* Left: Parameters - Expanded view contains ALL parameters */}
            <div className="flex items-center gap-2">
                {isMusic && !isEditMode ? (
                    <>
                        <div className="flex items-center gap-1">
                            <span
                                onClick={() => {
                                    const nextLyrics = !(settings.musicGenerateLyrics ?? false);
                                    const currentMusic = settings.musicGenerateMusic ?? true;
                                    if (!nextLyrics && !currentMusic) return;
                                    onUpdateSettings({
                                        ...settings,
                                        musicGenerateLyrics: nextLyrics,
                                        model: currentMusic
                                            ? (settings.musicModel || settings.model)
                                            : (settings.lyricsModel || settings.model),
                                    });
                                }}
                                className={cn(
                                    "text-[10px] px-2 py-1 rounded-full cursor-pointer transition-colors",
                                    (settings.musicGenerateLyrics ?? false)
                                        ? "bg-cyan-500/20 text-cyan-300 border border-cyan-500/30"
                                        : "text-muted-foreground hover:text-foreground hover:bg-white/5 border border-transparent"
                                )}
                            >
                                歌词
                            </span>
                            <ModelSelector
                                selectedModelId={settings.lyricsModel || ''}
                                models={lyricsModels}
                                onSelect={(id) => onUpdateSettings({
                                    ...settings,
                                    lyricsModel: id,
                                    musicGenerateLyrics: true,
                                    musicGenerateMusic: false,
                                    model: id
                                })}
                            />
                        </div>
                        <div className="flex items-center gap-1">
                            <span
                                onClick={() => {
                                    const currentLyrics = settings.musicGenerateLyrics ?? false;
                                    const nextMusic = !(settings.musicGenerateMusic ?? true);
                                    if (!currentLyrics && !nextMusic) return;
                                    onUpdateSettings({
                                        ...settings,
                                        musicGenerateMusic: nextMusic,
                                        model: nextMusic
                                            ? (settings.musicModel || settings.model)
                                            : (settings.lyricsModel || settings.model),
                                    });
                                }}
                                className={cn(
                                    "text-[10px] px-2 py-1 rounded-full cursor-pointer transition-colors",
                                    (settings.musicGenerateMusic ?? true)
                                        ? "bg-cyan-500/20 text-cyan-300 border border-cyan-500/30"
                                        : "text-muted-foreground hover:text-foreground hover:bg-white/5 border border-transparent"
                                )}
                            >
                                歌曲
                            </span>
                            <ModelSelector
                                selectedModelId={settings.musicModel || ''}
                                models={musicModels}
                                onSelect={(id) => onUpdateSettings({
                                    ...settings,
                                    musicModel: id,
                                    musicGenerateMusic: true,
                                    musicGenerateLyrics: false,
                                    model: id
                                })}
                            />
                        </div>
                    </>
                ) : (
                    <>
                        <ModelSelector
                            selectedModelId={settings.model}
                            models={availableModels}
                            onSelect={(id) => onUpdateSettings({ ...settings, model: id })}
                        />
                        <div className="h-4 w-[1px] bg-white/10 mx-1" />
                    </>
                )}
                
                {/* Image-specific controls: Resolution, Aspect Ratio, Style */}
                {isImage && (
                    <>
                        <ImageResolutionSelector 
                            resolution={settings.resolution || '1K'} 
                            onSelect={(r) => onUpdateSettings({ ...settings, resolution: r })} 
                            selectedModelId={settings.model}
                            models={availableModels}
                        />
                        <AspectRatioSelector 
                            aspectRatio={settings.aspectRatio} 
                            isVideo={false} 
                            onSelect={(r) => onUpdateSettings({ ...settings, aspectRatio: r })} 
                            selectedModelId={settings.model}
                            models={availableModels}
                            resolution={settings.resolution}
                        />
                        <StyleSelector 
                            selectedStyleId={settings.styleId}
                            styles={styles}
                            onSelect={(id) => onUpdateSettings({ ...settings, styleId: id || undefined })}
                            selectedModelId={settings.model}
                            models={availableModels}
                        />
                    </>
                )}

                {/* Video-specific controls: Resolution, Aspect Ratio, Duration */}
                {isVideo && (
                    <>
                        <ResolutionSelector 
                            resolution={settings.resolution} 
                            onSelect={(r) => onUpdateSettings({ ...settings, resolution: r })} 
                            selectedModelId={settings.model}
                            models={availableModels}
                        />
                        <AspectRatioSelector 
                            aspectRatio={settings.aspectRatio} 
                            isVideo={true} 
                            onSelect={(r) => onUpdateSettings({ ...settings, aspectRatio: r })} 
                            selectedModelId={settings.model}
                            models={availableModels}
                            resolution={settings.resolution}
                        />
                        <DurationSelector 
                            duration={settings.duration} 
                            onSelect={(d) => onUpdateSettings({ ...settings, duration: d })} 
                            selectedModelId={settings.model}
                            models={availableModels}
                        />
                    </>
                )}

                {/* Capability-based dynamic controls (video only) */}
                {isVideo && capabilities?.supportsCameraControl && (
                    <CameraControlSelector
                        cameraControl={settings.cameraControl}
                        onSelect={(v) => onUpdateSettings({ ...settings, cameraControl: v })}
                    />
                )}
                {isVideo && capabilities?.supportsShotType && (
                    <ShotTypeToggle
                        shotType={settings.shotType}
                        onToggle={(v) => onUpdateSettings({ ...settings, shotType: v })}
                    />
                )}
                {isVideo && capabilities?.supportsAudio && (
                    <AudioToggle
                        enableAudio={settings.enableAudio}
                        onToggle={(v) => onUpdateSettings({ ...settings, enableAudio: v })}
                    />
                )}

                {/* Audio-specific: voice selector */}
                {isAudio && voices.length > 0 && (
                    <VoiceSelector
                        voice={settings.voice}
                        voices={voices}
                        onSelect={(v) => onUpdateSettings({ ...settings, voice: v })}
                    />
                )}

                {isMusic && (
                    <span className="text-[10px] text-muted-foreground px-2">
                        当前模式：
                        {(settings.musicGenerateLyrics ?? false) && (settings.musicGenerateMusic ?? true)
                            ? '歌词 -> 音乐'
                            : (settings.musicGenerateLyrics ?? false)
                                ? '仅歌词'
                                : '仅音乐'}
                    </span>
                )}

                {(isImage || isVideo) && (
                    <CountSelector 
                        count={settings.count} 
                        isVideo={isVideo} 
                        onSelect={(c) => onUpdateSettings({ ...settings, count: c })} 
                        selectedModelId={settings.model}
                        models={availableModels}
                    />
                )}
            </div>

            {/* Right: Actions */}
            <div className="flex items-center gap-2">
                <div className="flex items-center gap-1 mr-2 text-foreground/40">
                    <IconButton icon={<Wand2 className="w-4 h-4" />} />
                </div>
                
                <Button 
                    onClick={isGenerating && currentTaskId ? onCancel : onGenerate}
                    disabled={!canGenerate && !(isGenerating && currentTaskId)}
                    title={isGenerating && currentTaskId ? '取消' : undefined}
                    onMouseEnter={() => showCancelOnHover && setIsHoveringCancel(true)}
                    onMouseLeave={() => setIsHoveringCancel(false)}
                    className="bg-white/10 hover:bg-white/20 text-foreground border-none w-8 h-8 rounded-full p-0 flex items-center justify-center transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    {isGenerating && currentTaskId && isHoveringCancel ? (
                        <X className="w-4 h-4" />
                    ) : isGenerating ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                        <ArrowRight className="w-4 h-4" />
                    )}
                </Button>
            </div>
        </div>
    );
});

InputFooter.displayName = 'InputFooter';
