'use client';

import React, { useState, useMemo } from 'react';
import { Edit2, Trash2, Copy, Check, Loader2, AlertCircle, Key, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { type ApiKey, updateApiKey, deleteApiKey } from '@/lib/api/userApiKeys';
import { useProviderConfigs } from '@/lib/hooks/useConfig';
import { ProviderIcon } from '@/components/common/ProviderIcon';
import { SearchInput } from '@/components/ui/search-input';
import { EmptyState } from '@/components/ui/empty-state';
import { CreateItemControl } from '@/components/common/CreateItemControl';
import { ViewDisplayControl } from '@/components/common/ViewDisplayControl';
import { cn } from '@/utils';

interface ApiKeyListProps {
  apiKeys: ApiKey[];
  isLoading: boolean;
  onEdit: (key: ApiKey) => void;
  onRefresh: () => void;
  onCreate?: () => void;
}

export function ApiKeyList({ apiKeys, isLoading, onEdit, onRefresh, onCreate }: ApiKeyListProps) {
  const [copiedId, setCopiedId] = React.useState<string | null>(null);
  const [deletingId, setDeletingId] = React.useState<string | null>(null);
  const [togglingId, setTogglingId] = React.useState<string | null>(null);

  // Fetch provider configs from API
  const { data: providerConfigs } = useProviderConfigs();

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

  const currentCols = viewMode === 'grid' ? gridCols : listCols;

  // Filtered API keys based on search and tab
  const filteredApiKeys = useMemo(() => {
    return apiKeys.filter(key => {
      const matchesSearch = (key.name?.toLowerCase() || '').includes(searchQuery.toLowerCase()) ||
        (key.provider?.toLowerCase() || '').includes(searchQuery.toLowerCase());
      const matchesTab = activeTab === 'all' ||
        (activeTab === 'active' && key.isActive) ||
        (activeTab === 'inactive' && !key.isActive);
      return matchesSearch && matchesTab;
    });
  }, [apiKeys, searchQuery, activeTab]);

  const handleCopy = async (keyId: string, maskedKey: string) => {
    await navigator.clipboard.writeText(maskedKey);
    setCopiedId(keyId);
    setTimeout(() => setCopiedId(null), 2000);
  };

  const handleDelete = async (keyId: string) => {
    setDeletingId(keyId);
    try {
      await deleteApiKey(keyId);
      onRefresh();
    } catch (error) {
      console.error('Failed to delete API key:', error);
    } finally {
      setDeletingId(null);
    }
  };

  const handleToggleActive = async (key: ApiKey) => {
    setTogglingId(key.id);
    try {
      await updateApiKey(key.id, { enabled: !key.isActive });
      onRefresh();
    } catch (error) {
      console.error('Failed to toggle API key:', error);
    } finally {
      setTogglingId(null);
    }
  };

  // Note: 纯用户密钥模式 - 移除查看完整密钥功能，仅允许编辑/更新

  const getProviderInfo = (providerId: string) => {
    const config = providerConfigs?.find((p: { id: string; name: string; description: string }) => p.id === providerId);
    if (config) {
      return {
        id: config.id,
        name: config.name,
        description: config.description,
      };
    }
    // Fallback: return providerId as name if not found
    return {
      id: providerId,
      name: providerId,
      description: '',
    };
  };

  const formatDate = (timestamp: number) => {
    return new Date(timestamp * 1000).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

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

  if (apiKeys.length === 0) {
    return (
      <EmptyState
        icon={Key}
        title="暂无密钥"
        description="您还没有添加任何密钥。添加密钥后，您可以使用自己的账号进行 AI 生成任务。"
        className="h-64"
      />
    );
  }

  return (
    <div className="flex flex-col h-full">
      {/* 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: 'active', label: '已启用' },
              { id: 'inactive', 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">
            {onCreate && (
              <CreateItemControl
                label="添加 Key"
                onClick={onCreate}
              />
            )}
            <ViewDisplayControl
              mode={viewMode}
              onModeChange={setViewMode}
              gridColumns={gridCols}
              setGridColumns={setGridCols}
              listColumns={listCols}
              setListColumns={setListCols}
            />
          </div>
        </div>
      </div>

      {/* API Keys 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"
        )}>
          {filteredApiKeys.map((key) => {
            const provider = getProviderInfo(key.provider);
            const isCopied = copiedId === key.id;
            const isDeleting = deletingId === key.id;
            const isToggling = togglingId === key.id;

            return (
              <div
                key={key.id}
                className={cn(
                  "bg-background border rounded-lg p-4 relative group transition-colors",
                  key.isActive
                    ? "border-border hover:border-blue-500/50"
                    : "border-border/50 opacity-60 hover:opacity-80"
                )}
              >
                {/* Header */}
                <div className="flex justify-between items-start mb-3">
                  <div className="flex items-center gap-2 min-w-0">
                    <div className="w-6 h-6 flex items-center justify-center shrink-0">
                      <ProviderIcon provider={key.provider} className="w-5 h-5" />
                    </div>
                    <div className="font-medium text-sm text-foreground truncate" title={key.name || provider.name}>
                      {key.name || provider.name}
                    </div>
                  </div>
                  <Badge
                    variant={key.isActive ? 'default' : 'secondary'}
                    className="shrink-0 text-[10px]"
                  >
                    {key.isActive ? '启用' : '禁用'}
                  </Badge>
                </div>

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

                {/* Masked Key */}
                <div className="flex items-center gap-2 mb-3">
                  <code className="flex-1 px-2 py-1 bg-muted rounded text-xs font-mono truncate">
                    {key.maskedKey}
                  </code>
                </div>

                {/* Stats */}
                <div className="flex items-center gap-3 text-xs text-muted-foreground mb-3">
                  <span>使用 {key.usageCount} 次</span>
                  <span>·</span>
                  <span>{key.createdAt ? formatDate(new Date(key.createdAt).getTime()) : "-"}</span>
                </div>

                {/* Actions */}
                <div className="flex items-center justify-between pt-3 border-t border-border">
                  <div className="flex items-center gap-1">
                    <Checkbox
                      checked={key.isActive}
                      onCheckedChange={() => handleToggleActive(key)}
                      disabled={isToggling}
                      className="h-4 w-4"
                    />
                    {isToggling && <Loader2 className="w-3 h-3 animate-spin" />}
                  </div>

                  <div className="flex items-center gap-1">
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8"
                      onClick={() => handleCopy(key.id, key.maskedKey || '')}
                      title="复制脱敏 Key"
                    >
                      {isCopied ? (
                        <Check className="w-4 h-4 text-green-500" />
                      ) : (
                        <Copy className="w-4 h-4" />
                      )}
                    </Button>
                    {/* Note: 纯用户密钥模式 - 移除查看完整密钥按钮 */}
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8"
                      onClick={() => onEdit(key)}
                      disabled={isDeleting}
                      title="编辑"
                    >
                      <Edit2 className="w-4 h-4" />
                    </Button>

                    <AlertDialog>
                      <AlertDialogTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-destructive hover:text-destructive"
                          disabled={isDeleting}
                          title="删除"
                        >
                          {isDeleting ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Trash2 className="w-4 h-4" />
                          )}
                        </Button>
                      </AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader>
                          <AlertDialogTitle className="flex items-center gap-2">
                            <AlertCircle className="w-5 h-5 text-destructive" />
                            确认删除
                          </AlertDialogTitle>
                          <AlertDialogDescription>
                            您确定要删除密钥 &quot;{key.name || provider.name}&quot; 吗？
                            此操作不可撤销，删除后将无法恢复。
                          </AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                          <AlertDialogCancel>取消</AlertDialogCancel>
                          <AlertDialogAction
                            onClick={() => handleDelete(key.id)}
                            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                          >
                            删除
                          </AlertDialogAction>
                        </AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  </div>
                </div>
              </div>
            );
          })}

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

      {/* Note: 纯用户密钥模式 - 移除查看完整密钥 Dialog */}
    </div>
  );
}
