/**
 * Artifacts Browser Page
 * 浏览特定 Repository 的所有 Artifacts (Tags)
 */
import React, { useState, useEffect } from "react";
import { Package, RefreshCw, ArrowLeft, Filter } from "lucide-react";
import { useNavigate, useParams } from "react-router-dom";
import { useToast } from "@/shared";
import { 
  PageHeader, 
  Button, 
  LoadingState, 
  ErrorState, 
  EmptyState,
  Badge
} from "@/shared/components";
import { listArtifacts, listRegistries } from "@/api";
import type { ArtifactListItem, ListArtifactsFilter } from "@/api";
import { TagCard } from "../components/TagCard";
import { globalCache } from "@/shared/services/artifact-cache";
import { SuccessMessages, formatApiError } from "@/shared/utils";

const ArtifactsBrowserPage: React.FC = () => {
  const { registryId, repositoryName } = useParams<{ registryId: string; repositoryName: string }>();
  const navigate = useNavigate();
  const { info: toastInfo, success: toastSuccess, error: toastError } = useToast();

  const [artifacts, setArtifacts] = useState<ArtifactListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [filter, setFilter] = useState<ListArtifactsFilter | undefined>(undefined);
  const [registryName, setRegistryName] = useState<string>("");

  // Decode repository name (URL encoded)
  const decodedRepositoryName = repositoryName ? decodeURIComponent(repositoryName) : "";

  // Load registry info
  useEffect(() => {
    const loadRegistryInfo = async () => {
      if (!registryId) return;
      try {
        const registries = await listRegistries();
        const registry = registries.find(r => r.id === registryId);
        if (registry) {
          setRegistryName(registry.name || "");
        }
      } catch (err) {
        console.error("Failed to load registry info:", err);
      }
    };
    loadRegistryInfo();
  }, [registryId]);

  // Load artifacts
  const loadArtifacts = async (isMounted = { current: true }, skipCache = false, isRefresh = false) => {
    if (!registryId || !decodedRepositoryName) {
      setError("Registry ID or Repository Name is missing");
      setLoading(false);
      return false;
    }

    const filterKey = filter ?? "all";

    if (!skipCache) {
      const cached = globalCache.get<ArtifactListItem[]>(
        "tags",
        registryId,
        decodedRepositoryName,
        filterKey
      );
      if (cached) {
        console.log(`[ArtifactsBrowserPage] Using cached artifacts for ${decodedRepositoryName}`);
        setArtifacts(cached);
        setLoading(false);
        return true;
      }
    }

    if (isRefresh) {
      setRefreshing(true);
    } else {
      setLoading(true);
    }
    setError(null);
    let succeeded = false;
    try {
      const data = await listArtifacts(
        { registryId, repositoryName: decodedRepositoryName },
        filter ? { filter } : undefined
      );
      if (isMounted.current) {
        setArtifacts(data);
        globalCache.set("tags", data, registryId, decodedRepositoryName, filterKey);
        succeeded = true;
      }
    } catch (err) {
      if (isMounted.current) {
        const errorMsg = formatApiError(err) || "Failed to load artifacts";
        setError(errorMsg);
        toastError(errorMsg);
        console.error(err);
      }
    } finally {
      if (isMounted.current) {
        if (isRefresh) {
          setRefreshing(false);
        } else {
          setLoading(false);
        }
      }
    }
    return succeeded;
  };

  useEffect(() => {
    const isMounted = { current: true };
    loadArtifacts(isMounted);
    return () => {
      isMounted.current = false;
    };
  }, [registryId, decodedRepositoryName, filter]);

  const handleRefresh = async () => {
    toastInfo("Refreshing artifacts...", {
      title: "Artifacts Refresh",
      durationMs: 1800,
      mergeKey: "artifacts-refresh",
    });
    globalCache.clearAll();
    const refreshed = await loadArtifacts({ current: true }, true, true);
    if (refreshed) {
      toastSuccess(SuccessMessages.DATA_REFRESHED);
    }
  };

  const handleBack = () => {
    if (registryId) {
      navigate(`/artifact/registries/${registryId}`);
    } else {
      navigate("/artifact/registries");
    }
  };

  const filterOptions: Array<{ value: ListArtifactsFilter | undefined; label: string }> = [
    { value: undefined, label: "All Types" },
    { value: "chart", label: "Helm Charts" },
    { value: "image", label: "Container Images" },
    { value: "other", label: "Other" },
  ];

  return (
    <div className="p-6">
      {/* Header */}
      <PageHeader
        title={`Artifacts - ${decodedRepositoryName}`}
        description={`Browse artifacts in ${registryName || registryId || "registry"}`}
        icon={Package}
        iconColor="text-purple-400"
        actions={
          <>
            <Button
              variant="secondary"
              icon={ArrowLeft}
              onClick={handleBack}
            >
              Back
            </Button>
            <Button
              variant="secondary"
              icon={RefreshCw}
              onClick={handleRefresh}
              loading={refreshing}
              spinIcon={true}
            >
              Refresh
            </Button>
          </>
        }
      />

      {/* Filter Bar */}
      {!loading && !error && (
        <div className="mt-4 flex items-center gap-3">
          <Filter className="w-4 h-4 text-gray-400" />
          <span className="text-sm text-gray-400">Filter by type:</span>
          <div className="flex gap-2">
            {filterOptions.map((option) => (
              <button
                key={option.value || "all"}
                onClick={() => setFilter(option.value)}
                className={`px-3 py-1.5 text-xs font-medium rounded transition-colors ${
                  filter === option.value
                    ? "bg-purple-600 text-white"
                    : "bg-dark-lighter text-gray-300 hover:bg-dark-border"
                }`}
              >
                {option.label}
              </button>
            ))}
          </div>
          {filter && (
            <Badge variant="info">
              {artifacts.length} {filter} artifact{artifacts.length !== 1 ? "s" : ""}
            </Badge>
          )}
        </div>
      )}

      {/* Loading State */}
      {loading && <LoadingState message="Loading artifacts..." />}

      {/* Error State */}
      {error && !loading && (
        <ErrorState message={error} onRetry={handleRefresh} />
      )}

      {/* Empty State */}
      {!loading && !error && artifacts.length === 0 && (
        <EmptyState
          icon={Package}
          title="No Artifacts Found"
          description={
            filter
              ? `No ${filter} artifacts found in this repository`
              : "This repository doesn't contain any artifacts yet"
          }
          action={{
            label: "Back to Repositories",
            icon: ArrowLeft,
            onClick: handleBack,
          }}
        />
      )}

      {/* Artifacts Grid */}
      {!loading && !error && artifacts.length > 0 && (
        <div className="mt-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {artifacts.map((artifact, index) => (
              <TagCard
                key={`${artifact.repositoryName || "repo"}-${artifact.tag || index}`}
                registryId={registryId || ""}
                tag={artifact}
              />
            ))}
          </div>
        </div>
      )}

      {/* Breadcrumb Info */}
      {!loading && artifacts.length > 0 && (
        <div className="mt-6 p-4 bg-dark-card border border-dark-border rounded-lg">
          <div className="flex items-center gap-2 text-sm text-gray-400">
            <span>Registry:</span>
            <span className="text-white font-medium">{registryName || registryId}</span>
            <span className="mx-2">/</span>
            <span>Repository:</span>
            <span className="text-white font-medium">{decodedRepositoryName}</span>
            <span className="mx-2">/</span>
            <span>Artifacts:</span>
            <span className="text-white font-medium">{artifacts.length}</span>
          </div>
        </div>
      )}
    </div>
  );
};

export default ArtifactsBrowserPage;
