import React, { useEffect, useRef } from 'react';
import { Clapperboard, Check } from 'lucide-react';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import * as Label from '@radix-ui/react-label';
import { Storyboard } from '@/types';
import { InputControl, SelectControl, SelectOption } from '../shared/FormControls';
import { MultiSelectControl } from '../shared/MultiSelectControl';
import { useOptions } from '@lib/hooks/useOptions';
import { Button } from "@/components/ui/button";
import { Textarea } from '@/components/ui/textarea';

const shotSchema = z.object({
    title: z.string().min(1, "请输入镜头标题"),
    type: z.string(),
    duration: z.string(),
    sceneId: z.string().optional(),
    characterIds: z.array(z.string()),
    propIds: z.array(z.string()),
    desc: z.string().optional()
});

type ShotFormValues = z.infer<typeof shotSchema>;

interface CreateShotFormProps {
    onCancelCreate?: () => void;
    onCreateShot?: (shot: Partial<Storyboard>) => void;
    availableScenes: SelectOption[];
    availableCharacters: SelectOption[];
    availableProps: SelectOption[];
    setFooter?: (footer: React.ReactNode) => void;
    isActive?: boolean;
}

export default function CreateShotForm({
    onCancelCreate,
    onCreateShot,
    availableScenes,
    availableCharacters,
    availableProps,
    setFooter,
    isActive = true
}: CreateShotFormProps) {
    const { getOptionsList } = useOptions();
    
    const { control, handleSubmit, reset } = useForm<ShotFormValues>({
        resolver: zodResolver(shotSchema),
        defaultValues: {
            title: '',
            type: '中景',
            duration: '3s',
            sceneId: '',
            characterIds: [],
            propIds: [],
            desc: ''
        }
    });

    // Reset form when mounted
    useEffect(() => {
        reset({
            title: '',
            type: '中景',
            duration: '3s',
            sceneId: '',
            characterIds: [],
            propIds: [],
            desc: ''
        });
    }, [reset]);

    const onSubmit = (data: ShotFormValues) => {
        onCreateShot?.({
            shot: data.title,
            type: data.type,
            duration: data.duration,
            sceneId: data.sceneId,
            characterIds: data.characterIds,
            propIds: data.propIds,
            desc: data.desc
        });
    };

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

    useEffect(() => {
        if (isActive && setFooter) {
            setFooter(
                <Button 
                    className="w-full gap-2 bg-primary hover:bg-primary/90 text-primary-foreground text-[11px] shadow-lg shadow-primary/20"
                    onClick={(e) => submitRef.current(e)}
                >
                    <Check size={14} />
                    <span>创建镜头</span>
                </Button>
            );
        }
    }, [isActive, setFooter]);

    return (
        <section className="h-full flex flex-col">
            <div className="p-6 space-y-6">
                {/* 基础信息 */}
                <div className="space-y-4">
                    <Controller
                        name="title"
                        control={control}
                        render={({ field }) => (
                            <InputControl 
                                label="镜头标题" 
                                placeholder="输入镜头标题..." 
                                {...field}
                            />
                        )}
                    />
                    
                    <div className="grid grid-cols-2 gap-4">
                        <Controller
                            name="type"
                            control={control}
                            render={({ field }) => (
                                <SelectControl 
                                    label="景别" 
                                    options={getOptionsList('shot_types').map(opt => ({ label: opt, value: opt }))}
                                    {...field}
                                />
                            )}
                        />
                         <Controller
                            name="duration"
                            control={control}
                            render={({ field }) => (
                                <InputControl 
                                    label="持续时间" 
                                    placeholder="3s"
                                    {...field}
                                />
                            )}
                        />
                    </div>
                </div>

                {/* 场景信息 */}
                <div className="space-y-4 pt-4 border-t border-border">
                     <div className="flex items-center gap-2 text-muted-foreground mb-2">
                        <Clapperboard size={14} />
                        <span className="text-xs font-semibold uppercase tracking-wider">场景信息</span>
                    </div>
                    
                    <div className="grid grid-cols-3 gap-4">
                        <Controller
                            name="sceneId"
                            control={control}
                            render={({ field }) => (
                                <SelectControl 
                                    label="场景地点" 
                                    options={availableScenes}
                                    {...field}
                                    value={field.value || ''}
                                />
                            )}
                        />
                        
                        <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>

                {/* 画面描述 */}
                <div className="space-y-2 pt-4 border-t border-border">
                    <Label.Root 
                        htmlFor="shot-desc"
                        className="text-xs text-muted-foreground font-medium uppercase tracking-wider block"
                    >
                        画面描述
                    </Label.Root>
                    <Controller
                        name="desc"
                        control={control}
                        render={({ field }) => (
                            <Textarea 
                                id="shot-desc"
                                className="w-full h-32 bg-background border border-border rounded-lg p-3 text-sm text-foreground placeholder-zinc-500 resize-none focus:outline-none focus:border-primary/50 leading-relaxed transition-colors"
                                placeholder="详细描述镜头的画面内容、动作和氛围..."
                                {...field}
                                value={field.value || ''}
                            />
                        )}
                    />
                </div>

                {/* 操作按钮 */}
                {!setFooter && (
                    <div className="pt-6 mt-auto flex justify-end">
                        <Button 
                            className="w-full sm:w-auto min-w-[120px] bg-primary hover:bg-primary/90 text-primary-foreground font-medium shadow-lg shadow-primary/20 gap-2"
                            onClick={handleSubmit(onSubmit)}
                        >
                            <Check size={16} />
                            <span>创建镜头</span>
                        </Button>
                    </div>
                )}
            </div>
        </section>
    );
}
