import React, { useState, useEffect, useRef } from 'react';
import { AssetType, Asset } from '@/types';
import { InputControl, SelectControl, TextareaControl } from '../shared/FormControls';
import { useOptions } from '@lib/hooks/useOptions';
import { generateId } from '@/utils';
import { useProjectStore } from '@lib/store/project';
import { Check } from 'lucide-react';
import { Button } from "@/components/ui/button";

interface CreateAssetFormProps {
    creatingAssetType: AssetType;
    onCancelCreate?: () => void;
    onCreateAsset?: (asset: Asset) => void;
    setFooter?: (footer: React.ReactNode) => void;
}

export default function CreateAssetForm({
    creatingAssetType,
    onCancelCreate,
    onCreateAsset,
    setFooter
}: CreateAssetFormProps) {
    const { getOptionsList } = useOptions();
    const projectId = useProjectStore(state => state.id);

    // Form State
    const [name, setName] = useState('');
    const [desc, setDesc] = useState('');
    const [tags, setTags] = useState('');
    
    // Character specific
    const [age, setAge] = useState('');
    const [gender, setGender] = useState('');
    const [role, setRole] = useState('');
    const [appearance, setAppearance] = useState('');

    // Scene specific
    const [location, setLocation] = useState('');
    const [timeOfDay, setTimeOfDay] = useState('');
    const [atmosphere, setAtmosphere] = useState('');

    // Prop specific
    const [usage, setUsage] = useState('');

    const handleCreate = () => {
        if (!onCreateAsset || !projectId) return;
        if (!name) {
            alert('请输入名称');
            return;
        }

        const baseAsset = {
            id: generateId(),
            projectId,
            name,
            desc,
            type: creatingAssetType,
            tags: tags.split(/[,，]\s*/).filter(Boolean),
            createdAt: Date.now(),
            updatedAt: Date.now(),
        };

        let newAsset: Asset;

        if (creatingAssetType === 'character') {
            newAsset = {
                ...baseAsset,
                age,
                gender: gender as any,
                role: role as any,
                appearance,
                imageUrls: []
            } as Asset;
        } else if (creatingAssetType === 'scene') {
            newAsset = {
                ...baseAsset,
                location,
                timeOfDay,
                atmosphere,
                imageUrls: []
            } as Asset;
        } else if (creatingAssetType === 'prop') {
            newAsset = {
                ...baseAsset,
                usage,
                imageUrls: []
            } as Asset;
        } else {
            newAsset = {
                ...baseAsset,
                imageUrls: []
            } as Asset;
        }

        onCreateAsset(newAsset);
    };

    const handleCreateRef = useRef(handleCreate);
    useEffect(() => {
        handleCreateRef.current = handleCreate;
    });

    // Set Footer
    useEffect(() => {
        if (setFooter) {
            setFooter(
                <Button 
                    onClick={() => handleCreateRef.current()}
                    disabled={!name}
                    className={`w-full bg-blue-600 hover:bg-blue-500 text-white text-[11px] font-bold shadow-lg shadow-blue-900/20 gap-2 ${!name ? 'opacity-50 cursor-not-allowed' : ''}`}
                >
                    <Check size={14} />
                    <span>创建素材</span>
                </Button>
            );
        }
    }, [setFooter, name]); // Dependencies for footer

    return (
        <div className="space-y-6 p-1">
            {/* 基础信息 */}
            <div className="space-y-4">
                <InputControl 
                    label="名称" 
                    placeholder="输入名称..." 
                    value={name}
                    onChange={setName}
                />

                {creatingAssetType === 'character' && (
                     <div className="space-y-4 animate-in fade-in slide-in-from-top-2 duration-300">
                        <div className="flex items-center gap-2 text-muted-foreground pt-2 border-t border-border">
                            <span className="text-xs font-semibold uppercase tracking-wider">角色信息</span>
                        </div>
                        
                        <div className="grid grid-cols-2 gap-4">
                            <InputControl 
                                label="年龄" 
                                placeholder="例如：18岁" 
                                value={age}
                                onChange={setAge}
                            />
                            <SelectControl 
                                label="性别" 
                                options={getOptionsList('character_genders').map(opt => ({ label: opt, value: opt }))}
                                value={gender} 
                                onChange={setGender}
                            />
                        </div>
                        <SelectControl 
                            label="角色定位" 
                            options={getOptionsList('character_roles').map(opt => ({ label: opt, value: opt }))}
                            value={role} 
                            onChange={setRole}
                        />
                        <div className="space-y-2">
                            <label className="text-xs text-muted-foreground font-medium uppercase tracking-wider block">外貌特征</label>
                            <textarea 
                                className="w-full h-24 bg-background border border-border rounded-lg p-3 text-sm text-foreground placeholder-zinc-500 resize-none focus:outline-none focus:border-blue-500/50 leading-relaxed transition-colors"
                                placeholder="描述角色的外貌特征..."
                                value={appearance}
                                onChange={(e) => setAppearance(e.target.value)}
                            />
                        </div>
                     </div>
                )}
                 {creatingAssetType === 'scene' && (
                     <div className="space-y-4 animate-in fade-in slide-in-from-top-2 duration-300">
                        <div className="flex items-center gap-2 text-muted-foreground pt-2 border-t border-border">
                            <span className="text-xs font-semibold uppercase tracking-wider">场景信息</span>
                        </div>

                        <InputControl 
                            label="地点" 
                            placeholder="例如：教学楼" 
                            value={location}
                            onChange={setLocation}
                        />
                        <div className="grid grid-cols-2 gap-4">
                            <InputControl 
                                label="时间" 
                                placeholder="例如：下午" 
                                value={timeOfDay}
                                onChange={setTimeOfDay}
                            />
                            <InputControl 
                                label="氛围" 
                                placeholder="例如：安静" 
                                value={atmosphere}
                                onChange={setAtmosphere}
                            />
                        </div>
                     </div>
                )}
                {creatingAssetType === 'prop' && (
                     <div className="space-y-4 animate-in fade-in slide-in-from-top-2 duration-300">
                        <div className="flex items-center gap-2 text-muted-foreground pt-2 border-t border-border">
                            <span className="text-xs font-semibold uppercase tracking-wider">道具信息</span>
                        </div>
                        <InputControl 
                            label="用途" 
                            placeholder="例如：佩戴" 
                            value={usage}
                            onChange={setUsage}
                        />
                     </div>
                )}

                <div className="space-y-2 pt-4 border-t border-border">
                    <label className="text-xs text-muted-foreground font-medium uppercase tracking-wider block">详细描述</label>
                    <textarea 
                        className="w-full h-24 bg-background border border-border rounded-lg p-3 text-sm text-foreground placeholder-zinc-500 resize-none focus:outline-none focus:border-blue-500/50 leading-relaxed transition-colors"
                        placeholder="输入详细描述..."
                        value={desc}
                        onChange={(e) => setDesc(e.target.value)}
                    />
                </div>

                <InputControl 
                    label="标签 (逗号分隔)" 
                    placeholder="例如：主角, 高中生" 
                    value={tags}
                    onChange={setTags}
                />
            </div>

            {!setFooter && (
                <div className="pt-6 mt-auto flex justify-end border-t border-border">
                    <Button 
                        onClick={handleCreate}
                        disabled={!name}
                        className={`w-full sm:w-auto min-w-[120px] bg-blue-600 hover:bg-blue-500 text-white font-medium shadow-lg shadow-blue-900/20 gap-2 ${!name ? 'opacity-50 cursor-not-allowed' : ''}`}
                    >
                        <Check size={16} />
                        <span>创建素材</span>
                    </Button>
                </div>
            )}
        </div>
    );
}
