/**
 * Registry Configuration Page
 * Manage OCI Registry configurations
 */
import React, { useState, useEffect } from "react";
import { Plus, RefreshCw, Database } from "lucide-react";
import { useToast } from "@/shared";
import { useAuth } from "@/app/providers";
import { isAdminUser } from "@/app/providers/auth-model";
import { Modal, PageHeader, Button } from "@/shared/components";
import { RegistryErrors, SuccessMessages, formatApiError } from "@/shared/utils";
import { RegistryForm } from "../components/RegistryForm";
import { RegistryList } from "../components/RegistryList";
import {
  listRegistries,
  createRegistry,
  updateRegistry,
  deleteRegistry,
} from "@/api";
import type { CreateRegistryRequest } from "@/api";
import type { AppRegistry, RegistryResponse } from "@/core/types";

const RegistryConfigPage: React.FC = () => {
  const { success, error: toastError, info: toastInfo } = useToast();
  const { user } = useAuth();
  const isAdmin = isAdminUser(user);

  const [registries, setRegistries] = useState<AppRegistry[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [editingRegistry, setEditingRegistry] = useState<AppRegistry | undefined>(undefined);

  // Load registries
  const loadRegistries = async (isMounted = { current: true }, isRefresh = false) => {
    if (isRefresh) {
      setRefreshing(true);
    } else {
      setLoading(true);
    }
    let succeeded = false;
    try {
      const data = await listRegistries();
      // Only update state if component is still mounted
      if (isMounted.current) {
        setRegistries(data);
        succeeded = true;
      }
    } catch (err) {
      if (isMounted.current) {
        toastError(formatApiError(err) || RegistryErrors.LOAD_FAILED);
        console.error(err);
      }
    } finally {
      if (isMounted.current) {
        if (isRefresh) {
          setRefreshing(false);
        } else {
          setLoading(false);
        }
      }
    }
    return succeeded;
  };

  useEffect(() => {
    const isMounted = { current: true };
    loadRegistries(isMounted);
    
    // Cleanup: mark component as unmounted
    return () => {
      isMounted.current = false;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Refresh registries
  const handleRefresh = async () => {
    toastInfo("Refreshing registries...", {
      title: "Registry Refresh",
      durationMs: 1800,
      mergeKey: "registries-refresh",
    });
    const refreshed = await loadRegistries({ current: true }, true);
    if (refreshed) {
      success(SuccessMessages.DATA_REFRESHED);
    }
  };

  // Add registry
  const handleAdd = () => {
    setEditingRegistry(undefined);
    setShowModal(true);
  };

  // Edit registry
  const handleEdit = (registry: RegistryResponse) => {
    setEditingRegistry(registry);
    setShowModal(true);
  };

  // Save registry
  const handleSave = async (data: Omit<RegistryResponse, "id">) => {
    try {
      const actionLabel = editingRegistry ? "Updating registry..." : "Creating registry...";
      toastInfo(actionLabel, {
        title: editingRegistry ? "Update Registry" : "Create Registry",
        durationMs: 1800,
        mergeKey: editingRegistry ? `registry-save-${editingRegistry.id}` : "registry-create",
      });

      if (editingRegistry) {
        if (!editingRegistry.id) {
          toastError("Registry identifier is missing. Please refresh and try again.");
          return;
        }
        await updateRegistry({ registryId: editingRegistry.id }, data);
        success(SuccessMessages.REGISTRY_UPDATED);
      } else {
        if (!data.name || !data.url || !data.username || !data.password) {
          toastError("Name, URL, username, and password are required to create a registry.");
          return;
        }
        const createData: CreateRegistryRequest = {
          name: data.name,
          url: data.url,
          username: data.username,
          password: data.password,
          description: data.description || "",
          insecure: data.insecure ?? false,
        };
        const newRegistry = await createRegistry(createData);
        success(SuccessMessages.REGISTRY_CREATED);
        console.log("New registry added:", newRegistry);
      }
      setShowModal(false);
      setEditingRegistry(undefined);
      await loadRegistries({ current: true });
      
      // Notify other pages to refresh (if registry browser is open)
      localStorage.setItem('registry_updated', Date.now().toString());
      localStorage.removeItem('registry_updated');
    } catch (error) {
      const errorMsg = editingRegistry ? RegistryErrors.UPDATE_FAILED : RegistryErrors.CREATE_FAILED;
      toastError(formatApiError(error) || errorMsg);
      console.error("Registry save error:", error);
      
      // Don't close modal so user can retry
      throw error;
    }
  };

  // Delete registry
  const handleDelete = async (registry: RegistryResponse) => {
    if (!confirm(`Are you sure you want to delete registry "${registry.name}"? This action cannot be undone.`)) {
      return;
    }

    try {
      toastInfo(`Deleting registry "${registry.name}"...`, {
        title: "Delete Registry",
        durationMs: 1800,
        mergeKey: `registry-delete-${registry.id}`,
      });
      if (!registry.id) {
        toastError("Registry identifier is missing. Please refresh and try again.");
        return;
      }
      await deleteRegistry({ registryId: registry.id });
      success(SuccessMessages.REGISTRY_DELETED);
      loadRegistries({ current: true });
    } catch (error) {
      toastError(formatApiError(error) || RegistryErrors.DELETE_FAILED);
      console.error(error);
    }
  };

  return (
    <div className="p-6">
      {/* Header */}
      <PageHeader
        title="Configuration - Registries"
        description={
          isAdmin
            ? "Manage all OCI registry connections and authentication"
            : "Manage your private OCI registry connections"
        }
        icon={Database}
        iconColor="text-blue-600"
        actions={
          <>
            <Button
              variant="secondary"
              icon={RefreshCw}
              onClick={handleRefresh}
              loading={refreshing}
              spinIcon={true}
            >
              Refresh
            </Button>
            <Button
              variant="primary"
              icon={Plus}
              onClick={handleAdd}
            >
              Add Registry
            </Button>
          </>
        }
      />

      {/* Registry List */}
      <RegistryList
        registries={registries}
        loading={loading}
        onEdit={handleEdit}
        onDelete={handleDelete}
        user={user}
      />

      {/* Add/Edit Modal */}
      <Modal
        open={showModal}
        onClose={() => {
          setShowModal(false);
          setEditingRegistry(undefined);
        }}
        title={editingRegistry ? "Edit Registry Configuration" : "Add Registry Configuration"}
        icon={Database}
        size="lg"
      >
        <RegistryForm
          registry={editingRegistry}
          onSave={handleSave}
          onCancel={() => {
            setShowModal(false);
            setEditingRegistry(undefined);
          }}
        />
      </Modal>
    </div>
  );
};

export default RegistryConfigPage;
