'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { Trash2, Save, Box, LockKeyhole, Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { ProviderIcon } from "@/components/common/ProviderIcon";
import { DefaultService } from "@/lib/api";
import { cn } from '@/utils';

// 简单的辅助函数：首字母大写
const capitalize = (s: string) => s ? s.charAt(0).toUpperCase() + s.slice(1) : '';
import { InputControl, IconSelectControl, SelectControl } from '@/components/canvas/panels/shared/FormControls';
import { ViewDisplayControl } from '@/components/common/ViewDisplayControl';
import { CreateItemControl } from '@/components/common/CreateItemControl';
import { SearchInput } from '@/components/ui/search-input';
import { EmptyState } from '@/components/ui/empty-state';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useConfirm } from '@/components/ui/confirm-dialog';
import { StringListEditor, KeyValueEditor } from './ModelEditors';
import { useModelStore } from '@/lib/store/modelStore';

interface ModelsTabProps {
    models: any[];
    availableModels?: any[];
    configuredProviders: Set<string>;
    config: any;
    setConfig: (config: any) => void;
    onNavigateToKeys?: () => void;
    onRefreshModels: () => void;
    onSave: () => void;
    saving: boolean;
    onModelAdded?: (model: any) => void;
}

export const ModelsTab: React.FC<ModelsTabProps> = ({
    models,
    availableModels = [],
    configuredProviders,
    config,
    setConfig,
    onNavigateToKeys,
    onRefreshModels,
    onSave,
    saving: parentSaving,
    onModelAdded
}) => {
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [editingModel, setEditingModel] = useState<any | null>(null);
    const [saving, setSaving] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');
    const [activeTab, setActiveTab] = useState<'all' | 'image' | 'video' | 'audio' | 'lyrics' | 'llm' | 'music'>('all');
    const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
    const [gridCols, setGridCols] = useState<number>(4);
    const [listCols, setListCols] = useState<number>(1);
    
    // Use store for providers to avoid redundant fetches
    const { providers, fetchProviders } = useModelStore();

    const currentCols = viewMode === 'grid' ? gridCols : listCols;
    const { confirm, ConfirmDialog } = useConfirm();
    const configuredProviderIds = useMemo(() => Array.from(configuredProviders), [configuredProviders]);

    useEffect(() => {
        fetchProviders();
    }, [fetchProviders]);

    // Filtered models based on search, tab, and configured API keys
    const filteredModels = useMemo(() => {
        return models.filter(model => {
            // Only show models whose provider has a configured API key
            const providerConfigured = configuredProviders.has(model.provider);
            const matchesSearch = (model.name?.toLowerCase() || '').includes(searchQuery.toLowerCase()) ||
                (model.id?.toLowerCase() || '').includes(searchQuery.toLowerCase());
            const matchesTab = activeTab === 'all' ||
                model.type === activeTab ||
                model.type === `${activeTab}_generation`;
            return providerConfigured && matchesSearch && matchesTab;
        });
    }, [models, configuredProviders, searchQuery, activeTab]);

    const availableModelCount = useMemo(() => {
        return availableModels.filter((model) => model.provider && configuredProviders.has(model.provider)).length;
    }, [availableModels, configuredProviders]);

    // Initialize empty model for creation
    const getEmptyModel = () => ({
        name: "",
        model_id: "",
        provider: configuredProviderIds[0] || "",
        type: "llm",
        family: "",
        enabled: true,
        args: [],
        capabilities: {
            supportsRefImage: false,
            supportsLora: false,
            supportsFirstFrame: false,
            supportsLastFrame: false
        },
        variants: {},
        resolutions: {},
        durations: []
    });

    const handleCreate = () => {
        if (configuredProviders.size === 0) {
            return;
        }
        setEditingModel(getEmptyModel());
        setIsDialogOpen(true);
    };

    const handleEdit = (model: any) => {
        // Ensure args and durations are arrays (backend might return objects)
        const ensureArray = (value: any): string[] => {
            if (Array.isArray(value)) return value;
            if (typeof value === 'object' && value !== null) return Object.keys(value);
            return [];
        };

        setEditingModel({
            ...model,
            enabled: model.enabled !== false,
            args: ensureArray(model.args),
            capabilities: model.capabilities || {
                supportsRefImage: false,
                supportsLora: false,
                supportsFirstFrame: false,
                supportsLastFrame: false
            },
            variants: model.variants || {},
            resolutions: model.resolutions || {},
            durations: ensureArray(model.durations)
        });
        setIsDialogOpen(true);
    };

    const handleSave = async () => {
        // 1. Basic Validation
        if (!editingModel || !editingModel.name || !editingModel.model_id) {
            confirm({
                title: '验证失败',
                description: '请填写完整信息',
                confirmText: '确定',
                variant: 'destructive',
                onConfirm: () => {}
            });
            return;
        }

        // 2. Structure Validation
        if (!editingModel.capabilities || typeof editingModel.capabilities !== 'object') {
            console.error("Invalid capabilities structure", editingModel);
            confirm({
                title: '验证失败',
                description: '模型配置错误: capabilities 结构无效',
                confirmText: '确定',
                variant: 'destructive',
                onConfirm: () => {}
            });
            return;
        }

        // 3. Type-specific Validation
        if (editingModel.type === 'image' && (!editingModel.resolutions || typeof editingModel.resolutions !== 'object')) {
             // Initialize resolutions if missing for image models
             editingModel.resolutions = {};
        }

        setSaving(true);
        try {
            if (editingModel.id) {
                // Model update: The backend API for updating models is not yet implemented
                confirm({
                    title: '功能未开放',
                    description: '模型更新功能暂未开放，敬请期待',
                    confirmText: '确定',
                    onConfirm: () => {}
                });
                setIsDialogOpen(false);
            } else {
                // Create new model
                await DefaultService.registerNewModel(editingModel);
                confirm({
                    title: '添加成功',
                    description: '新模型已成功添加',
                    confirmText: '确定',
                    onConfirm: () => {}
                });
                setIsDialogOpen(false);

                if (onModelAdded) {
                    onModelAdded(editingModel);
                } else {
                    onRefreshModels();
                }
            }
        } catch (e: any) {
            console.error(e);
            confirm({
                title: '操作失败',
                description: e.message || "未知错误",
                confirmText: '确定',
                variant: 'destructive',
                onConfirm: () => {}
            });
        } finally {
            setSaving(false);
        }
    };

    const handleDelete = async (id: string) => {
        // Model deletion: The backend API for deleting models is not yet implemented
        confirm({
            title: '功能未开放',
            description: '模型删除功能暂未开放，敬请期待',
            confirmText: '确定',
            onConfirm: () => {}
        });
    };

    const handleDialogClose = () => {
        setIsDialogOpen(false);
    };

    return (
        <div className="flex flex-col h-full bg-background text-foreground">
            <div className="flex flex-col space-y-4 mb-6 flex-shrink-0">
                <div className="flex items-center justify-between">
                    <div>
                        <h3 className="text-lg font-medium">模型管理</h3>
                        <p className="mt-1 text-sm text-muted-foreground">
                            仅展示已配置密钥的供应商模型，自定义模型也只能绑定到已配置 provider。
                        </p>
                    </div>
                    <SearchInput
                        value={searchQuery}
                        onChange={setSearchQuery}
                        placeholder="搜索模型..."
                        className="w-64"
                    />
                </div>

                <div className="flex items-center justify-between">
                    {/* Tabs */}
                    <div className="flex space-x-1 bg-muted/20 p-1 rounded-lg border border-border w-fit">
                        {[
                            { id: 'all', label: '全部' },
                            { id: 'llm', label: '文本' },
                            { id: 'image', label: '图像' },
                            { id: 'video', label: '视频' },
                            { id: 'audio', label: '音频' },
                            { id: 'lyrics', label: '歌词' },
                            { id: 'music', label: '歌曲' }
                        ].map((tab) => (
                            <button
                                key={tab.id}
                                onClick={() => setActiveTab(tab.id as any)}
                                className={cn(
                                    "flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-medium transition-all",
                                    activeTab === tab.id
                                        ? "bg-background text-foreground shadow-sm border border-border/50"
                                        : "text-muted-foreground hover:text-foreground hover:bg-background/50"
                                )}
                            >
                                <span>{tab.label}</span>
                            </button>
                        ))}
                    </div>

                    {/* Grid Columns Control */}
                    <div className="flex items-center gap-3">
                        <CreateItemControl 
                            label="添加模型"
                            onClick={handleCreate}
                            disabled={configuredProviders.size === 0}
                        />
                        <ViewDisplayControl 
                            mode={viewMode}
                            onModeChange={setViewMode}
                            gridColumns={gridCols}
                            setGridColumns={setGridCols}
                            listColumns={listCols}
                            setListColumns={setListCols}
                        />
                    </div>
                </div>
            </div>

            <div className="mb-6 rounded-2xl border border-border bg-muted/20 p-5">
                <div className="flex items-start justify-between gap-4">
                    <div className="space-y-2">
                        <div className="flex items-center gap-2 text-sm font-medium text-foreground">
                            <Sparkles className="h-4 w-4 text-primary" />
                            模型能力与密钥状态联动
                        </div>
                        <p className="text-sm text-muted-foreground">
                            当前已配置 {configuredProviders.size} 个供应商，已解锁 {availableModelCount} 个模型。
                            未配置密钥的供应商不会显示模型，也不能添加自定义模型。
                        </p>
                    </div>
                    {configuredProviders.size === 0 && onNavigateToKeys && (
                        <Button variant="outline" onClick={onNavigateToKeys}>
                            去配置密钥
                        </Button>
                    )}
                </div>
            </div>

            <div className="flex-1 overflow-y-auto min-h-0 pr-2">
                <div className={cn(
                    "grid gap-4 pb-6",
                    // Grid Mode Classes
                    viewMode === 'grid' && currentCols === 2 && "grid-cols-2",
                    viewMode === 'grid' && currentCols === 3 && "grid-cols-3",
                    viewMode === 'grid' && currentCols === 4 && "grid-cols-4",
                    viewMode === 'grid' && currentCols === 5 && "grid-cols-5",
                    viewMode === 'grid' && currentCols === 6 && "grid-cols-6",
                    // List Mode Classes
                    viewMode === 'list' && currentCols === 1 && "grid-cols-1",
                    viewMode === 'list' && currentCols === 2 && "grid-cols-2"
                )}>
                    {filteredModels.map(model => (
                        <div 
                            key={model.id || Math.random()} 
                            className="bg-background border border-border rounded-lg p-4 relative group hover:border-blue-500/50 transition-colors cursor-pointer"
                            onClick={() => handleEdit(model)}
                        >
                            <div className="flex justify-between items-start mb-2">
                                <div className="font-medium text-sm text-foreground truncate pr-2" title={model.name || '未命名'}>{model.name || '未命名'}</div>
                                <span className="text-[10px] px-1.5 py-0.5 bg-muted rounded text-muted-foreground uppercase shrink-0 tracking-wider font-semibold">{model.type || 'unknown'}</span>
                            </div>
                            <div className="text-xs text-muted-foreground truncate font-mono mb-2" title={model.id || ''}>{model.id || 'N/A'}</div>
                            <div className="flex items-center gap-1.5 pt-2 border-t border-border">
                                <div className="w-4 h-4 text-muted-foreground">
                                    <ProviderIcon provider={model.provider || 'unknown'} />
                                </div>
                                <span className="text-xs text-muted-foreground capitalize">{model.provider_name || capitalize(model.provider) || 'unknown'}</span>
                            </div>
                        </div>
                    ))}

                    {filteredModels.length === 0 && configuredProviders.size > 0 && (
                        <EmptyState
                            icon={Box}
                            title="没有找到相关模型"
                            description="尝试调整搜索条件或添加新模型"
                            className="col-span-full h-64"
                        />
                    )}

                    {configuredProviders.size === 0 && (
                        <EmptyState
                            icon={LockKeyhole}
                            title="模型管理已锁定"
                            description="请先在密钥管理中添加至少一个供应商密钥，系统才会显示该供应商支持的模型，并开放自定义模型能力。"
                            action={onNavigateToKeys ? <Button onClick={onNavigateToKeys}>前往密钥管理</Button> : undefined}
                            className="col-span-full h-64"
                        />
                    )}
                </div>
            </div>

            {/* Edit/Create Dialog */}
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent className="max-w-3xl max-h-[90vh] overflow-hidden flex flex-col">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2 text-xl">
                            {editingModel?.id ? "编辑模型" : "添加新模型"}
                        </DialogTitle>
                        <p className="text-sm text-muted-foreground mt-1">
                            {editingModel?.id ? "修改模型配置信息" : "配置新的 AI 模型以供使用"}
                        </p>
                    </DialogHeader>

                    {editingModel && (
                        <div className="flex-1 overflow-y-auto pr-2 space-y-6 py-4">
                            {/* Basic Information */}
                            <section className="space-y-4">
                                <h3 className="text-sm font-semibold text-foreground uppercase tracking-wider flex items-center gap-2">
                                    <div className="w-1 h-4 bg-primary rounded-full" />
                                    基本信息
                                </h3>
                                
                                <div className="space-y-4 pl-3">
                                    <div className="flex items-center space-x-2">
                                        <Checkbox
                                            id="model-enabled"
                                            checked={editingModel.enabled}
                                            onCheckedChange={(checked) => setEditingModel({ ...editingModel, enabled: checked as boolean })}
                                        />
                                        <Label htmlFor="model-enabled" className="text-sm font-medium cursor-pointer">
                                            启用模型
                                        </Label>
                                    </div>

                                    <div>
                                        <InputControl
                                            label="模型名称"
                                            required
                                            value={editingModel.name || ''}
                                            onChange={(val) => setEditingModel({ ...editingModel, name: val })}
                                            placeholder="例如: Qwen Turbo"
                                        />
                                        <p className="text-xs text-muted-foreground mt-1.5">用于界面显示的友好名称</p>
                                    </div>
                                    
                                    <div>
                                        <InputControl
                                            label="模型 ID"
                                            required
                                            value={editingModel.model_id || ''}
                                            onChange={(val) => setEditingModel({ ...editingModel, model_id: val })}
                                            placeholder="例如: qwen-turbo"
                                        />
                                        <p className="text-xs text-muted-foreground mt-1.5">API 调用时使用的模型标识符</p>
                                    </div>
                                    
                                    <div className="grid grid-cols-2 gap-4">
                                        <div>
                                            <IconSelectControl
                                                label="提供商"
                                                value={editingModel.provider || ''}
                                                onChange={(val) => setEditingModel({ ...editingModel, provider: val })}
                                                options={(Array.isArray(providers) ? providers : []).filter((p) => configuredProviders.has(p.id)).map((p) => ({
                                                    label: capitalize(p.id),
                                                    value: p.id,
                                                    description: `(${p.name})`,
                                                    icon: <ProviderIcon provider={p.id} />
                                                }))}
                                            />
                                        </div>
                                        
                                        <div>
                                            <IconSelectControl
                                                label="模型类型"
                                                value={editingModel.type || 'llm'}
                                                onChange={(val) => setEditingModel({ ...editingModel, type: val })}
                                                options={[
                                                    { label: 'LLM', value: 'llm', description: '(文本生成)' },
                                                    { label: 'Image', value: 'image', description: '(图像生成)' },
                                                    { label: 'Video', value: 'video', description: '(视频生成)' },
                                                    { label: 'Audio', value: 'audio', description: '(音频生成)' }
                                                ]}
                                            />
                                        </div>
                                    </div>

                                    {editingModel.provider === 'dashscope' && editingModel.type === 'image' && (
                                        <div className="bg-muted/30 border border-border rounded-lg p-4">
                                            <SelectControl
                                                label="模型家族"
                                                value={editingModel.family || 'default'}
                                                onChange={(value) => setEditingModel({ ...editingModel, family: value })}
                                                options={[
                                                    { label: '默认 (Wan)', value: 'default' },
                                                    { label: 'Wan (通义万相)', value: 'wan' },
                                                    { label: 'Z-Image (其他)', value: 'z-image' }
                                                ]}
                                            />
                                            <p className="text-xs text-muted-foreground mt-1.5">阿里云图像模型的特定家族配置</p>
                                        </div>
                                    )}

                                    <StringListEditor
                                        label="初始化参数 (Args)"
                                        items={editingModel.args || []}
                                        onChange={(items) => setEditingModel({ ...editingModel, args: items })}
                                        placeholder="例如: qwen-turbo"
                                        description="传递给服务构造函数的参数列表"
                                    />
                                    <p className="text-xs text-muted-foreground">
                                        只允许为已配置密钥的 provider 添加自定义模型，避免模型在界面中可见但实际不可调用。
                                    </p>
                                </div>
                            </section>

                            <div className="h-px bg-border" />

                            {/* Advanced Configuration */}
                            {['image', 'video'].includes(editingModel.type) && (
                                <section className="space-y-4">
                                    <h3 className="text-sm font-semibold text-foreground uppercase tracking-wider flex items-center gap-2">
                                        <div className="w-1 h-4 bg-primary rounded-full" />
                                        功能配置
                                    </h3>
                                    
                                    <div className="space-y-4 pl-3">
                                        <div className="bg-muted/30 border border-border rounded-lg p-4">
                                            <Label className="text-sm font-medium mb-3 block">支持的功能 (Capabilities)</Label>
                                            <div className="grid grid-cols-2 gap-3">
                                                <div className="flex items-center space-x-2 p-2 rounded-md hover:bg-background/50 transition-colors">
                                                    <Checkbox
                                                        id="supportsRefImage"
                                                        checked={editingModel.capabilities?.supportsRefImage || false}
                                                        onCheckedChange={(checked) => setEditingModel({
                                                            ...editingModel,
                                                            capabilities: { ...editingModel.capabilities, supportsRefImage: checked as boolean }
                                                        })}
                                                    />
                                                    <Label htmlFor="supportsRefImage" className="text-sm font-normal cursor-pointer flex-1">
                                                        参考图 (i2i)
                                                    </Label>
                                                </div>
                                                <div className="flex items-center space-x-2 p-2 rounded-md hover:bg-background/50 transition-colors">
                                                    <Checkbox
                                                        id="supportsLora"
                                                        checked={editingModel.capabilities?.supportsLora || false}
                                                        onCheckedChange={(checked) => setEditingModel({
                                                            ...editingModel,
                                                            capabilities: { ...editingModel.capabilities, supportsLora: checked as boolean }
                                                        })}
                                                    />
                                                    <Label htmlFor="supportsLora" className="text-sm font-normal cursor-pointer flex-1">
                                                        LoRA 模型
                                                    </Label>
                                                </div>
                                                {editingModel.type === 'video' && (
                                                    <>
                                                        <div className="flex items-center space-x-2 p-2 rounded-md hover:bg-background/50 transition-colors">
                                                            <Checkbox
                                                                id="supportsFirstFrame"
                                                                checked={editingModel.capabilities?.supportsFirstFrame || false}
                                                                onCheckedChange={(checked) => setEditingModel({
                                                                    ...editingModel,
                                                                    capabilities: { ...editingModel.capabilities, supportsFirstFrame: checked as boolean }
                                                                })}
                                                            />
                                                            <Label htmlFor="supportsFirstFrame" className="text-sm font-normal cursor-pointer flex-1">
                                                                首帧 (图生视频)
                                                            </Label>
                                                        </div>
                                                        <div className="flex items-center space-x-2 p-2 rounded-md hover:bg-background/50 transition-colors">
                                                            <Checkbox
                                                                id="supportsLastFrame"
                                                                checked={editingModel.capabilities?.supportsLastFrame || false}
                                                                onCheckedChange={(checked) => setEditingModel({
                                                                    ...editingModel,
                                                                    capabilities: { ...editingModel.capabilities, supportsLastFrame: checked as boolean }
                                                                })}
                                                            />
                                                            <Label htmlFor="supportsLastFrame" className="text-sm font-normal cursor-pointer flex-1">
                                                                尾帧 (视频延展)
                                                            </Label>
                                                        </div>
                                                    </>
                                                )}
                                            </div>
                                            <p className="text-xs text-muted-foreground mt-3">勾选模型支持的特殊功能</p>
                                        </div>

                                        <KeyValueEditor
                                            label="变体映射 (Variants)"
                                            items={editingModel.variants || {}}
                                            onChange={(items) => setEditingModel({ ...editingModel, variants: items })}
                                            keyLabel="Config Key"
                                            valueLabel="API Model"
                                            description="前端选项到后端模型ID的映射"
                                        />

                                        <KeyValueEditor
                                            label="分辨率映射 (Resolutions)"
                                            items={editingModel.resolutions || {}}
                                            onChange={(items) => setEditingModel({ ...editingModel, resolutions: items })}
                                            keyLabel="Ratio (e.g. 16:9)"
                                            valueLabel="Pixel (e.g. 1280*720)"
                                            description="支持的宽高比及其对应的分辨率"
                                        />

                                        {editingModel.type === 'video' && (
                                            <StringListEditor
                                                label="支持的时长 (Durations)"
                                                items={editingModel.durations || []}
                                                onChange={(items) => setEditingModel({ ...editingModel, durations: items })}
                                                placeholder="例如: 5"
                                                description="视频生成支持的时长选项（秒）"
                                            />
                                        )}
                                    </div>
                                </section>
                            )}
                        </div>
                    )}

                    {/* Footer Actions */}
                    <div className="flex items-center justify-between pt-4 border-t border-border">
                        {editingModel?.id ? (
                            <Button
                                variant="ghost"
                                onClick={() => handleDelete(editingModel.id!)}
                                disabled={true}
                                title="模型删除功能暂未开放"
                                className="flex items-center gap-2 bg-red-500/10 hover:bg-red-500/20 text-red-500 border border-red-500/20 h-10 opacity-50 cursor-not-allowed"
                            >
                                <Trash2 size={16} />
                                <span>删除模型（未开放）</span>
                            </Button>
                        ) : (
                            <div />
                        )}
                        
                        <div className="flex items-center gap-3">
                            <Button 
                                variant="outline"
                                onClick={handleDialogClose}
                                className="h-10 px-6"
                            >
                                取消
                            </Button>
                            <Button 
                                onClick={handleSave}
                                disabled={saving}
                                className="bg-primary hover:bg-primary/90 h-10 px-6"
                            >
                                <Save size={16} className="mr-2" />
                                {saving ? "保存中..." : "保存"}
                            </Button>
                        </div>
                    </div>
                </DialogContent>
            </Dialog>

            {/* Confirm Dialog */}
            <ConfirmDialog />
        </div>
    );
};
