'use client';

import React, { useState, useCallback, useMemo } from 'react';
import { Plus, Check, Settings2, Search, ExternalLink, Loader2, Sparkles } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ApiKeyForm } from '@/components/settings/ApiKeyForm';
import { useApiKeys } from '@/lib/hooks/useApiKeys';
import { useProviderConfigs } from '@/lib/hooks/useConfig';
import { type ApiKey } from '@/lib/api/userApiKeys';
import { SearchInput } from '@/components/ui/search-input';
import { EmptyState } from '@/components/ui/empty-state';
import { ViewDisplayControl } from '@/components/common/ViewDisplayControl';
import { ProviderIcon } from '@/components/common/ProviderIcon';
import { cn } from '@/utils';

interface UserApiKeysTabProps {
  models?: Array<{ provider?: string }>;
  configuredProviders?: Set<string>;
  onNavigateToModels?: () => void;
}

export const UserApiKeysTab: React.FC<UserApiKeysTabProps> = ({
  models = [],
  configuredProviders = new Set<string>(),
  onNavigateToModels,
}) => {
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [selectedProvider, setSelectedProvider] = useState<string>('');
  const { apiKeys, isLoading: isApiKeysLoading, error, refresh } = useApiKeys() as { apiKeys: ApiKey[], isLoading: boolean, error: unknown, refresh: () => void };
  const { data: providerConfigs = [], isLoading: isProvidersLoading } = useProviderConfigs();

  // Search and view state
  const [searchQuery, setSearchQuery] = useState('');
  const [activeTab, setActiveTab] = useState<'all' | 'configured' | 'unconfigured'>('all');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [gridCols, setGridCols] = useState<number>(4);
  const [listCols, setListCols] = useState<number>(1);

  const currentCols = viewMode === 'grid' ? gridCols : listCols;
  const isLoading = isApiKeysLoading || isProvidersLoading;

  // Build provider status map
  const providerStatusMap = useMemo(() => {
    const map = new Map<string, ApiKey | null>();
    providerConfigs.forEach((provider: any) => {
      const configuredKey = apiKeys.find(k => k.provider === provider.id && k.isActive);
      map.set(provider.id, configuredKey || null);
    });
    return map;
  }, [apiKeys, providerConfigs]);

  // Filter providers based on search and tab
  const filteredProviders = useMemo(() => {
    return providerConfigs.filter((provider: any) => {
      const matchesSearch = provider.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        provider.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
        provider.id.toLowerCase().includes(searchQuery.toLowerCase());

      const isConfigured = providerStatusMap.get(provider.id) !== null;

      const matchesTab = activeTab === 'all' ||
        (activeTab === 'configured' && isConfigured) ||
        (activeTab === 'unconfigured' && !isConfigured);

      return matchesSearch && matchesTab;
    });
  }, [searchQuery, activeTab, providerStatusMap, providerConfigs]);

  const modelCountByProvider = useMemo(() => {
    const counts = new Map<string, number>();
    models.forEach((model) => {
      if (!model.provider) return;
      counts.set(model.provider, (counts.get(model.provider) || 0) + 1);
    });
    return counts;
  }, [models]);

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

  const handleOpenProvider = useCallback((providerId: string) => {
    setSelectedProvider(providerId);
    setIsFormOpen(true);
  }, []);

  const handleClose = useCallback(() => {
    setIsFormOpen(false);
    setSelectedProvider('');
  }, []);

  const handleSuccess = useCallback(() => {
    refresh();
    handleClose();
  }, [refresh, handleClose]);

  // Get configured providers list for the form
  const existingProviders = useMemo(() =>
    apiKeys.filter(k => k.isActive).map(k => k.provider),
    [apiKeys]
  );

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-full">
        <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full bg-background text-foreground animate-in fade-in slide-in-from-bottom-4 duration-500">
      {!!error && (
        <div className="mb-4 p-4 bg-destructive/10 text-destructive rounded-lg">
          {error instanceof Error ? error.message : String(error)}
        </div>
      )}

      {/* Header with Search and Controls */}
      <div className="flex flex-col space-y-4 mb-6 flex-shrink-0">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-medium">密钥管理</h3>
          <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: 'configured', label: '已配置' },
              { id: 'unconfigured', 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>

          {/* Controls */}
          <div className="flex items-center gap-3">
            <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">
              模型管理依赖供应商密钥。配置完成后，才会显示该供应商支持的官方模型，并允许你添加同 provider 的自定义模型。
            </p>
          </div>
          {configuredProviders.size > 0 && onNavigateToModels && (
            <Button variant="outline" onClick={onNavigateToModels}>
              查看已解锁模型
            </Button>
          )}
        </div>

        <div className="mt-4 grid gap-3 md:grid-cols-3">
          <div className="rounded-xl border border-border bg-background/60 p-4">
            <div className="text-xs text-muted-foreground">已配置供应商</div>
            <div className="mt-1 text-2xl font-semibold text-foreground">{configuredProviders.size}</div>
          </div>
          <div className="rounded-xl border border-border bg-background/60 p-4">
            <div className="text-xs text-muted-foreground">已解锁模型</div>
            <div className="mt-1 text-2xl font-semibold text-foreground">{unlockedModelCount}</div>
          </div>
          <div className="rounded-xl border border-border bg-background/60 p-4">
            <div className="text-xs text-muted-foreground">待解锁供应商</div>
            <div className="mt-1 text-2xl font-semibold text-foreground">
              {Math.max(providerConfigs.length - configuredProviders.size, 0)}
            </div>
          </div>
        </div>
      </div>

      {/* Providers Grid/List */}
      <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",
          // List Mode Classes
          viewMode === 'list' && currentCols === 1 && "grid-cols-1",
          viewMode === 'list' && currentCols === 2 && "grid-cols-2"
        )}>
          {filteredProviders.map((provider: any) => {
            const isConfigured = providerStatusMap.get(provider.id) !== null;
            const supportedModelCount = modelCountByProvider.get(provider.id) || 0;

            return (
              <div
                key={provider.id}
                onClick={() => handleOpenProvider(provider.id)}
                className={cn(
                  "bg-background border rounded-lg p-4 relative group transition-all cursor-pointer",
                  isConfigured
                    ? "border-border hover:border-blue-500/50 hover:shadow-sm"
                    : "border-border/50 hover:border-border hover:shadow-sm"
                )}
              >
                {/* Header */}
                <div className="flex justify-between items-start mb-3">
                  <div className="flex items-center gap-2 min-w-0">
                    <div className="w-8 h-8 flex items-center justify-center shrink-0">
                      <ProviderIcon provider={provider.id} className="w-6 h-6" />
                    </div>
                    <div className="font-medium text-sm text-foreground truncate" title={provider.name}>
                      {provider.name}
                    </div>
                  </div>
                  {isConfigured ? (
                    <Badge variant="default" className="shrink-0 text-[10px]">
                      <Check className="w-3 h-3 mr-1" />
                      已配置
                    </Badge>
                  ) : (
                    <Badge variant="secondary" className="shrink-0 text-[10px]">
                      未配置
                    </Badge>
                  )}
                </div>

                {/* Description */}
                <div className="text-xs text-muted-foreground mb-4 truncate">
                  {provider.description}
                </div>

                <div className="mb-4 rounded-lg border border-border/70 bg-muted/20 px-3 py-2">
                  <div className="text-xs font-medium text-foreground">
                    {isConfigured ? `已解锁 ${supportedModelCount} 个模型` : `配置后可解锁 ${supportedModelCount} 个模型`}
                  </div>
                  <div className="mt-1 text-[11px] text-muted-foreground">
                    {isConfigured
                      ? '当前可以在模型管理里查看官方模型，并按该提供商添加自定义模型。'
                      : '先添加此提供商密钥，模型管理页才会显示其可用模型。'}
                  </div>
                </div>

                {/* Action Button */}
                <div className="flex items-center justify-between pt-3 border-t border-border">
                  {provider.helpUrl && (
                    <a
                      href={provider.helpUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex items-center text-xs text-primary hover:text-primary/80 transition-colors"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <ExternalLink className="w-3 h-3 mr-1" />
                      获取 Key
                    </a>
                  )}

                  <div className={cn("flex items-center gap-2", !provider.helpUrl && "ml-auto")}>
                    {isConfigured && onNavigateToModels && (
                      <Button
                        size="sm"
                        variant="ghost"
                        className="h-8"
                        onClick={(e) => {
                          e.stopPropagation();
                          onNavigateToModels();
                        }}
                      >
                        查看模型
                      </Button>
                    )}
                    <Button
                      size="sm"
                      variant={isConfigured ? "outline" : "default"}
                      className="h-8"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleOpenProvider(provider.id);
                      }}
                    >
                      {isConfigured ? (
                        <>
                          <Settings2 className="w-4 h-4 mr-1" />
                          配置
                        </>
                      ) : (
                        <>
                          <Plus className="w-4 h-4 mr-1" />
                          添加
                        </>
                      )}
                    </Button>
                  </div>
                </div>
              </div>
            );
          })}

          {filteredProviders.length === 0 && (
            <EmptyState
              icon={Search}
              title="没有找到相关供应商"
              description="尝试调整搜索条件"
              className="col-span-full h-64"
            />
          )}
        </div>
      </div>

      <ApiKeyForm
        isOpen={isFormOpen}
        onClose={handleClose}
        onSuccess={handleSuccess}
        editKey={selectedProvider ? providerStatusMap.get(selectedProvider) : null}
        existingProviders={existingProviders}
        defaultProvider={selectedProvider}
        providerConfigs={providerConfigs}
      />
    </div>
  );
};
