/**
 * Cluster Configuration Page
 * Manage Kubernetes cluster configurations
 */
import React, { useState, useEffect } from "react";
import { Plus, RefreshCw, Server } from "lucide-react";
import { useToast, Modal, Button, PageHeader } from "@/shared";
import { useAuth } from "@/app/providers";
import { isAdminUser } from "@/app/providers/auth-model";
import { ClusterErrors, SuccessMessages, formatApiError } from "@/shared/utils";
import { ClusterForm } from "../components/ClusterForm";
import { ClusterList } from "../components/ClusterList";
import {
  listClusters,
  createCluster,
  updateCluster,
  deleteCluster,
  getClusterHealth,
} from "@/api";
import type { ClusterConfig, ClusterResponse } from "@/core/types";

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

  const [clusters, setClusters] = useState<ClusterConfig[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [editingCluster, setEditingCluster] = useState<ClusterConfig | undefined>(undefined);

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

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

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

  // Add cluster
  const handleAdd = () => {
    setEditingCluster(undefined);
    setShowModal(true);
  };

  // Edit cluster
  const handleEdit = (cluster: ClusterResponse) => {
    setEditingCluster(cluster);
    setShowModal(true);
  };

  // Save cluster
  const handleSave = async (
    data: Omit<ClusterResponse, "id" | "createdAt" | "updatedAt">
  ) => {
    try {
      const actionLabel = editingCluster ? "Updating cluster..." : "Creating cluster...";
      toastInfo(actionLabel, {
        title: editingCluster ? "Update Cluster" : "Create Cluster",
        durationMs: 1800,
        mergeKey: editingCluster ? `cluster-save-${editingCluster.id}` : "cluster-create",
      });

      if (editingCluster) {
        if (!editingCluster.id) {
          toastError("Cluster identifier is missing. Please refresh and try again.");
          return;
        }
        await updateCluster({ clusterId: editingCluster.id }, data);
        success(SuccessMessages.CLUSTER_UPDATED);
      } else {
        // Build create data with only non-empty auth fields
        const createData: any = {
          name: data.name,
          host: data.host,
          description: data.description,
        };
        
        // Add certificate auth if all three fields are provided
        if (data.caData && data.certData && data.keyData) {
          createData.caData = data.caData;
          createData.certData = data.certData;
          createData.keyData = data.keyData;
        }
        
        // Add token auth if provided
        if (data.token) {
          createData.token = data.token;
        }
        
        await createCluster(createData);
        success(SuccessMessages.CLUSTER_CREATED);
      }
      setShowModal(false);
      setEditingCluster(undefined);
      loadClusters({ current: true });
    } catch (error) {
      const errorMsg = editingCluster ? ClusterErrors.UPDATE_FAILED : ClusterErrors.CREATE_FAILED;
      toastError(formatApiError(error) || errorMsg);
      console.error(error);
    }
  };

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

    try {
      toastInfo(`Deleting cluster "${cluster.name}"...`, {
        title: "Delete Cluster",
        durationMs: 1800,
        mergeKey: `cluster-delete-${cluster.id}`,
      });
      if (!cluster.id) {
        toastError("Cluster identifier is missing. Please refresh and try again.");
        return;
      }
      await deleteCluster({ clusterId: cluster.id });
      success(SuccessMessages.CLUSTER_DELETED);
      loadClusters({ current: true });
    } catch (error) {
      toastError(formatApiError(error) || ClusterErrors.DELETE_FAILED);
      console.error(error);
    }
  };

  const handleHealthCheck = async (cluster: ClusterResponse) => {
    if (!cluster.id) {
      toastError("Cluster identifier is missing. Please refresh and try again.");
      return;
    }

    toastInfo(`Testing cluster "${cluster.name}"...`, {
      title: "Cluster Health",
      durationMs: 1800,
      mergeKey: `cluster-health-${cluster.id}`,
    });

    try {
      const result = await getClusterHealth({ clusterId: cluster.id }) as any;
      if (result.healthy === false) {
        toastError(result.message || ClusterErrors.CONNECTION_FAILED);
        return;
      }
      success(result.message || SuccessMessages.OPERATION_COMPLETED);
    } catch (error) {
      toastError(formatApiError(error) || ClusterErrors.CONNECTION_FAILED);
    }
  };

  return (
    <div className="p-6">
      {/* Header */}
      <PageHeader
        title="Configuration - Clusters"
        description={
          isAdmin
            ? "Manage all Kubernetes cluster connections and authentication"
            : "Manage your private Kubernetes cluster connections"
        }
        icon={Server}
        iconColor="text-blue-400"
        actions={
          <>
            <Button
              variant="secondary"
              icon={RefreshCw}
              onClick={handleRefresh}
              loading={refreshing}
              spinIcon={true}
            >
              Refresh
            </Button>
            <Button
              variant="primary"
              icon={Plus}
              onClick={handleAdd}
              className="bg-blue-600 hover:bg-blue-700 border-blue-600"
            >
              Add Cluster
            </Button>
          </>
        }
      />

      {/* Cluster List */}
      <ClusterList
        clusters={clusters}
        loading={loading}
        onEdit={handleEdit}
        onDelete={handleDelete}
        onHealthCheck={handleHealthCheck}
        user={user}
      />

      {/* Add/Edit Modal */}
      <Modal
        open={showModal}
        onClose={() => {
          setShowModal(false);
          setEditingCluster(undefined);
        }}
        title={editingCluster ? "Edit Cluster Configuration" : "Add Cluster Configuration"}
      >
        <ClusterForm
          cluster={editingCluster}
          onSave={handleSave}
          onCancel={() => {
            setShowModal(false);
            setEditingCluster(undefined);
          }}
        />
      </Modal>
    </div>
  );
};

export default ClusterConfigPage;
