/**
 * Registries Browser Page
 * Display all registries and their repositories
 */
import React, { useState, useEffect } from "react";
import { Database, RefreshCw, Plus } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { useToast } from "@/shared";
import { 
  PageHeader, 
  Button, 
  LoadingState, 
  ErrorState, 
  EmptyState 
} from "@/shared/components";
import { RegistryTreeExplorer } from "../components/RegistryTreeExplorer";
import { listRegistries } from "@/api";
import type { AppRegistry } from "@/core/types";
import { globalCache } from "@/shared/services/artifact-cache";
import { RegistryErrors, SuccessMessages, formatApiError } from "@/shared/utils";

const RegistriesBrowserPage: React.FC = () => {
  const { info: toastInfo, success: toastSuccess, error: toastError } = useToast();
  const navigate = useNavigate();

  const [registries, setRegistries] = useState<AppRegistry[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Load registries with global cache
  const loadRegistries = async (
    isMounted = { current: true },
    skipCache = false,
    isRefresh = false
  ) => {
    let succeeded = false;
    if (!skipCache) {
      // Check global cache first
      const cachedRegistries = globalCache.get<AppRegistry[]>('registries');
      if (cachedRegistries) {
        console.log('[RegistriesBrowserPage] Using cached registries');
        setRegistries(cachedRegistries);
        setLoading(false);
        return true;
      }
    }

    if (isRefresh) {
      setRefreshing(true);
    } else {
      setLoading(true);
    }
    setError(null);
    try {
      const data = await listRegistries();
      if (isMounted.current) {
        setRegistries(data);
        // Cache registries list (30 minutes TTL)
        globalCache.set('registries', data);
        succeeded = true;
      }
    } catch (err) {
      if (isMounted.current) {
        const errorMsg = formatApiError(err) || RegistryErrors.LOAD_FAILED;
        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 };
    loadRegistries(isMounted);

    // Listen for storage events to auto-refresh when registries are added
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === 'registry_updated') {
        console.log('[RegistriesBrowserPage] Detected registry update, refreshing...');
        loadRegistries(isMounted);
      }
    };

    window.addEventListener('storage', handleStorageChange);

    return () => {
      isMounted.current = false;
      window.removeEventListener('storage', handleStorageChange);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Refresh handler
  const handleRefresh = async () => {
    toastInfo("Refreshing registry list and clearing cache...", {
      title: "Registry Browser Refresh",
      durationMs: 1800,
      mergeKey: "registry-browser-refresh",
    });
    // Clear all caches to force reload all data
    globalCache.clearAll();
    const refreshed = await loadRegistries({ current: true }, true, true); // skipCache = true, refresh
    if (refreshed) {
      toastSuccess(SuccessMessages.DATA_REFRESHED);
    }
  };

  // Navigate to config page
  const handleAddRegistry = () => {
    navigate("/configuration/registries");
  };

  return (
    <div className="p-6">
      {/* Header */}
      <PageHeader
        title="Artifact - Registries"
        description="Browse all OCI registries and their artifacts"
        icon={Database}
        iconColor="text-purple-400"
        actions={
          <>
            <Button
              variant="secondary"
              icon={RefreshCw}
              onClick={handleRefresh}
              loading={refreshing}
              spinIcon={true}
            >
              Refresh
            </Button>
            <Button
              variant="primary"
              icon={Plus}
              onClick={handleAddRegistry}
            >
              Add Registry
            </Button>
          </>
        }
      />

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

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

      {/* Empty State */}
      {!loading && !error && registries.length === 0 && (
        <EmptyState
          icon={Database}
          title="No Registries Found"
          description="Add your first OCI registry to start managing artifacts"
          action={{
            label: "Add Registry",
            icon: Plus,
            onClick: handleAddRegistry,
          }}
        />
      )}

      {/* Registry Tree Explorer (Three-Level Layout) */}
      {!loading && !error && registries.length > 0 && (
        <RegistryTreeExplorer registries={registries} />
      )}
    </div>
  );
};

export default RegistriesBrowserPage;
