'use client';

import React, { useEffect, useState, useMemo } from 'react';
import { Trash2, Save } from 'lucide-react';
import { Asset, CharacterAsset, SceneAsset, PropAsset, AudioAsset } from '@/types';
import { InputControl, SelectControl, TextareaControl } from '@components/canvas/panels/shared/FormControls';
import { useOptions } from '@lib/hooks/useOptions';
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { useConfirm } from '@/components/ui/confirm-dialog';

// Fallback options
const DEFAULT_GENDERS = ["男", "女", "未知"].map(s => ({ label: s, value: s }));
const DEFAULT_ROLES = ["主角", "配角", "反派", "龙套", "群演"].map(s => ({ label: s, value: s }));

interface AssetInfoTabProps {
    selectedAsset: Asset;
    onUpdateAsset: (id: string, updates: Partial<Asset>) => void;
    onDeleteAsset?: (id: string) => void;
    setFooter?: (footer: React.ReactNode) => void;
    onClose?: () => void;
    isActive?: boolean;
}

export default function AssetInfoTab({
    selectedAsset,
    onUpdateAsset,
    onDeleteAsset,
    setFooter,
    onClose,
    isActive
}: AssetInfoTabProps) {
    const { getOptionsList } = useOptions();
    const { confirm, ConfirmDialog } = useConfirm();

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

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

    const emotionOptions: { label: string; value: string }[] = [];
    const environmentTypeOptions: { label: string; value: string }[] = [];
    const weatherOptions: { label: string; value: string }[] = [];
    const timeOfDayOptions: { label: string; value: string }[] = [];

    // Set Footer
    useEffect(() => {
        if (isActive && setFooter) {
            setFooter(
                <div className="flex items-center gap-2 w-full">
                    <Button 
                        onClick={() => onClose?.()}
                        className="flex-1 py-2 bg-blue-600 hover:bg-blue-500 text-white text-[11px] font-bold rounded-lg transition-colors shadow-lg shadow-blue-900/20 flex items-center justify-center gap-2"
                    >
                        <Save size={14} />
                        <span>保存</span>
                    </Button>
                    {onDeleteAsset && (
                        <Button 
                            variant="ghost"
                            size="icon"
                            onClick={() => {
                                confirm({
                                    title: '确认删除？',
                                    description: '确定要删除这个素材吗？此操作无法撤销。',
                                    variant: 'destructive',
                                    onConfirm: () => onDeleteAsset(selectedAsset.id)
                                });
                            }}
                            className="p-2 bg-red-500/10 hover:bg-red-500/20 text-red-500 rounded-lg transition-colors border border-red-500/20"
                            title="删除素材"
                        >
                            <Trash2 size={16} />
                        </Button>
                    )}
                </div>
            );
        }
    }, [isActive, setFooter, onDeleteAsset, selectedAsset.id, onClose, confirm]);

    return (
        <>
        <ConfirmDialog />
        <div className="space-y-3">
            <InputControl 
                label="名称" 
                value={selectedAsset.name} 
                onChange={(v) => onUpdateAsset(selectedAsset.id, { name: v })}
            />

            {selectedAsset.type === 'character' && (
                 <>
                    <div className="grid grid-cols-2 gap-2">
                        <InputControl 
                            label="年龄" 
                            value={(selectedAsset as CharacterAsset).age || ''} 
                            onChange={(v) => onUpdateAsset(selectedAsset.id, { age: v } as Partial<CharacterAsset>)}
                        />
                        <SelectControl 
                            label="性别" 
                            options={genderOptions}
                            value={(selectedAsset as CharacterAsset).gender || ''} 
                            onChange={(v) => onUpdateAsset(selectedAsset.id, { gender: v } as Partial<CharacterAsset>)}
                        />
                    </div>
                    <div className="grid grid-cols-2 gap-2">
                        <SelectControl 
                            label="角色定位" 
                            options={roleOptions}
                            value={(selectedAsset as CharacterAsset).role || ''} 
                            onChange={(v) => onUpdateAsset(selectedAsset.id, { role: v } as Partial<CharacterAsset>)}
                        />
                        <SelectControl 
                            label="情绪基调" 
                            options={emotionOptions}
                            value={(selectedAsset as CharacterAsset).emotion || ''} 
                            onChange={(v) => onUpdateAsset(selectedAsset.id, { emotion: v } as Partial<CharacterAsset>)}
                        />
                    </div>
                    <div className="space-y-1.5">
                        <TextareaControl
                            label="外貌特征"
                            value={(selectedAsset as CharacterAsset).appearance || ''} 
                            onChange={(v) => onUpdateAsset(selectedAsset.id, { appearance: v } as Partial<CharacterAsset>)}
                            rows={3}
                        />
                    </div>
                 </>
            )}
             {selectedAsset.type === 'scene' && (
                 <>
                    <InputControl 
                        label="地点" 
                        value={(selectedAsset as SceneAsset).location || ''} 
                        onChange={(v) => onUpdateAsset(selectedAsset.id, { location: v } as Partial<SceneAsset>)}
                    />
                    <div className="grid grid-cols-2 gap-2">
                        <SelectControl 
                            label="空间类型" 
                            options={environmentTypeOptions}
                            value={(selectedAsset as SceneAsset).environmentType || ''} 
                            onChange={(v) => onUpdateAsset(selectedAsset.id, { environmentType: v } as Partial<SceneAsset>)}
                        />
                        <SelectControl 
                            label="拍摄时段" 
                            options={timeOfDayOptions}
                            value={(selectedAsset as SceneAsset).timeOfDay || ''} 
                            onChange={(v) => onUpdateAsset(selectedAsset.id, { timeOfDay: v } as Partial<SceneAsset>)}
                        />
                    </div>
                    <div className="grid grid-cols-2 gap-2">
                        <SelectControl 
                            label="天气环境" 
                            options={weatherOptions}
                            value={(selectedAsset as SceneAsset).weather || ''} 
                            onChange={(v) => onUpdateAsset(selectedAsset.id, { weather: v } as Partial<SceneAsset>)}
                        />
                        <InputControl 
                            label="氛围" 
                            value={(selectedAsset as SceneAsset).atmosphere || ''} 
                            onChange={(v) => onUpdateAsset(selectedAsset.id, { atmosphere: v } as Partial<SceneAsset>)}
                        />
                    </div>
                 </>
            )}
            {selectedAsset.type === 'prop' && (
                 <>
                    <InputControl 
                        label="用途" 
                        value={(selectedAsset as PropAsset).usage || ''} 
                        onChange={(v) => onUpdateAsset(selectedAsset.id, { usage: v } as Partial<PropAsset>)}
                    />
                 </>
            )}
            {selectedAsset.type === 'audio' && (
                 <>
                    <InputControl 
                        label="时长 (秒)" 
                        type="number"
                        value={(selectedAsset as AudioAsset).duration?.toString() || ''} 
                        onChange={(v) => onUpdateAsset(selectedAsset.id, { duration: Number(v) } as Partial<AudioAsset>)}
                    />
                 </>
            )}

            <div className="space-y-1.5">
                <label className="text-[10px] text-muted-foreground font-medium uppercase tracking-wider">描述</label>
                <Textarea 
                    className="w-full h-32 bg-background border border-border rounded-lg p-3 !text-[11px] text-foreground placeholder-zinc-700 resize-none focus:outline-none focus:border-blue-500/50 leading-relaxed"
                    value={selectedAsset.desc}
                    onChange={(e) => onUpdateAsset(selectedAsset.id, { desc: e.target.value })}
                />
            </div>

            {/* AI Generated Image Prompt */}
            {(selectedAsset.type === 'character' || selectedAsset.type === 'scene' || selectedAsset.type === 'prop') && (
                <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">AI 生图提示词</label>
                        {(selectedAsset.type === 'character' || selectedAsset.type === 'prop') && (
                            <span className="text-[9px] px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded">白底图</span>
                        )}
                        {selectedAsset.type === 'scene' && (
                            <span className="text-[9px] px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded">纯场景</span>
                        )}
                    </div>
                    <Textarea 
                        className="w-full h-24 bg-blue-500/5 border border-blue-500/20 rounded-lg p-3 !text-[11px] text-foreground placeholder-zinc-700 resize-none focus:outline-none focus:border-blue-500/50 leading-relaxed font-mono"
                        value={(selectedAsset as CharacterAsset | SceneAsset | PropAsset).imagePrompt || ''}
                        onChange={(e) => onUpdateAsset(selectedAsset.id, { imagePrompt: e.target.value } as Partial<Asset>)}
                        placeholder="AI 自动生成的图像提示词..."
                    />
                </div>
            )}

            <InputControl 
                label="标签 (逗号分隔)" 
                value={selectedAsset.tags.join("，")} 
                onChange={(v) => onUpdateAsset(selectedAsset.id, { tags: v.split(/[,，]\s*/).filter(Boolean) })}
            />
        </div>
        </>
    );
}
