'use client';

import React, { useEffect, useMemo, useRef } from 'react';
import { Clapperboard, Trash2, Save } from 'lucide-react';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Storyboard, StoryboardId } from '@/types';
import { InputControl, SelectControl, SelectOption, TextareaControl } from '@components/canvas/panels/shared/FormControls';
import { MultiSelectControl } from '@components/canvas/panels/shared/MultiSelectControl';
import { useOptions } from '@lib/hooks/useOptions';
import { useStoryboardOptions, useCinematicOptions } from '@lib/hooks/useGenerationConfig';
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
  } from "@/components/ui/alert-dialog";

const shotInfoSchema = z.object({
    shot: z.string().min(1, "请输入镜头标题"),
    type: z.string(),
    duration: z.string(),
    sceneId: z.string().optional(),
    location: z.string().optional(),
    time: z.string().optional(),
    characterIds: z.array(z.string()),
    propIds: z.array(z.string()),
    cameraMovement: z.string().optional(),
    cameraAngle: z.string().optional(),
    lens: z.string().optional(),
    focus: z.string().optional(),
    lighting: z.string().optional(),
    colorStyle: z.string().optional(),
    transition: z.string().optional(),
    voiceover: z.string().optional(),
    audioDesc: z.string().optional(),
    desc: z.string().optional(),
    originalText: z.string().optional(),
    mergeImagePrompt: z.string().optional(),
    videoPrompt: z.string().optional()
});

type ShotInfoFormValues = z.infer<typeof shotInfoSchema>;

interface ShotInfoTabProps {
    selectedStoryboard: Storyboard;
    onUpdateStoryboard: (id: StoryboardId, updates: Partial<Storyboard>) => void;
    onDeleteStoryboard?: (id: StoryboardId) => void;
    availableScenes: SelectOption[];
    availableCharacters: SelectOption[];
    availableProps: SelectOption[];
    setFooter?: (footer: React.ReactNode) => void;
    isActive?: boolean;
    onClose?: () => void;
}

