"use client";

import React, { useState, useEffect, useCallback, useMemo } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogTitle,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { ModalLayout, ModalSidebar, ModalContent } from "@/components/ui/modal-layout";
import { NavButton } from "@/components/ui/nav-button";
import {
  Settings,
  Box,
  Key,
  Palette,
  Shield,
  X
} from 'lucide-react';
import { Button } from "@/components/ui/button";
import { LoadingState } from "@/components/ui/loading-state";
import { Save } from 'lucide-react';
import { DefaultService } from "@lib/api";
import { useConfirm } from '@/components/ui/confirm-dialog';
import { useQueryClient } from '@tanstack/react-query';
import { CONFIG_KEYS } from '@/lib/hooks/useConfig';
import { listApiKeys } from '@/lib/api/userApiKeys';

import { GeneralTab } from './tabs/GeneralTab';
import { ModelsTab } from './tabs/ModelsTab';
import { StylesTab } from './tabs/StylesTab';
import { UserApiKeysTab } from './tabs/UserApiKeysTab';
import { SessionsTab } from './tabs/SessionsTab';

export type SettingsTabType = 'general' | 'keys' | 'sessions' | 'models' | 'styles';

interface SettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
  defaultTab?: SettingsTabType;
}

export const SettingsModal: React.FC<SettingsModalProps> = ({
  isOpen,
  onClose,
  defaultTab,
}) => {
  const [activeTab, setActiveTab] = useState<SettingsTabType>(defaultTab || 'general');

  // Update active tab when defaultTab changes or modal opens
  useEffect(() => {
    if (isOpen && defaultTab) {
      setActiveTab(defaultTab);
    }
  }, [isOpen, defaultTab]);
  const [config, setConfig] = useState<any>({});
  const [models, setModels] = useState<any[]>([]);
  const [configuredProviders, setConfiguredProviders] = useState<Set<string>>(new Set());
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const { confirm, ConfirmDialog } = useConfirm();
  const queryClient = useQueryClient();

  const menuItems: { id: SettingsTabType; label: string; icon: React.ElementType }[] = [
    { id: 'general', label: '通用设置', icon: Settings },
    { id: 'styles', label: '美术风格', icon: Palette },
    { id: 'keys', label: '密钥管理', icon: Key },
    { id: 'sessions', label: '会话管理', icon: Shield },
    { id: 'models', label: '模型管理', icon: Box },
  ];

  // Filtered models based on configured API keys
  const filteredModels = useMemo(() => {
    return models.filter(model => configuredProviders.has(model.provider));
  }, [models, configuredProviders]);

  // Fetch settings data
  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      const [configRes, modelsRes, apiKeys] = await Promise.all([
        DefaultService.getSystemConfig(),
        DefaultService.getModelsConfig(),
        listApiKeys(false)
      ]);
      setConfig(configRes.data || {});

      // Get configured providers
      const activeProviders = new Set(apiKeys.filter(k => k.isActive).map(k => k.provider));
      setConfiguredProviders(activeProviders);

      // Backend returns grouped HashMaps by type; flatten for the settings UI
      const allModels: any[] = [];
      const modelData = modelsRes.data;
      if (modelData) {
        Object.values(modelData.image || {}).forEach(m => allModels.push(m));
        Object.values(modelData.video || {}).forEach(m => allModels.push(m));
        Object.values(modelData.llm || {}).forEach(m => allModels.push(m));
        Object.values(modelData.audio || {}).forEach(m => allModels.push(m));
        Object.values(modelData.lyrics || {}).forEach(m => allModels.push(m));
        Object.values(modelData.music || {}).forEach(m => allModels.push(m));
      }
      console.log('[Settings] Loaded models:', allModels.length, allModels);
      console.log('[Settings] Configured providers:', Array.from(activeProviders));
      setModels(allModels);
    } catch (error) {
      console.error("[Settings] Failed to load settings:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (isOpen) {
      fetchData();
    }
  }, [isOpen, fetchData]);

  const handleSave = async () => {
    setSaving(true);
    try {
      await DefaultService.updateSystemConfig(config);
      
      // Invalidate React Query cache to trigger ModelInitializer refresh
      queryClient.invalidateQueries({ queryKey: CONFIG_KEYS.models() });
      
      // Refresh local models state
      await fetchData();
      
      // Show success message using confirm dialog
      confirm({
        title: '保存成功',
        description: '默认模型配置已更新。',
        confirmText: '确定',
        onConfirm: () => {}
      });
    } catch (error) {
      console.error("Failed to save settings", error);
      confirm({
        title: '保存失败',
        description: error instanceof Error ? error.message : "未知错误",
        confirmText: '确定',
        variant: 'destructive',
        onConfirm: () => {}
      });
    } finally {
      setSaving(false);
    }
  };

  const handleModelAdded = (newModel: any) => {
    setModels(prev => [...prev, newModel]);
    // Invalidate React Query cache to ensure consistency elsewhere
    queryClient.invalidateQueries({ queryKey: CONFIG_KEYS.models() });
  };

  return (
    <>
      <ConfirmDialog />
      <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="max-w-6xl h-[85vh] flex flex-col p-0 gap-0 overflow-hidden border-none outline-none bg-background [&_.dialog-close-button]:hidden">
        <DialogDescription className="sr-only">
          系统设置面板，可管理默认模型、风格、密钥、会话和系统配置。
        </DialogDescription>
        
        {/* Full Width Header */}
        <div className="h-14 flex items-center px-6 border-b border-border bg-background shrink-0 justify-between">
          <DialogTitle className="flex items-center gap-2 font-semibold truncate text-foreground text-sm m-0">
            <Settings className="w-4 h-4 text-primary" />
            <span>设置</span>
          </DialogTitle>
          <Button variant="ghost" size="icon" className="h-8 w-8 rounded-full" onClick={onClose}>
            <X className="h-4 w-4" />
          </Button>
        </div>

        <ModalLayout>
          {/* Sidebar Navigation */}
          <ModalSidebar>
            <nav className="flex-1 py-4 px-3 space-y-2 overflow-y-auto">
              {menuItems.map((item) => (
                <NavButton
                  key={item.id}
                  isActive={activeTab === item.id}
                  onClick={() => setActiveTab(item.id)}
                  icon={item.icon}
                  label={item.label}
                />
              ))}
            </nav>
            
            {/* Footer / Version Info */}
            <div className="p-4 border-t border-border text-xs text-muted-foreground bg-background">
              <div className="flex justify-between items-center">
                <span>状态</span>
                <span className="flex items-center gap-1.5">
                    <span className="w-2 h-2 rounded-full bg-green-500" />
                    进行中
                </span>
              </div>
            </div>
          </ModalSidebar>

          {/* Main Content Area */}
          <ModalContent>
          
            {/* Scrollable Content */}
            <ScrollArea className="flex-1">
                <div className="p-6 pb-24">
                    {loading ? (
                        <div className="max-w-3xl mx-auto">
                            <LoadingState message="加载设置中..." />
                        </div>
                    ) : (
                        <>
                            {activeTab === 'general' && (
                                <div className="max-w-4xl mx-auto">
                                    <GeneralTab
                                        config={config}
                                        setConfig={setConfig}
                                        models={filteredModels}
                                        onSave={handleSave}
                                        saving={saving}
                                    />
                                </div>
                            )}
                            {activeTab === 'keys' && (
                                <div className="max-w-5xl mx-auto">
                                    <UserApiKeysTab
                                        models={models}
                                        configuredProviders={configuredProviders}
                                        onNavigateToModels={() => setActiveTab('models')}
                                    />
                                </div>
                            )}
                            {activeTab === 'sessions' && (
                                <div className="max-w-5xl mx-auto">
                                    <SessionsTab />
                                </div>
                            )}
                            {activeTab === 'models' && (
                                <div className="max-w-5xl mx-auto">
                                    <ModelsTab
                                        models={filteredModels}
                                        configuredProviders={configuredProviders}
                                        config={config}
                                        setConfig={setConfig}
                                        availableModels={models}
                                        onNavigateToKeys={() => setActiveTab('keys')}
                                        onRefreshModels={fetchData}
                                        onSave={handleSave}
                                        saving={saving}
                                        onModelAdded={handleModelAdded}
                                    />
                                </div>
                            )}
                            {activeTab === 'styles' && (
                                <div className="max-w-6xl mx-auto">
                                    <StylesTab />
                                </div>
                            )}
                        </>
                    )}
                </div>
            </ScrollArea>
          </ModalContent>
        </ModalLayout>
      </DialogContent>
    </Dialog>
    </>
  );
};
