/**
 * Repository Item Component
 * Expandable to show tags list with type filtering
 */
import React, { useState, useEffect } from "react";
import { Package, ChevronDown, ChevronRight, Copy, Tag as TagIcon, Filter, AlertCircle, Rocket } from "lucide-react";
import { listArtifacts } from "@/api";
import type { ArtifactListItem } from "@/api";
import { useToast } from "@/shared";
import { LaunchModal } from "./LaunchModal";
import { artifactCache } from "@/shared/services/artifact-cache";
import { RegistryErrors, formatApiError } from "@/shared/utils";
import { inferArtifactCategory, type ArtifactCategory } from "../utils/artifactType";

interface RepositoryItemProps {
  registryId: string;
  registryName: string;
  registryUrl: string;
  repository: string;
}

export const RepositoryItem: React.FC<RepositoryItemProps> = ({
  registryId,
  registryName,
  registryUrl,
  repository,
}) => {
  const { success, error: toastError } = useToast();
  const [expanded, setExpanded] = useState(false);
  const [allTags, setAllTags] = useState<ArtifactListItem[]>([]); // All tags
  const [filteredTags, setFilteredTags] = useState<ArtifactListItem[]>([]); // Filtered tags
  const [loading, setLoading] = useState(false);
  const [tagsLoaded, setTagsLoaded] = useState(false); // Whether tags are loaded
  const [filterType, setFilterType] = useState<ArtifactCategory | "all">("chart"); // Default filter: chart
  const [loadError, setLoadError] = useState<string | null>(null); // Load error message
  const [launchModalOpen, setLaunchModalOpen] = useState(false);
  const [selectedTag, setSelectedTag] = useState<ArtifactListItem | null>(null);

  // Load tags when expanded (using isMounted pattern for Strict Mode compatibility)
  // 🚀 Enhanced with cache support and auto-retry
  useEffect(() => {
    if (!expanded || tagsLoaded) {
      return; // Not expanded or already loaded, skip
    }

    const isMounted = { current: true };

    const loadTags = async (attempt = 1) => {
      const MAX_RETRIES = 2;
      
      // 🚀 Check cache first
      const cachedData = artifactCache.get(registryId, repository);
      if (cachedData !== null) {
        console.log(`[RepositoryItem] ✅ Cache hit for ${repository} (${cachedData.length} tags)`);
        setAllTags(cachedData);
        setTagsLoaded(true);
        setLoadError(null);
        return; // Skip API call
      }

      // Cache miss, load from API
      setLoading(true);
      setLoadError(null);
      
      try {
        console.log(`[RepositoryItem] 📡 Loading tags from API for: ${repository} (attempt ${attempt})`);
        
        // Mark as loading in cache to prevent duplicate requests
        artifactCache.setLoading(registryId, repository);
        
        // Fetch all tags to support client-side filter switching
        const tagList = await listArtifacts({ registryId, repositoryName: repository });
        
        // Only update state if component is still mounted
        if (isMounted.current) {
          console.log(`[RepositoryItem] ✅ Loaded ${tagList.length} tags from API`);
          
          // Update cache
          artifactCache.set(registryId, repository, tagList);
          
          setAllTags(tagList);
          setTagsLoaded(true);
          setLoadError(null);
        }
      } catch (error) {
        // Only show error if component is still mounted
        if (isMounted.current) {
          // Retry if attempts remaining
          if (attempt < MAX_RETRIES) {
            console.log(`[RepositoryItem] 🔄 Retrying ${repository} (${attempt + 1}/${MAX_RETRIES})...`);
            await new Promise(resolve => setTimeout(resolve, 500 * attempt)); // Exponential backoff
            return loadTags(attempt + 1);
          }
          
          // All retries exhausted
          console.error(`[RepositoryItem] ❌ All retries exhausted for ${repository}:`, error);
          
          // Format error message using unified error handling
          const errorMsg = formatApiError(error) || RegistryErrors.TAGS_LOAD_FAILED;
          setLoadError(errorMsg);
          toastError(errorMsg);
          
          // 🔧 Clear cache to allow manual retry
          artifactCache.clear(registryId, repository);
          
          setAllTags([]);
          // Don't set tagsLoaded to true - allow retry
        }
      } finally {
        if (isMounted.current) {
          setLoading(false);
        }
      }
    };

    loadTags();

    // Cleanup: mark as unmounted to prevent state updates
    return () => {
      isMounted.current = false;
    };
  }, [expanded, tagsLoaded, registryId, repository, toastError]);

  // Filter tags by type
  useEffect(() => {
    if (filterType === "all") {
      setFilteredTags(allTags);
      return;
    }
    setFilteredTags(
      allTags.filter((tagItem) => inferArtifactCategory(tagItem) === filterType),
    );
  }, [allTags, filterType]);

  // Get plural form of type name
  const getTypeName = (type: string): string => {
    if (type === "all") return "artifacts";
    // Convert to plural form
    const typeMap: Record<string, string> = {
      chart: "charts",
      image: "images",
      other: "others",
    };
    return typeMap[type] || type;
  };

  const handleCopyPullCommand = (tagName?: string, tagType?: ArtifactCategory) => {
    const baseUrl = registryUrl.replace(/^https?:\/\//, "");
    
    let pullCommand: string;
    if (tagType === "chart") {
      // Helm Chart - use helm pull
      pullCommand = tagName 
        ? `helm pull oci://${baseUrl}/${repository} --version ${tagName}`
        : `helm pull oci://${baseUrl}/${repository}`;
    } else if (tagType === "image") {
      // Docker Image - use docker pull
      pullCommand = tagName
        ? `docker pull ${baseUrl}/${repository}:${tagName}`
        : `docker pull ${baseUrl}/${repository}`;
    } else {
      // Other types - generic format
      pullCommand = `${baseUrl}/${repository}${tagName ? `:${tagName}` : ""}`;
    }
    
    navigator.clipboard.writeText(pullCommand);
    success("Pull command copied to clipboard");
  };

  const handleToggle = () => {
    setExpanded(!expanded);
  };

  const handleLaunch = (tagItem: ArtifactListItem) => {
    setSelectedTag(tagItem);
    setLaunchModalOpen(true);
  };

  const handleCloseLaunchModal = () => {
    setLaunchModalOpen(false);
    setSelectedTag(null);
  };

  return (
    <>
      {/* Launch Modal */}
      {selectedTag && selectedTag.repositoryName && selectedTag.tag && (
        <LaunchModal
          isOpen={launchModalOpen}
          onClose={handleCloseLaunchModal}
          registryId={registryId}
          repositoryName={selectedTag.repositoryName}
          tag={selectedTag.tag}
          artifactType={inferArtifactCategory(selectedTag)}
        />
      )}
    <div className="bg-gray-800/50 border border-gray-700 rounded-lg overflow-hidden">
      {/* Repository Header */}
      <div className="flex items-center justify-between p-3 hover:bg-gray-800 transition group">
        {/* Left: Repository Info */}
        <div
          className="flex items-center gap-3 flex-1 min-w-0 cursor-pointer"
          onClick={handleToggle}
        >
          {/* Expand/Collapse Icon */}
          {expanded ? (
            <ChevronDown className="w-4 h-4 text-gray-400 flex-shrink-0" />
          ) : (
            <ChevronRight className="w-4 h-4 text-gray-400 flex-shrink-0" />
          )}
          <Package className="w-4 h-4 text-blue-400 flex-shrink-0" />
          <span className="text-sm text-gray-200 font-mono truncate" title={repository}>
            {repository}
          </span>
          {/* Registry Name Badge */}
          <span className="px-2 py-0.5 bg-purple-600/20 border border-purple-500/30 rounded text-xs text-purple-300 flex-shrink-0">
            🏷️ {registryName}
          </span>
          {/* Tag Count Badge */}
          {allTags.length > 0 && (
            <span className="px-2 py-0.5 bg-blue-600/20 border border-blue-500/30 rounded text-xs text-blue-300">
              {filteredTags.length}/{allTags.length} {getTypeName(filterType)}
            </span>
          )}
        </div>

        {/* Right: Action Buttons */}
        <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition">
          <button
            onClick={(e) => {
              e.stopPropagation();
              // 使用第一个tag的类型作为默认类型
              const firstTagType = allTags.length > 0 ? inferArtifactCategory(allTags[0]) : undefined;
              handleCopyPullCommand(undefined, firstTagType);
            }}
            className="p-1.5 hover:bg-gray-700 rounded transition"
            title="Copy pull command"
          >
            <Copy className="w-3.5 h-3.5 text-gray-400 hover:text-blue-400" />
          </button>
        </div>
      </div>

      {/* Tags List (shown when expanded) */}
      {expanded && (
        <div className="border-t border-gray-700 bg-gray-900/50 p-3">
          {loading ? (
            <div className="flex items-center justify-center py-6">
              <div className="flex flex-col items-center gap-2">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
                <p className="text-xs text-gray-500">Loading tags...</p>
              </div>
            </div>
          ) : (
            <>
              {/* Filter */}
              {allTags.length > 0 && (
                <div className="flex items-center gap-2 mb-3 pb-3 border-b border-gray-700">
                  <Filter className="w-3.5 h-3.5 text-gray-400" />
                  <span className="text-xs text-gray-400">Type:</span>
                  <div className="flex gap-1">
                    <button
                      onClick={() => setFilterType("chart")}
                      className={`px-2 py-0.5 text-xs rounded transition ${
                        filterType === "chart"
                          ? "bg-green-600 text-white"
                          : "bg-gray-700 text-gray-400 hover:bg-gray-600"
                      }`}
                    >
                      Chart
                    </button>
                    <button
                      onClick={() => setFilterType("image")}
                      className={`px-2 py-0.5 text-xs rounded transition ${
                        filterType === "image"
                          ? "bg-blue-600 text-white"
                          : "bg-gray-700 text-gray-400 hover:bg-gray-600"
                      }`}
                    >
                      Image
                    </button>
                    <button
                      onClick={() => setFilterType("other")}
                      className={`px-2 py-0.5 text-xs rounded transition ${
                        filterType === "other"
                          ? "bg-purple-600 text-white"
                          : "bg-gray-700 text-gray-400 hover:bg-gray-600"
                      }`}
                    >
                      Other
                    </button>
                    <button
                      onClick={() => setFilterType("all")}
                      className={`px-2 py-0.5 text-xs rounded transition ${
                        filterType === "all"
                          ? "bg-gray-600 text-white"
                          : "bg-gray-700 text-gray-400 hover:bg-gray-600"
                      }`}
                    >
                      All
                    </button>
                  </div>
                </div>
              )}

              {/* Error State */}
              {loadError ? (
                <div className="text-center py-4 text-red-400 text-sm">
                  <AlertCircle className="w-8 h-8 mx-auto mb-2" />
                  <p>Failed to load artifacts</p>
                  <p className="text-xs text-gray-500 mt-1">{loadError}</p>
                </div>
              ) : filteredTags.length === 0 ? (
                <div className="text-center py-4 text-gray-500 text-sm">
                  <TagIcon className="w-8 h-8 mx-auto mb-2 opacity-30" />
                  <p>No {filterType === "all" ? "" : getTypeName(filterType)} tags</p>
                </div>
              ) : (
                <div className="space-y-1.5">
                  {filteredTags.map((tagItem, index) => {
                    const category = inferArtifactCategory(tagItem);
                    return (
                      <div
                        key={`${tagItem.tag}-${index}`}
                        className="flex items-center justify-between p-2 bg-gray-800/50 hover:bg-gray-800 rounded transition group/tag"
                      >
                        {/* Tag Info */}
                        <div className="flex items-center gap-2 flex-1 min-w-0">
                          <TagIcon className="w-3.5 h-3.5 text-green-400 flex-shrink-0" />
                          <span className="text-sm text-gray-300 font-mono truncate" title={tagItem.tag}>
                            {tagItem.tag}
                          </span>
                          {/* Artifact Type Badge */}
                          <span
                            className={`px-1.5 py-0.5 text-xs rounded ${
                              category === "chart"
                                ? "bg-green-600/20 text-green-300 border border-green-500/30"
                                : category === "image"
                                ? "bg-blue-600/20 text-blue-300 border border-blue-500/30"
                                : "bg-purple-600/20 text-purple-300 border border-purple-500/30"
                            }`}
                            title={tagItem.mediaType || tagItem.type}
                          >
                            {category}
                          </span>
                          {/* Artifact Size */}
                          {tagItem.size && tagItem.size > 0 && (
                            <span className="text-xs text-gray-500">
                              {(tagItem.size / 1024 / 1024).toFixed(2)} MB
                            </span>
                          )}
                        </div>

                        {/* Tag Action Buttons */}
                        <div className="flex items-center gap-1 opacity-0 group-hover/tag:opacity-100">
                          {/* Launch button - only for chart/helm type */}
                          {category === "chart" && (
                            <button
                              onClick={() => handleLaunch(tagItem)}
                              className="p-1 hover:bg-green-700/50 rounded transition"
                              title={`Launch ${tagItem.tag}`}
                            >
                              <Rocket className="w-3 h-3 text-green-400 hover:text-green-300" />
                            </button>
                          )}
                          <button
                            onClick={() => handleCopyPullCommand(tagItem.tag, category)}
                            className="p-1 hover:bg-gray-700 rounded transition"
                            title={`Copy pull command for ${tagItem.tag}`}
                          >
                            <Copy className="w-3 h-3 text-gray-400 hover:text-blue-400" />
                          </button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </>
          )}
        </div>
      )}
    </div>
    </>
  );
};