export default function ShotInfoTab({
    selectedStoryboard,
    onUpdateStoryboard,
    onDeleteStoryboard,
    availableScenes,
    availableCharacters,
    availableProps,
    setFooter,
    isActive,
    onClose
}: ShotInfoTabProps) {
    const { getOptionsList } = useOptions();
    const [showDeleteAlert, setShowDeleteAlert] = React.useState(false);
    // Note: useStoryboardOptions and useCinematicOptions return { config, updateConfig, resetConfig }
    // The config is GenerationConfig type which doesn't have the complex options structure
    // Using API options directly as fallback

    // Get options from API
    const shotTypes = useMemo(() => {
        const apiOptions = getOptionsList('shot_types');
        if (apiOptions.length > 0) return apiOptions.map(s => ({ label: s, value: s }));
        return [];
    }, [getOptionsList]);

    const cameraMovements = useMemo(() => {
        const apiOptions = getOptionsList('camera_movements');
        if (apiOptions.length > 0) return apiOptions.map(s => ({ label: s, value: s }));
        return [];
    }, [getOptionsList]);

    const cameraAngles: { label: string; value: string }[] = [];

    const lenses: { label: string; value: string }[] = [];

    const focusOptions: { label: string; value: string }[] = [];

    const lightingOptions: { label: string; value: string }[] = [];

    const colorStyleOptions: { label: string; value: string }[] = [];

    const transitions = useMemo(() => {
        const apiOptions = getOptionsList('transitions');
        if (apiOptions.length > 0) return apiOptions.map(s => ({ label: s, value: s }));
        return [];
    }, [getOptionsList]);

    const { control, handleSubmit, reset } = useForm<ShotInfoFormValues>({
        resolver: zodResolver(shotInfoSchema),
        defaultValues: {
            shot: selectedStoryboard.shot || '',
            type: selectedStoryboard.type || '',
            duration: selectedStoryboard.duration || '',
            sceneId: selectedStoryboard.sceneId || '',
            location: selectedStoryboard.location || '',
            time: selectedStoryboard.time || '',
            characterIds: selectedStoryboard.characterIds || [],
            propIds: selectedStoryboard.propIds || [],
            cameraMovement: selectedStoryboard.cameraMovement || '',
            cameraAngle: selectedStoryboard.cameraAngle || '',
            lens: selectedStoryboard.lens || '',
            focus: selectedStoryboard.focus || '',
            lighting: selectedStoryboard.lighting || '',
            colorStyle: selectedStoryboard.colorStyle || '',
            transition: selectedStoryboard.transition || '',
            voiceover: selectedStoryboard.voiceover || '',
            audioDesc: selectedStoryboard.audioDesc || '',
            desc: selectedStoryboard.desc || '',
            originalText: selectedStoryboard.originalText || '',
            mergeImagePrompt: selectedStoryboard.mergeImagePrompt || '',
            videoPrompt: selectedStoryboard.videoPrompt || ''
        }
    });

    useEffect(() => {
        reset({
            shot: selectedStoryboard.shot || '',
            type: selectedStoryboard.type || '',
            duration: selectedStoryboard.duration || '',
            sceneId: selectedStoryboard.sceneId || '',
            location: selectedStoryboard.location || '',
            time: selectedStoryboard.time || '',
            characterIds: selectedStoryboard.characterIds || [],
            propIds: selectedStoryboard.propIds || [],
            cameraMovement: selectedStoryboard.cameraMovement || '',
            cameraAngle: selectedStoryboard.cameraAngle || '',
            lens: selectedStoryboard.lens || '',
            focus: selectedStoryboard.focus || '',
            lighting: selectedStoryboard.lighting || '',
            colorStyle: selectedStoryboard.colorStyle || '',
            transition: selectedStoryboard.transition || '',
            voiceover: selectedStoryboard.voiceover || '',
            audioDesc: selectedStoryboard.audioDesc || '',
            desc: selectedStoryboard.desc || '',
            originalText: selectedStoryboard.originalText || '',
            mergeImagePrompt: selectedStoryboard.mergeImagePrompt || '',
            videoPrompt: selectedStoryboard.videoPrompt || ''
        });
    }, [selectedStoryboard, reset]);

    const onSubmit = (data: ShotInfoFormValues) => {
        onUpdateStoryboard(selectedStoryboard.id, data);
        onClose?.();
    };

    const submitRef = useRef(handleSubmit(onSubmit));
    submitRef.current = handleSubmit(onSubmit);

    // Set Footer
    useEffect(() => {
        if (isActive && setFooter) {
            setFooter(
                <div className="flex items-center gap-2 w-full">
                    <Button 
                        onClick={(e) => submitRef.current(e)}
                        className="flex-1 gap-2 bg-primary hover:bg-primary/90 text-primary-foreground text-[11px] shadow-lg shadow-primary/20"
                    >
                        <Save size={14} />
                        <span>保存</span>
                    </Button>
                    {onDeleteStoryboard && (
                        <Button 
                            variant="ghost"
                            size="icon"
                            onClick={() => setShowDeleteAlert(true)}
                            className="bg-destructive/10 hover:bg-destructive/20 text-destructive border border-destructive/20 h-10 w-10"
                            title="删除分镜"
                        >
                            <Trash2 size={16} />
                        </Button>
                    )}
                </div>
            );
        }
    }, [isActive, setFooter, onDeleteStoryboard]);

    return (
        <>
            <AlertDialog open={showDeleteAlert} onOpenChange={setShowDeleteAlert}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>确认删除分镜?</AlertDialogTitle>
                        <AlertDialogDescription>
                            此操作无法撤销。该分镜及其所有生成内容将被永久删除。
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>取消</AlertDialogCancel>
                        <AlertDialogAction onClick={() => {
                            onDeleteStoryboard?.(selectedStoryboard.id);
                            setShowDeleteAlert(false);
                        }} className="bg-destructive hover:bg-destructive/90">
                            删除
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            <Controller
                name="shot"
                control={control}
                render={({ field }) => (
                    <InputControl 
                        label="镜头标题" 
                        {...field}
                    />
                )}
            />
            
            <div className="grid grid-cols-2 gap-2">
                <Controller
                    name="type"
                    control={control}
                    render={({ field }) => (
                        <SelectControl 
                            label="景别" 
                            options={shotTypes} 
                            {...field}
                        />
                    )}
                />
                 <Controller
                    name="duration"
                    control={control}
                    render={({ field }) => (
                        <InputControl 
                            label="持续时间" 
                            {...field}
                        />
                    )}
                />
            </div>

             {/* New Fields */}
            <div className="space-y-2 pt-4 mt-4 border-t border-border">
                 <div className="flex items-center gap-2 text-muted-foreground mb-2">
                    <Clapperboard size={12} />
                    <span className="text-[10px] font-semibold uppercase tracking-wider">场景信息</span>
                </div>
                
                <Controller
                    name="sceneId"
                    control={control}
                    render={({ field }) => (
                        <SelectControl 
                            label="关联场景" 
                            options={availableScenes}
                            {...field}
                            value={field.value || ''}
                        />
                    )}
                />

                <div className="grid grid-cols-2 gap-2">
                    <Controller
                        name="location"
                        control={control}
                        render={({ field }) => (
                            <InputControl 
                                label="建议地点" 
                                {...field}
                                value={field.value || ''}
                                placeholder="原始文本地点"
                            />
                        )}
                    />
                    <Controller
                        name="time"
                        control={control}
                        render={({ field }) => (
                            <InputControl 
                                label="建议时间" 
                                {...field}
                                value={field.value || ''}
                                placeholder="e.g. Day"
                            />
                        )}
                    />
                </div>
                
                <Controller
                    name="characterIds"
                    control={control}
                    render={({ field }) => (
                        <MultiSelectControl 
                            label="登场角色"  
                            options={availableCharacters}
                            selectedValues={field.value}
                            onChange={field.onChange}
                        />
                    )}
                />

                <Controller
                    name="propIds"
                    control={control}
                    render={({ field }) => (
                        <MultiSelectControl 
                            label="相关道具" 
                            options={availableProps}
                            selectedValues={field.value}
                            onChange={field.onChange}
                        />
                    )}
                />
            </div>

            <div className="space-y-2 pt-4 mt-4 border-t border-border">
                <div className="flex items-center gap-2 text-muted-foreground mb-2">
                    <Clapperboard size={12} />
                    <span className="text-[10px] font-semibold uppercase tracking-wider">拍摄控制</span>
                </div>

                <div className="grid grid-cols-2 gap-2">
                    <Controller
                        name="cameraMovement"
                        control={control}
                        render={({ field }) => (
                            <SelectControl 
                                label="运镜方式" 
                                options={cameraMovements}
                                {...field}
                                value={field.value || ''}
                            />
                        )}
                    />
                    <Controller
                        name="cameraAngle"
                        control={control}
                        render={({ field }) => (
                            <SelectControl 
                                label="镜头角度" 
                                options={cameraAngles}
                                {...field}
                                value={field.value || ''}
                            />
                        )}
                    />
                </div>

                <div className="grid grid-cols-2 gap-2">
                    <Controller
                        name="lens"
                        control={control}
                        render={({ field }) => (
                            <SelectControl 
                                label="镜头焦距" 
                                options={lenses}
                                {...field}
                                value={field.value || ''}
                            />
                        )}
                    />
                    <Controller
                        name="focus"
                        control={control}
                        render={({ field }) => (
                            <SelectControl 
                                label="焦点控制" 
                                options={focusOptions}
                                {...field}
                                value={field.value || ''}
                            />
                        )}
                    />
                </div>

                <div className="grid grid-cols-2 gap-2 pt-2">
                    <Controller
                        name="lighting"
                        control={control}
                        render={({ field }) => (
                            <SelectControl 
                                label="灯光风格" 
                                options={lightingOptions}
                                {...field}
                                value={field.value || ''}
                            />
                        )}
                    />
                    <Controller
                        name="colorStyle"
                        control={control}
                        render={({ field }) => (
                            <SelectControl 
                                label="色调氛围" 
                                options={colorStyleOptions}
                                {...field}
                                value={field.value || ''}
                            />
                        )}
                    />
                </div>

                <Controller
                    name="transition"
                    control={control}
                    render={({ field }) => (
                        <SelectControl 
                            label="转场效果" 
                            options={transitions}
                            {...field}
                            value={field.value || ''}
                        />
                    )}
                />
            </div>

            <div className="space-y-2 pt-4 mt-4 border-t border-border">
                <div className="flex items-center gap-2 text-muted-foreground mb-2">
                    <Clapperboard size={12} />
                    <span className="text-[10px] font-semibold uppercase tracking-wider">音频 & 对白</span>
                </div>

                <Controller
                    name="voiceover"
                    control={control}
                    render={({ field }) => (
                        <TextareaControl 
                            label="对白"
                            placeholder="输入对白..."
                            rows={2}
                            {...field}
                            value={field.value || ''}
                        />
                    )}
                />

                <Controller
                    name="audioDesc"
                    control={control}
                    render={({ field }) => (
                        <InputControl 
                            label="音效描述"
                            placeholder="输入音效描述..."
                            {...field}
                            value={field.value || ''}
                        />
                    )}
                />
            </div>

            <div className="space-y-2 pt-4 mt-4 border-t border-border">
                <Controller
                    name="desc"
                    control={control}
                    render={({ field }) => (
                        <TextareaControl 
                            label="画面描述"
                            placeholder="详细描述镜头的画面内容..."
                            rows={4}
                            {...field}
                            value={field.value || ''}
                        />
                    )}
                />
            </div>

            {/* AI Generated Prompts Section */}
            <div className="space-y-3 pt-4 mt-4 border-t border-border">
                <div className="flex items-center gap-2 text-muted-foreground mb-2">
                    <Clapperboard size={12} />
                    <span className="text-[10px] font-semibold uppercase tracking-wider">AI 生成提示词</span>
                </div>

                {/* Original Text */}
                <Controller
                    name="originalText"
                    control={control}
                    render={({ field }) => (
                        <div className="space-y-1.5">
                            <div className="flex items-center gap-2">
                                <label className="text-[10px] text-muted-foreground font-medium uppercase tracking-wider">原文</label>
                                <span className="text-[9px] px-1.5 py-0.5 bg-gray-500/20 text-gray-400 rounded">小说原文</span>
                            </div>
                            <Textarea 
                                placeholder="对应的小说原文..."
                                rows={2}
                                {...field}
                                value={field.value || ''}
                                className="!text-[11px] resize-none min-h-[60px] bg-gray-500/5 border-gray-500/20 font-mono"
                            />
                        </div>
                    )}
                />

                {/* Merge Image Prompt */}
                <Controller
                    name="mergeImagePrompt"
                    control={control}
                    render={({ field }) => (
                        <div className="space-y-1.5">
                            <div className="flex items-center gap-2">
                                <label className="text-[10px] text-muted-foreground font-medium uppercase tracking-wider">融图提示词</label>
                                <span className="text-[9px] px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded">图像生成</span>
                            </div>
                            <Textarea 
                                placeholder="AI 生成的融图提示词（角色+场景+画面）..."
                                rows={3}
                                {...field}
                                value={field.value || ''}
                                className="!text-[11px] resize-none min-h-[80px] bg-blue-500/5 border-blue-500/20 font-mono"
                            />
                        </div>
                    )}
                />

                {/* Video Prompt */}
                <Controller
                    name="videoPrompt"
                    control={control}
                    render={({ field }) => (
                        <div className="space-y-1.5">
                            <div className="flex items-center gap-2">
                                <label className="text-[10px] text-muted-foreground font-medium uppercase tracking-wider">视频提示词</label>
                                <span className="text-[9px] px-1.5 py-0.5 bg-purple-500/20 text-purple-400 rounded">动作描述</span>
                            </div>
                            <Textarea 
                                placeholder="AI 生成的视频提示词（动作、表情、镜头变化）..."
                                rows={3}
                                {...field}
                                value={field.value || ''}
                                className="!text-[11px] resize-none min-h-[80px] bg-purple-500/5 border-purple-500/20 font-mono"
                            />
                        </div>
                    )}
                />
            </div>
        </>
    );
}
