import { useState, useEffect, useCallback } from 'react';
import { useKubeconfigs } from './useKubeconfigs';

// Helper function para executar kubectl com kubeconfig ativo
const useKubectlExecutor = () => {
  const { activeConfig } = useKubeconfigs();

  const executeWithKubeconfig = async (
    command: string,
  ): Promise<KubectlResponse> => {
    try {
      console.log(
        '🚀 Executing kubectl with config:',
        activeConfig?.name,
        'path:',
        activeConfig?.path,
      );
      console.log('📝 Command:', command);

      const response: KubectlResponse =
        await window.electron?.ipcRenderer.executeKubectl(
          command,
          activeConfig?.path,
        );
      return response;
    } catch (error) {
      return {
        success: false,
        data: null,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  };

  return executeWithKubeconfig;
};

export interface NodeCapacity {
  cpu: string;
  memory: string;
  pods: string;
  'ephemeral-storage': string;
}

export interface NodeAddresses {
  internalIP: string;
  externalIP: string;
  hostname: string;
}

export interface NodeStatus {
  ready: boolean;
  readyMessage: string;
  conditions: any[];
}

export interface NodeInfo {
  name: string;
  labels: Record<string, string>;
  // Original node info
  architecture: string;
  bootID: string;
  containerRuntimeVersion: string;
  kernelVersion: string;
  kubeProxyVersion: string;
  kubeletVersion: string;
  machineID: string;
  operatingSystem: string;
  osImage: string;
  systemUUID: string;
  // New fields
  addresses: NodeAddresses;
  capacity: NodeCapacity;
  allocatable: NodeCapacity;
  status: NodeStatus;
}

export interface KubectlResponse {
  success: boolean;
  data: any;
  error: string | null;
}

export function useNodesInfo() {
  const [nodes, setNodes] = useState<NodeInfo[]>([]);
  const { activeConfig } = useKubeconfigs();
  const [loading, setLoading] = useState(!!activeConfig?.path);
  const [error, setError] = useState<string | null>(null);

  const fetchNodes = async () => {
    try {
      console.log(
        '🚀 useNodesInfo: Fetching nodes with kubeconfig:',
        activeConfig?.name,
        activeConfig?.path,
      );
      setLoading(true);
      setError(null);

      const response: KubectlResponse =
        await window.electron?.ipcRenderer.getNodesInfo(activeConfig?.path);

      if (response.success) {
        console.log('✅ useNodesInfo: Nodes fetched successfully');
        setNodes(response.data);
      } else {
        console.error(
          '❌ useNodesInfo: Failed to fetch nodes:',
          response.error,
        );
        setError(response.error || 'Failed to fetch nodes');
      }
    } catch (err) {
      console.error('❌ useNodesInfo: Error:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log('⏳ useNodesInfo: Waiting for activeConfig to be loaded');
      setLoading(false);
      setNodes([]);
      return;
    }
    console.log('🔄 useNodesInfo: activeConfig changed, re-fetching nodes');
    fetchNodes();
  }, [activeConfig?.path]);

  return {
    nodes,
    loading,
    error,
    refetch: fetchNodes,
  };
}

export function useNodeDetails(nodeName: string) {
  const [nodeDetails, setNodeDetails] = useState<NodeInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { activeConfig } = useKubeconfigs();

  const fetchNodeDetails = async () => {
    try {
      setLoading(true);
      setError(null);

      const response: KubectlResponse =
        await window.electron?.ipcRenderer.getNodeDetails(
          nodeName,
          activeConfig?.path,
        );

      if (response.success) {
        setNodeDetails(response.data);
      } else {
        setError(response.error || 'Failed to fetch node details');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log('⏳ useNodeDetails: Waiting for activeConfig to be loaded');
      return;
    }
    if (nodeName) {
      fetchNodeDetails();
    }
  }, [nodeName, activeConfig?.path]);

  return {
    nodeDetails,
    loading,
    error,
    refetch: fetchNodeDetails,
  };
}

export function useNodePods(nodeName: string) {
  const [podStats, setPodStats] = useState<{
    total: number;
    running: number;
    available: number;
  } | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { activeConfig } = useKubeconfigs();

  const fetchNodePods = async () => {
    try {
      setLoading(true);
      setError(null);

      const response: KubectlResponse =
        await window.electron?.ipcRenderer.getNodePods(
          nodeName,
          activeConfig?.path,
        );

      if (response.success) {
        setPodStats({
          total: response.data.total,
          running: response.data.running,
          available: response.data.total,
        });
      } else {
        setError(response.error || 'Failed to fetch node pods');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log('⏳ useNodePods: Waiting for activeConfig to be loaded');
      return;
    }
    if (nodeName) {
      fetchNodePods();
    }
  }, [nodeName, activeConfig?.path]);

  return {
    podStats,
    loading,
    error,
    refetch: fetchNodePods,
  };
}

export function useNodeMetrics(nodeName: string) {
  const [metrics, setMetrics] = useState<{
    cpuUsed: string;
    cpuPercent: string;
    memoryUsed: string;
    memoryPercent: string;
  } | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { activeConfig } = useKubeconfigs();

  const fetchNodeMetrics = async () => {
    try {
      setLoading(true);
      setError(null);

      const response: KubectlResponse =
        await window.electron?.ipcRenderer.getNodeMetrics(
          nodeName,
          activeConfig?.path,
        );

      if (response.success) {
        setMetrics(response.data);
      } else {
        setError(response.error || 'Failed to fetch node metrics');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (nodeName) {
      fetchNodeMetrics();
    }
  }, [nodeName, activeConfig?.path]);

  return {
    metrics,
    loading,
    error,
    refetch: fetchNodeMetrics,
  };
}

export interface NamespaceInfo {
  name: string;
  status: string;
  age: string;
  creationTimestamp: string;
  labels: Record<string, string>;
  annotations: Record<string, string>;
  resourceQuota?: {
    hard: Record<string, string>;
    used: Record<string, string>;
  };
}

export function useNamespacesInfo() {
  const [namespaces, setNamespaces] = useState<NamespaceInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const executeKubectl = useKubectlExecutor();
  const { activeConfig } = useKubeconfigs();

  const fetchNamespaces = async () => {
    try {
      setLoading(true);
      setError(null);

      const response: KubectlResponse = await executeKubectl(
        'kubectl get namespaces -o json',
      );

      if (response.success) {
        let parsedData;
        try {
          // Parse the JSON string response
          parsedData =
            typeof response.data === 'string'
              ? JSON.parse(response.data)
              : response.data;
        } catch (parseError) {
          console.error('Error parsing namespaces JSON:', parseError);
          setError('Failed to parse namespaces data');
          return;
        }

        const namespacesData =
          parsedData.items?.map((ns: any) => ({
            name: ns.metadata.name,
            status: ns.status.phase,
            age: ns.metadata.creationTimestamp,
            creationTimestamp: ns.metadata.creationTimestamp,
            labels: ns.metadata.labels || {},
            annotations: ns.metadata.annotations || {},
          })) || [];

        setNamespaces(namespacesData);
      } else {
        console.error('Namespaces fetch failed:', response.error);
        setError(response.error || 'Failed to fetch namespaces');
      }
    } catch (err) {
      console.error('Namespaces fetch error:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log(
        '⏳ useNamespacesInfo: Waiting for activeConfig to be loaded',
      );
      setLoading(false);
      return;
    }
    fetchNamespaces();
  }, [activeConfig?.path]);

  return {
    namespaces,
    loading,
    error,
    refetch: fetchNamespaces,
  };
}

export function useNamespaceDetails(namespaceName: string) {
  const [namespaceInfo, setNamespaceInfo] = useState<any>(null);
  const [resources, setResources] = useState<{
    pods: any[];
    services: any[];
    configMaps: any[];
    secrets: any[];
    deployments: any[];
    replicaSets: any[];
  }>({
    pods: [],
    services: [],
    configMaps: [],
    secrets: [],
    deployments: [],
    replicaSets: [],
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { activeConfig } = useKubeconfigs();

  const fetchNamespaceDetails = async () => {
    try {
      setLoading(true);
      setError(null);

      // Get namespace info
      const nsResponse: KubectlResponse =
        await window.electron?.ipcRenderer.executeKubectl(
          `kubectl get namespace ${namespaceName} -o json`,
          activeConfig?.path,
        );

      if (!nsResponse.success) {
        setError(nsResponse.error || 'Failed to fetch namespace details');
        return;
      }

      const nsData =
        typeof nsResponse.data === 'string'
          ? JSON.parse(nsResponse.data)
          : nsResponse.data;
      setNamespaceInfo(nsData);

      // Get all resources in parallel
      const [
        podsRes,
        servicesRes,
        configMapsRes,
        secretsRes,
        deploymentsRes,
        replicaSetsRes,
      ] = await Promise.all([
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get pods -n ${namespaceName} -o json`,
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get services -n ${namespaceName} -o json`,
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get configmaps -n ${namespaceName} -o json`,
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get secrets -n ${namespaceName} -o json`,
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get deployments -n ${namespaceName} -o json`,
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get replicasets -n ${namespaceName} -o json`,
          activeConfig?.path,
        ),
      ]);

      const parseResponse = (response: KubectlResponse) => {
        if (!response.success) return [];
        try {
          const data =
            typeof response.data === 'string'
              ? JSON.parse(response.data)
              : response.data;
          return data.items || [];
        } catch {
          return [];
        }
      };

      setResources({
        pods: parseResponse(podsRes),
        services: parseResponse(servicesRes),
        configMaps: parseResponse(configMapsRes),
        secrets: parseResponse(secretsRes),
        deployments: parseResponse(deploymentsRes),
        replicaSets: parseResponse(replicaSetsRes),
      });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (namespaceName) {
      fetchNamespaceDetails();
    }
  }, [namespaceName, activeConfig?.path]);

  return {
    namespaceInfo,
    resources,
    loading,
    error,
    refetch: fetchNamespaceDetails,
  };
}

export interface DeploymentInfo {
  name: string;
  namespace: string;
  replicas: number;
  readyReplicas: number;
  availableReplicas: number;
  unavailableReplicas: number;
  updatedReplicas: number;
  hasPodIssues: boolean;
  status: string;
  creationTimestamp: string;
  labels: Record<string, string>;
  images: string[];
  conditions: any[];
}

export interface StatefulSetInfo {
  name: string;
  namespace: string;
  replicas: number;
  readyReplicas: number;
  currentReplicas: number;
  updatedReplicas: number;
  hasPodIssues: boolean;
  status: string;
  creationTimestamp: string;
  labels: Record<string, string>;
  images: string[];
  conditions: any[];
  serviceName?: string;
}

export interface DaemonSetInfo {
  name: string;
  namespace: string;
  desiredNumberScheduled: number;
  currentNumberScheduled: number;
  numberMisscheduled: number;
  numberReady: number;
  updatedNumberScheduled: number;
  numberAvailable: number;
  hasPodIssues: boolean;
  status: string;
  creationTimestamp: string;
  labels: Record<string, string>;
  images: string[];
  conditions: any[];
}

export interface IngressInfo {
  name: string;
  namespace: string;
  className?: string;
  hosts: string[];
  addresses: string[];
  ports: string[];
  age: string;
  creationTimestamp: string;
  labels: Record<string, string>;
  annotations: Record<string, string>;
  rules: any[];
  tls: any[];
}

export interface ServiceInfo {
  name: string;
  namespace: string;
  type: string;
  clusterIP: string;
  externalIPs: string[];
  ports: Array<{
    name?: string;
    port: number;
    targetPort: string | number;
    protocol: string;
    nodePort?: number;
  }>;
  selector: Record<string, string>;
  sessionAffinity: string;
  age: string;
  creationTimestamp: string;
  labels: Record<string, string>;
  annotations: Record<string, string>;
}

export interface ConfigMapInfo {
  name: string;
  namespace: string;
  dataCount: number;
  age: string;
  creationTimestamp: string;
  labels: Record<string, string>;
  annotations: Record<string, string>;
  data: Record<string, string>;
  binaryData?: Record<string, string>;
}

export interface SecretInfo {
  name: string;
  namespace: string;
  type: string;
  dataCount: number;
  age: string;
  creationTimestamp: string;
  labels: Record<string, string>;
  annotations: Record<string, string>;
}

export function useDeploymentsInfo() {
  const [deployments, setDeployments] = useState<DeploymentInfo[]>([]);
  const [namespaces, setNamespaces] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchDeployments = async (isBackground = false) => {
    try {
      // Only show loading spinner on initial load, not on background refreshes
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      // 🚀 Fazer três requisições em paralelo: deployments + pods + namespaces
      const [deploymentsResponse, podsResponse, namespacesResponse] =
        await Promise.all([
          window.electron?.ipcRenderer.executeKubectl(
            'kubectl get deployments -A -o json',
            activeConfig?.path,
          ),
          window.electron?.ipcRenderer.executeKubectl(
            'kubectl get pods -A -o json',
            activeConfig?.path,
          ),
          window.electron?.ipcRenderer.executeKubectl(
            'kubectl get namespaces -o json',
            activeConfig?.path,
          ),
        ]);

      if (
        deploymentsResponse.success &&
        podsResponse.success &&
        namespacesResponse.success
      ) {
        let deploymentsData;
        let podsData;
        let namespacesData;
        try {
          deploymentsData =
            typeof deploymentsResponse.data === 'string'
              ? JSON.parse(deploymentsResponse.data)
              : deploymentsResponse.data;

          podsData =
            typeof podsResponse.data === 'string'
              ? JSON.parse(podsResponse.data)
              : podsResponse.data;

          namespacesData =
            typeof namespacesResponse.data === 'string'
              ? JSON.parse(namespacesResponse.data)
              : namespacesResponse.data;
        } catch (parseError) {
          console.error('Error parsing JSON:', parseError);
          setError('Failed to parse data');
          return;
        }

        // 🔍 Identificar pods quebrados
        const brokenPods = (podsData.items || []).filter((pod: any) => {
          const containerStatuses = pod.status?.containerStatuses || [];
          const phase = pod.status?.phase;

          // Pod com problemas se:
          return (
            phase === 'Pending' ||
            phase === 'Failed' ||
            containerStatuses.some(
              (container: any) =>
                container.state?.waiting?.reason === 'ImagePullBackOff' ||
                container.state?.waiting?.reason === 'ErrImagePull' ||
                container.state?.waiting?.reason === 'CrashLoopBackOff' ||
                container.state?.waiting?.reason ===
                  'CreateContainerConfigError' ||
                (container.state?.terminated &&
                  container.state.terminated.exitCode !== 0),
            )
          );
        });

        // 🎯 Mapear pods quebrados para deployments usando selectors
        const deploymentsWithIssues = new Set();

        // Primeiro, criar um mapa de pods quebrados por namespace e labels
        const brokenPodsByNamespace = new Map();
        brokenPods.forEach((pod: any) => {
          const namespace = pod.metadata?.namespace;
          const labels = pod.metadata?.labels || {};

          if (!brokenPodsByNamespace.has(namespace)) {
            brokenPodsByNamespace.set(namespace, []);
          }
          brokenPodsByNamespace.get(namespace).push(labels);
        });

        // 📋 Processar deployments e adicionar flag de problemas
        const processedDeployments =
          deploymentsData.items?.map((deployment: any) => {
            const containers =
              deployment.spec?.template?.spec?.containers || [];
            const images = containers.map((container: any) => container.image);

            const deploymentNamespace = deployment.metadata?.namespace;
            const deploymentName = deployment.metadata?.name;
            const matchLabels = deployment.spec?.selector?.matchLabels || {};

            // Verificar se há pods quebrados que fazem match com os selectors deste deployment
            let hasPodIssues = false;
            if (brokenPodsByNamespace.has(deploymentNamespace)) {
              const brokenPodsInNamespace =
                brokenPodsByNamespace.get(deploymentNamespace);

              hasPodIssues = brokenPodsInNamespace.some((podLabels: any) => {
                // Verificar se todos os matchLabels do deployment estão presentes no pod
                return Object.entries(matchLabels).every(
                  ([key, value]) => podLabels[key] === value,
                );
              });
            }

            return {
              name: deployment.metadata?.name || '',
              namespace: deployment.metadata?.namespace || '',
              replicas: deployment.spec?.replicas || 0,
              readyReplicas: deployment.status?.readyReplicas || 0,
              availableReplicas: deployment.status?.availableReplicas || 0,
              unavailableReplicas: deployment.status?.unavailableReplicas || 0,
              updatedReplicas: deployment.status?.updatedReplicas || 0,
              hasPodIssues, // 🚨 Nova flag!
              status:
                deployment.status?.conditions?.find(
                  (c: any) => c.type === 'Available',
                )?.status === 'True'
                  ? 'Available'
                  : 'Unavailable',
              creationTimestamp: deployment.metadata?.creationTimestamp || '',
              labels: deployment.metadata?.labels || {},
              images,
              conditions: deployment.status?.conditions || [],
            };
          }) || [];

        // Extract all namespaces from the cluster
        const allNamespaces = (namespacesData.items || [])
          .map((ns: any) => ns.metadata.name)
          .sort();

        setDeployments(processedDeployments);
        setNamespaces(allNamespaces);
      } else {
        console.error(
          'Fetch failed:',
          deploymentsResponse.error ||
            podsResponse.error ||
            namespacesResponse.error,
        );
        setError(
          deploymentsResponse.error ||
            podsResponse.error ||
            namespacesResponse.error ||
            'Failed to fetch data',
        );
      }
    } catch (err) {
      console.error('Deployments fetch error:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log(
        '⏳ useDeploymentsInfo: Waiting for activeConfig to be loaded',
      );
      setLoading(false);
      return;
    }
    fetchDeployments();
  }, [activeConfig?.path]);

  const refetch = () => fetchDeployments(false);
  const backgroundRefetch = () => fetchDeployments(true);

  return {
    deployments,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function useStatefulSetsInfo() {
  const [statefulSets, setStatefulSets] = useState<StatefulSetInfo[]>([]);
  const [namespaces, setNamespaces] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchStatefulSets = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      // Fetch StatefulSets, Pods and Namespaces in parallel
      const [statefulSetsResponse, podsResponse, namespacesResponse] =
        await Promise.all([
          window.electron?.ipcRenderer.executeKubectl(
            'kubectl get statefulsets -A -o json',
            activeConfig?.path,
          ),
          window.electron?.ipcRenderer.executeKubectl(
            'kubectl get pods -A -o json',
            activeConfig?.path,
          ),
          window.electron?.ipcRenderer.executeKubectl(
            'kubectl get namespaces -o json',
            activeConfig?.path,
          ),
        ]);

      if (
        statefulSetsResponse.success &&
        podsResponse.success &&
        namespacesResponse.success
      ) {
        let statefulSetsData;
        let podsData;
        let namespacesData;
        try {
          statefulSetsData =
            typeof statefulSetsResponse.data === 'string'
              ? JSON.parse(statefulSetsResponse.data)
              : statefulSetsResponse.data;

          podsData =
            typeof podsResponse.data === 'string'
              ? JSON.parse(podsResponse.data)
              : podsResponse.data;

          namespacesData =
            typeof namespacesResponse.data === 'string'
              ? JSON.parse(namespacesResponse.data)
              : namespacesResponse.data;
        } catch (parseError) {
          console.error('Error parsing JSON:', parseError);
          setError('Failed to parse data');
          return;
        }

        // Get broken pods (Failed, CrashLoopBackOff, etc.)
        const brokenPods = (podsData.items || []).filter(
          (pod: any) =>
            pod.status?.phase === 'Failed' ||
            pod.status?.containerStatuses?.some(
              (container: any) =>
                container.state?.waiting?.reason === 'CrashLoopBackOff' ||
                container.state?.waiting?.reason === 'ImagePullBackOff' ||
                container.state?.terminated?.reason === 'Error',
            ),
        );

        // Create a map of broken pods by namespace and labels
        const brokenPodsByNamespace = new Map();
        brokenPods.forEach((pod: any) => {
          const namespace = pod.metadata?.namespace;
          const labels = pod.metadata?.labels || {};

          if (!brokenPodsByNamespace.has(namespace)) {
            brokenPodsByNamespace.set(namespace, []);
          }
          brokenPodsByNamespace.get(namespace).push(labels);
        });

        // Process StatefulSets and add pod issues flag
        const processedStatefulSets =
          statefulSetsData.items?.map((statefulSet: any) => {
            const containers =
              statefulSet.spec?.template?.spec?.containers || [];
            const images = containers.map((container: any) => container.image);

            const statefulSetNamespace = statefulSet.metadata?.namespace;
            const statefulSetName = statefulSet.metadata?.name;
            const matchLabels = statefulSet.spec?.selector?.matchLabels || {};

            // Check if this StatefulSet has pod issues
            let hasPodIssues = false;
            if (brokenPodsByNamespace.has(statefulSetNamespace)) {
              const namespaceBrokenPods =
                brokenPodsByNamespace.get(statefulSetNamespace);
              hasPodIssues = namespaceBrokenPods.some((podLabels: any) => {
                return Object.entries(matchLabels).every(([key, value]) => {
                  return podLabels[key] === value;
                });
              });
            }

            return {
              name: statefulSet.metadata?.name || '',
              namespace: statefulSet.metadata?.namespace || '',
              replicas: statefulSet.spec?.replicas || 0,
              readyReplicas: statefulSet.status?.readyReplicas || 0,
              currentReplicas: statefulSet.status?.currentReplicas || 0,
              updatedReplicas: statefulSet.status?.updatedReplicas || 0,
              hasPodIssues,
              status:
                statefulSet.status?.readyReplicas === statefulSet.spec?.replicas
                  ? 'Ready'
                  : 'Not Ready',
              creationTimestamp: statefulSet.metadata?.creationTimestamp || '',
              labels: statefulSet.metadata?.labels || {},
              images,
              conditions: statefulSet.status?.conditions || [],
              serviceName: statefulSet.spec?.serviceName,
            };
          }) || [];

        // Extract all namespaces from the cluster
        const allNamespaces = (namespacesData.items || [])
          .map((ns: any) => ns.metadata.name)
          .sort();

        setStatefulSets(processedStatefulSets);
        setNamespaces(allNamespaces);
      } else {
        console.error(
          'Fetch failed:',
          statefulSetsResponse.error ||
            podsResponse.error ||
            namespacesResponse.error,
        );
        setError(
          statefulSetsResponse.error ||
            podsResponse.error ||
            namespacesResponse.error ||
            'Failed to fetch data',
        );
      }
    } catch (err) {
      console.error('StatefulSets fetch error:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log(
        '⏳ useStatefulSetsInfo: Waiting for activeConfig to be loaded',
      );
      setLoading(false);
      return;
    }
    fetchStatefulSets();
  }, [activeConfig?.path]);

  const refetch = () => fetchStatefulSets(false);
  const backgroundRefetch = () => fetchStatefulSets(true);

  return {
    statefulSets,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function useDaemonSetsInfo() {
  const [daemonSets, setDaemonSets] = useState<DaemonSetInfo[]>([]);
  const [namespaces, setNamespaces] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchDaemonSets = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      // Fetch DaemonSets, Pods and Namespaces in parallel
      const [daemonSetsResponse, podsResponse, namespacesResponse] =
        await Promise.all([
          window.electron?.ipcRenderer.executeKubectl(
            'kubectl get daemonsets -A -o json',
            activeConfig?.path,
          ),
          window.electron?.ipcRenderer.executeKubectl(
            'kubectl get pods -A -o json',
            activeConfig?.path,
          ),
          window.electron?.ipcRenderer.executeKubectl(
            'kubectl get namespaces -o json',
            activeConfig?.path,
          ),
        ]);

      if (
        daemonSetsResponse.success &&
        podsResponse.success &&
        namespacesResponse.success
      ) {
        let daemonSetsData;
        let podsData;
        let namespacesData;
        try {
          daemonSetsData =
            typeof daemonSetsResponse.data === 'string'
              ? JSON.parse(daemonSetsResponse.data)
              : daemonSetsResponse.data;

          podsData =
            typeof podsResponse.data === 'string'
              ? JSON.parse(podsResponse.data)
              : podsResponse.data;

          namespacesData =
            typeof namespacesResponse.data === 'string'
              ? JSON.parse(namespacesResponse.data)
              : namespacesResponse.data;
        } catch (parseError) {
          console.error('Error parsing JSON:', parseError);
          setError('Failed to parse data');
          return;
        }

        // Get broken pods (Failed, CrashLoopBackOff, etc.)
        const brokenPods = (podsData.items || []).filter(
          (pod: any) =>
            pod.status?.phase === 'Failed' ||
            pod.status?.containerStatuses?.some(
              (container: any) =>
                container.state?.waiting?.reason === 'CrashLoopBackOff' ||
                container.state?.waiting?.reason === 'ImagePullBackOff' ||
                container.state?.terminated?.reason === 'Error',
            ),
        );

        // Create a map of broken pods by namespace and labels
        const brokenPodsByNamespace = new Map();
        brokenPods.forEach((pod: any) => {
          const namespace = pod.metadata?.namespace;
          const labels = pod.metadata?.labels || {};

          if (!brokenPodsByNamespace.has(namespace)) {
            brokenPodsByNamespace.set(namespace, []);
          }
          brokenPodsByNamespace.get(namespace).push(labels);
        });

        // Process DaemonSets and add pod issues flag
        const processedDaemonSets =
          daemonSetsData.items?.map((daemonSet: any) => {
            const containers = daemonSet.spec?.template?.spec?.containers || [];
            const images = containers.map((container: any) => container.image);

            const daemonSetNamespace = daemonSet.metadata?.namespace;
            const daemonSetName = daemonSet.metadata?.name;
            const matchLabels = daemonSet.spec?.selector?.matchLabels || {};

            // Check if this DaemonSet has pod issues
            let hasPodIssues = false;
            if (brokenPodsByNamespace.has(daemonSetNamespace)) {
              const namespaceBrokenPods =
                brokenPodsByNamespace.get(daemonSetNamespace);
              hasPodIssues = namespaceBrokenPods.some((podLabels: any) => {
                return Object.entries(matchLabels).every(([key, value]) => {
                  return podLabels[key] === value;
                });
              });
            }

            return {
              name: daemonSet.metadata?.name || '',
              namespace: daemonSet.metadata?.namespace || '',
              desiredNumberScheduled:
                daemonSet.status?.desiredNumberScheduled || 0,
              currentNumberScheduled:
                daemonSet.status?.currentNumberScheduled || 0,
              numberMisscheduled: daemonSet.status?.numberMisscheduled || 0,
              numberReady: daemonSet.status?.numberReady || 0,
              updatedNumberScheduled:
                daemonSet.status?.updatedNumberScheduled || 0,
              numberAvailable: daemonSet.status?.numberAvailable || 0,
              hasPodIssues,
              status:
                daemonSet.status?.numberReady ===
                daemonSet.status?.desiredNumberScheduled
                  ? 'Ready'
                  : 'Not Ready',
              creationTimestamp: daemonSet.metadata?.creationTimestamp || '',
              labels: daemonSet.metadata?.labels || {},
              images,
              conditions: daemonSet.status?.conditions || [],
            };
          }) || [];

        // Extract all namespaces from the cluster
        const allNamespaces = (namespacesData.items || [])
          .map((ns: any) => ns.metadata.name)
          .sort();

        setDaemonSets(processedDaemonSets);
        setNamespaces(allNamespaces);
      } else {
        console.error(
          'Fetch failed:',
          daemonSetsResponse.error ||
            podsResponse.error ||
            namespacesResponse.error,
        );
        setError(
          daemonSetsResponse.error ||
            podsResponse.error ||
            namespacesResponse.error ||
            'Failed to fetch data',
        );
      }
    } catch (err) {
      console.error('DaemonSets fetch error:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log(
        '⏳ useDaemonSetsInfo: Waiting for activeConfig to be loaded',
      );
      setLoading(false);
      return;
    }
    fetchDaemonSets();
  }, [activeConfig?.path]);

  const refetch = () => fetchDaemonSets(false);
  const backgroundRefetch = () => fetchDaemonSets(true);

  return {
    daemonSets,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function useIngressesInfo() {
  const [ingresses, setIngresses] = useState<IngressInfo[]>([]);
  const [namespaces, setNamespaces] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchIngresses = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      const ingressesResponse =
        await window.electron?.ipcRenderer.executeKubectl(
          'kubectl get ingresses -A -o json',
          activeConfig?.path,
        );

      if (ingressesResponse.success) {
        let ingressesData;
        try {
          ingressesData =
            typeof ingressesResponse.data === 'string'
              ? JSON.parse(ingressesResponse.data)
              : ingressesResponse.data;
        } catch (parseError) {
          console.error('Error parsing JSON:', parseError);
          setError('Failed to parse data');
          return;
        }

        const processedIngresses =
          ingressesData.items?.map((ingress: any) => {
            const rules = ingress.spec?.rules || [];
            const hosts = rules.map((rule: any) => rule.host).filter(Boolean);
            const addresses =
              ingress.status?.loadBalancer?.ingress
                ?.map((lb: any) => lb.ip || lb.hostname)
                .filter(Boolean) || [];
            const ports = [];

            // Extract ports from rules
            rules.forEach((rule: any) => {
              rule.http?.paths?.forEach((path: any) => {
                const port =
                  path.backend?.service?.port?.number ||
                  path.backend?.service?.port?.name;
                if (port && !ports.includes(port.toString())) {
                  ports.push(port.toString());
                }
              });
            });

            return {
              name: ingress.metadata?.name || '',
              namespace: ingress.metadata?.namespace || '',
              className: ingress.spec?.ingressClassName,
              hosts,
              addresses,
              ports,
              age: ingress.metadata?.creationTimestamp || '',
              creationTimestamp: ingress.metadata?.creationTimestamp || '',
              labels: ingress.metadata?.labels || {},
              annotations: ingress.metadata?.annotations || {},
              rules: ingress.spec?.rules || [],
              tls: ingress.spec?.tls || [],
            };
          }) || [];

        // Extract unique namespaces
        const uniqueNamespaces = [
          ...new Set(
            processedIngresses.map((ingress: IngressInfo) => ingress.namespace),
          ),
        ].sort();

        setIngresses(processedIngresses);
        setNamespaces(uniqueNamespaces);
      } else {
        console.error('Fetch failed:', ingressesResponse.error);
        setError(ingressesResponse.error || 'Failed to fetch data');
      }
    } catch (err) {
      console.error('Ingresses fetch error:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log('⏳ useIngressesInfo: Waiting for activeConfig to be loaded');
      setLoading(false);
      return;
    }
    fetchIngresses();
  }, [activeConfig?.path]);

  const refetch = () => fetchIngresses(false);
  const backgroundRefetch = () => fetchIngresses(true);

  return {
    ingresses,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function useServicesInfo() {
  const [services, setServices] = useState<ServiceInfo[]>([]);
  const [namespaces, setNamespaces] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchServices = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      const servicesResponse =
        await window.electron?.ipcRenderer.executeKubectl(
          'kubectl get services -A -o json',
          activeConfig?.path,
        );

      if (servicesResponse.success) {
        let servicesData;
        try {
          servicesData =
            typeof servicesResponse.data === 'string'
              ? JSON.parse(servicesResponse.data)
              : servicesResponse.data;
        } catch (parseError) {
          console.error('Error parsing JSON:', parseError);
          setError('Failed to parse data');
          return;
        }

        const processedServices =
          servicesData.items?.map((service: any) => {
            const ports =
              service.spec?.ports?.map((port: any) => ({
                name: port.name,
                port: port.port,
                targetPort: port.targetPort,
                protocol: port.protocol || 'TCP',
                nodePort: port.nodePort,
              })) || [];

            return {
              name: service.metadata?.name || '',
              namespace: service.metadata?.namespace || '',
              type: service.spec?.type || 'ClusterIP',
              clusterIP: service.spec?.clusterIP || '',
              externalIPs: service.spec?.externalIPs || [],
              ports,
              selector: service.spec?.selector || {},
              sessionAffinity: service.spec?.sessionAffinity || 'None',
              age: service.metadata?.creationTimestamp || '',
              creationTimestamp: service.metadata?.creationTimestamp || '',
              labels: service.metadata?.labels || {},
              annotations: service.metadata?.annotations || {},
            };
          }) || [];

        // Extract unique namespaces
        const uniqueNamespaces = [
          ...new Set(
            processedServices.map((service: ServiceInfo) => service.namespace),
          ),
        ].sort();

        setServices(processedServices);
        setNamespaces(uniqueNamespaces);
      } else {
        console.error('Fetch failed:', servicesResponse.error);
        setError(servicesResponse.error || 'Failed to fetch data');
      }
    } catch (err) {
      console.error('Services fetch error:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log('⏳ useServicesInfo: Waiting for activeConfig to be loaded');
      setLoading(false);
      return;
    }
    fetchServices();
  }, [activeConfig?.path]);

  const refetch = () => fetchServices(false);
  const backgroundRefetch = () => fetchServices(true);

  return {
    services,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function useConfigMapsInfo() {
  const [configMaps, setConfigMaps] = useState<ConfigMapInfo[]>([]);
  const [namespaces, setNamespaces] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchConfigMaps = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      const configMapsResponse =
        await window.electron?.ipcRenderer.executeKubectl(
          'kubectl get configmaps -A -o json',
          activeConfig?.path,
        );

      if (configMapsResponse.success) {
        let configMapsData;
        try {
          configMapsData =
            typeof configMapsResponse.data === 'string'
              ? JSON.parse(configMapsResponse.data)
              : configMapsResponse.data;
        } catch (parseError) {
          console.error('Error parsing JSON:', parseError);
          setError('Failed to parse data');
          return;
        }

        const processedConfigMaps =
          configMapsData.items?.map((configMap: any) => {
            const data = configMap.data || {};
            const binaryData = configMap.binaryData || {};

            return {
              name: configMap.metadata?.name || '',
              namespace: configMap.metadata?.namespace || '',
              dataCount:
                Object.keys(data).length + Object.keys(binaryData).length,
              age: configMap.metadata?.creationTimestamp || '',
              creationTimestamp: configMap.metadata?.creationTimestamp || '',
              labels: configMap.metadata?.labels || {},
              annotations: configMap.metadata?.annotations || {},
              data,
              binaryData,
            };
          }) || [];

        // Extract unique namespaces
        const uniqueNamespaces = [
          ...new Set(
            processedConfigMaps.map((cm: ConfigMapInfo) => cm.namespace),
          ),
        ].sort();

        setConfigMaps(processedConfigMaps);
        setNamespaces(uniqueNamespaces);
      } else {
        console.error('Fetch failed:', configMapsResponse.error);
        setError(configMapsResponse.error || 'Failed to fetch data');
      }
    } catch (err) {
      console.error('ConfigMaps fetch error:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log(
        '⏳ useConfigMapsInfo: Waiting for activeConfig to be loaded',
      );
      setLoading(false);
      return;
    }
    fetchConfigMaps();
  }, [activeConfig?.path]);

  const refetch = () => fetchConfigMaps(false);
  const backgroundRefetch = () => fetchConfigMaps(true);

  return {
    configMaps,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function useSecretsInfo() {
  const [secrets, setSecrets] = useState<SecretInfo[]>([]);
  const [namespaces, setNamespaces] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchSecrets = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      // Fetch secrets and all namespaces in parallel
      const [secretsResponse, namespacesResponse] = await Promise.all([
        window.electron?.ipcRenderer.executeKubectl(
          'kubectl get secrets -A -o json',
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          'kubectl get namespaces -o json',
          activeConfig?.path,
        ),
      ]);

      if (secretsResponse.success && namespacesResponse.success) {
        let secretsData;
        let namespacesData;
        try {
          secretsData =
            typeof secretsResponse.data === 'string'
              ? JSON.parse(secretsResponse.data)
              : secretsResponse.data;
          namespacesData =
            typeof namespacesResponse.data === 'string'
              ? JSON.parse(namespacesResponse.data)
              : namespacesResponse.data;
        } catch (parseError) {
          console.error('Error parsing JSON:', parseError);
          setError('Failed to parse data');
          return;
        }

        const processedSecrets =
          secretsData.items?.map((secret: any) => {
            const data = secret.data || {};

            return {
              name: secret.metadata?.name || '',
              namespace: secret.metadata?.namespace || '',
              type: secret.type || 'Opaque',
              dataCount: Object.keys(data).length,
              age: secret.metadata?.creationTimestamp || '',
              creationTimestamp: secret.metadata?.creationTimestamp || '',
              labels: secret.metadata?.labels || {},
              annotations: secret.metadata?.annotations || {},
            };
          }) || [];

        // Extract all namespaces from the cluster
        const allNamespaces = (namespacesData.items || [])
          .map((ns: any) => ns.metadata.name)
          .sort();

        setSecrets(processedSecrets);
        setNamespaces(allNamespaces);
      } else {
        console.error('Fetch failed:', secretsResponse.error || namespacesResponse.error);
        setError(secretsResponse.error || namespacesResponse.error || 'Failed to fetch data');
      }
    } catch (err) {
      console.error('Secrets fetch error:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log('⏳ useSecretsInfo: Waiting for activeConfig to be loaded');
      setLoading(false);
      return;
    }
    fetchSecrets();
  }, [activeConfig?.path]);

  const refetch = () => fetchSecrets(false);
  const backgroundRefetch = () => fetchSecrets(true);

  return {
    secrets,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function usePodsInfo() {
  const [pods, setPods] = useState<any[]>([]);
  const [namespaces, setNamespaces] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchPods = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      const [podsResponse, namespacesResponse] = await Promise.all([
        window.electron?.ipcRenderer.executeKubectl(
          'kubectl get pods -A -o json',
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          'kubectl get namespaces -o json',
          activeConfig?.path,
        ),
      ]);

      if (podsResponse.success && namespacesResponse.success) {
        let podsData;
        let namespacesData;
        try {
          podsData =
            typeof podsResponse.data === 'string'
              ? JSON.parse(podsResponse.data)
              : podsResponse.data;

          namespacesData =
            typeof namespacesResponse.data === 'string'
              ? JSON.parse(namespacesResponse.data)
              : namespacesResponse.data;
        } catch (parseError) {
          console.error('Error parsing JSON:', parseError);
          setError('Failed to parse data');
          return;
        }

        const processedPods = podsData.items || [];

        // Extract all namespaces from the cluster
        const allNamespaces = (namespacesData.items || [])
          .map((ns: any) => ns.metadata.name)
          .sort();

        setPods(processedPods);
        setNamespaces(allNamespaces);
      } else {
        console.error(
          'Fetch failed:',
          podsResponse.error || namespacesResponse.error,
        );
        setError(
          podsResponse.error ||
            namespacesResponse.error ||
            'Failed to fetch data',
        );
      }
    } catch (err) {
      console.error('Pods fetch error:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log('⏳ usePodsInfo: Waiting for activeConfig to be loaded');
      setLoading(false);
      return;
    }
    fetchPods();
  }, [activeConfig?.path]);

  const refetch = () => fetchPods(false);
  const backgroundRefetch = () => fetchPods(true);

  return {
    pods,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function useDeploymentDetails(
  deploymentName: string,
  namespaceName: string,
) {
  const [deploymentInfo, setDeploymentInfo] = useState<any>(null);
  const [pods, setPods] = useState<any[]>([]);
  const [replicaSets, setReplicaSets] = useState<any[]>([]);
  const [events, setEvents] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchDeploymentDetails = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      // Get deployment details
      const [deploymentRes, podsRes, replicaSetsRes, eventsRes] =
        await Promise.all([
          window.electron?.ipcRenderer.executeKubectl(
            `kubectl get deployment ${deploymentName} -n ${namespaceName} -o json`,
            activeConfig?.path,
          ),
          window.electron?.ipcRenderer.executeKubectl(
            `kubectl get pods -n ${namespaceName} -o json`,
            activeConfig?.path,
          ),
          window.electron?.ipcRenderer.executeKubectl(
            `kubectl get replicasets -n ${namespaceName} -o json`,
            activeConfig?.path,
          ),
          window.electron?.ipcRenderer.executeKubectl(
            `kubectl get events -n ${namespaceName} --field-selector involvedObject.kind=Deployment,involvedObject.name=${deploymentName} --sort-by='.lastTimestamp' -o json`,
            activeConfig?.path,
          ),
        ]);

      if (!deploymentRes.success) {
        setError(deploymentRes.error || 'Failed to fetch deployment details');
        return;
      }

      const parseResponse = (response: KubectlResponse) => {
        if (!response.success) return null;
        try {
          return typeof response.data === 'string'
            ? JSON.parse(response.data)
            : response.data;
        } catch {
          return null;
        }
      };

      const deploymentData = parseResponse(deploymentRes);
      const podsData = parseResponse(podsRes);
      const replicaSetsData = parseResponse(replicaSetsRes);
      const eventsData = parseResponse(eventsRes);

      setDeploymentInfo(deploymentData);

      // Filter pods and replicasets that belong to this deployment
      const deploymentUid = deploymentData?.metadata?.uid;
      const deploymentLabels =
        deploymentData?.spec?.selector?.matchLabels || {};

      // Filter ReplicaSets owned by this deployment
      const filteredReplicaSets = (replicaSetsData?.items || []).filter(
        (rs: any) => {
          const ownerRefs = rs.metadata?.ownerReferences || [];
          return ownerRefs.some(
            (ref: any) =>
              ref.uid === deploymentUid && ref.kind === 'Deployment',
          );
        },
      );

      // Filter Pods that match the deployment selector labels
      const filteredPods = (podsData?.items || []).filter((pod: any) => {
        const podLabels = pod.metadata?.labels || {};
        return Object.entries(deploymentLabels).every(
          ([key, value]) => podLabels[key] === value,
        );
      });

      setPods(filteredPods);
      setReplicaSets(filteredReplicaSets);
      setEvents(eventsData?.items || []);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    if (deploymentName && namespaceName) {
      fetchDeploymentDetails();
    }
  }, [deploymentName, namespaceName, activeConfig?.path]);

  const refetch = () => fetchDeploymentDetails(false);
  const backgroundRefetch = () => fetchDeploymentDetails(true);

  return {
    deploymentInfo,
    pods,
    replicaSets,
    events,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export interface ClusterEvent {
  type: string;
  reason: string;
  message: string;
  count: number;
  firstTimestamp: string;
  lastTimestamp: string;
  involvedObject: {
    kind: string;
    name: string;
    namespace: string;
  };
  source: {
    component: string;
    host?: string;
  };
}

export function useClusterEvents() {
  const [events, setEvents] = useState<ClusterEvent[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchClusterEvents = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      // Get warning events from all namespaces
      const response: KubectlResponse =
        await window.electron?.ipcRenderer.executeKubectl(
          "kubectl get events --all-namespaces --field-selector type=Warning --sort-by='.lastTimestamp' -o json",
          activeConfig?.path,
        );

      if (response.success) {
        let parsedData;
        try {
          parsedData =
            typeof response.data === 'string'
              ? JSON.parse(response.data)
              : response.data;
        } catch (parseError) {
          console.error('Error parsing events JSON:', parseError);
          setError('Failed to parse events data');
          return;
        }

        const eventsData =
          parsedData.items?.map((event: any) => ({
            type: event.type,
            reason: event.reason,
            message: event.message,
            count: event.count || 1,
            firstTimestamp: event.firstTimestamp,
            lastTimestamp: event.lastTimestamp,
            involvedObject: {
              kind: event.involvedObject.kind,
              name: event.involvedObject.name,
              namespace: event.involvedObject.namespace,
            },
            source: {
              component: event.source?.component,
              host: event.source?.host,
            },
          })) || [];

        setEvents(eventsData);
      } else {
        setError(response.error || 'Failed to fetch cluster events');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log('⏳ useClusterEvents: Waiting for activeConfig to be loaded');
      setLoading(false);
      return;
    }
    fetchClusterEvents();
  }, [activeConfig?.path]);

  const refetch = () => fetchClusterEvents(false);
  const backgroundRefetch = () => fetchClusterEvents(true);

  return {
    events,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export interface ImageDetails {
  name: string;
  pullPolicy: string;
  registry?: string;
  repository?: string;
  tag?: string;
  digest?: string;
  secrets?: string[];
  ports?: Array<{
    containerPort: number;
    protocol: string;
    name?: string;
  }>;
  env?: Array<{
    name: string;
    value?: string;
    valueFrom?: any;
  }>;
  resources?: {
    requests?: {
      cpu?: string;
      memory?: string;
    };
    limits?: {
      cpu?: string;
      memory?: string;
    };
  };
  volumeMounts?: Array<{
    name: string;
    mountPath: string;
    readOnly?: boolean;
  }>;
  securityContext?: any;
  livenessProbe?: any;
  readinessProbe?: any;
  startupProbe?: any;
}

export function useImageDetails() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { activeConfig } = useKubeconfigs();

  const getImageDetails = async (
    deploymentName: string,
    namespaceName: string,
    imageName: string,
  ): Promise<ImageDetails | null> => {
    try {
      setLoading(true);
      setError(null);

      // Get deployment details
      const deploymentRes: KubectlResponse =
        await window.electron?.ipcRenderer.executeKubectl(
          `kubectl get deployment ${deploymentName} -n ${namespaceName} -o json`,
          activeConfig?.path,
        );

      if (!deploymentRes.success) {
        setError(deploymentRes.error || 'Failed to fetch deployment details');
        return null;
      }

      // Get namespace secrets (for image pull secrets)
      const secretsRes: KubectlResponse =
        await window.electron?.ipcRenderer.executeKubectl(
          `kubectl get secrets -n ${namespaceName} -o json`,
          activeConfig?.path,
        );

      const parseResponse = (response: KubectlResponse) => {
        if (!response.success) return null;
        try {
          return typeof response.data === 'string'
            ? JSON.parse(response.data)
            : response.data;
        } catch {
          return null;
        }
      };

      const deploymentData = parseResponse(deploymentRes);
      const secretsData = parseResponse(secretsRes);

      if (!deploymentData) {
        setError('Failed to parse deployment data');
        return null;
      }

      // Find the specific container with the image
      const containers = deploymentData.spec?.template?.spec?.containers || [];
      const container = containers.find((c: any) => c.image === imageName);

      if (!container) {
        setError('Container with specified image not found');
        return null;
      }

      // Extract image information
      const parseImageName = (fullImageName: string) => {
        let registry = '';
        let repository = '';
        let tag = 'latest';

        // Handle tag first - split on the LAST : to handle registry:port/image:tag
        const lastColonIndex = fullImageName.lastIndexOf(':');
        let imageWithoutTag = fullImageName;

        if (lastColonIndex > 0) {
          const potentialTag = fullImageName.substring(lastColonIndex + 1);
          // If it doesn't contain '/', it's likely a tag, not a port
          if (!potentialTag.includes('/')) {
            tag = potentialTag;
            imageWithoutTag = fullImageName.substring(0, lastColonIndex);
          }
        }

        // Now analyze the image part
        const parts = imageWithoutTag.split('/');

        if (parts.length === 1) {
          // Simple image name like "nginx" or "ubuntu"
          registry = 'Docker Hub (implícito)';
          repository = parts[0];
        } else if (parts.length === 2) {
          // Could be "namespace/image" or "registry.com/image"
          if (
            parts[0].includes('.') ||
            parts[0].includes(':') ||
            parts[0] === 'localhost'
          ) {
            // Has dots, colons, or is localhost - it's a registry
            registry = parts[0];
            repository = parts[1];
          } else {
            // Namespace/image format (Docker Hub)
            registry = 'Docker Hub (implícito)';
            repository = imageWithoutTag; // Keep the full namespace/image
          }
        } else {
          // 3+ parts: registry.com/namespace/image
          registry = parts[0];
          repository = parts.slice(1).join('/');
        }

        return { registry, repository, tag };
      };

      const { registry, repository, tag } = parseImageName(imageName);

      // Get image pull secrets - only those explicitly referenced
      const imagePullSecrets =
        deploymentData.spec?.template?.spec?.imagePullSecrets || [];
      const relatedSecrets = (secretsData?.items || [])
        .filter(
          (secret: any) =>
            secret.type === 'kubernetes.io/dockerconfigjson' &&
            imagePullSecrets.some(
              (ips: any) => ips.name === secret.metadata.name,
            ),
        )
        .map((secret: any) => secret.metadata.name);

      const imageDetails: ImageDetails = {
        name: imageName,
        pullPolicy: container.imagePullPolicy || 'IfNotPresent',
        registry,
        repository,
        tag,
        secrets: relatedSecrets,
        ports:
          container.ports?.map((port: any) => ({
            containerPort: port.containerPort,
            protocol: port.protocol || 'TCP',
            name: port.name,
          })) || [],
        env:
          container.env?.map((envVar: any) => ({
            name: envVar.name,
            value: envVar.value,
            valueFrom: envVar.valueFrom,
          })) || [],
        resources: container.resources || {},
        volumeMounts: container.volumeMounts || [],
        securityContext: container.securityContext,
        livenessProbe: container.livenessProbe,
        readinessProbe: container.readinessProbe,
        startupProbe: container.startupProbe,
      };

      return imageDetails;
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
      return null;
    } finally {
      setLoading(false);
    }
  };

  return {
    getImageDetails,
    loading,
    error,
  };
}

export function usePodDetails(podName: string, namespaceName: string) {
  const [podInfo, setPodInfo] = useState<any>(null);
  const [containers, setContainers] = useState<any[]>([]);
  const [events, setEvents] = useState<any[]>([]);
  const [metrics, setMetrics] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchPodDetails = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      // Get pod details, events, and metrics in parallel
      const [podRes, eventsRes, metricsRes] = await Promise.all([
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get pod ${podName} -n ${namespaceName} -o json`,
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get events -n ${namespaceName} --field-selector involvedObject.kind=Pod,involvedObject.name=${podName} --sort-by='.lastTimestamp' -o json`,
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl top pod ${podName} -n ${namespaceName} --no-headers`,
          activeConfig?.path,
        ),
      ]);

      if (!podRes.success) {
        setError(podRes.error || 'Failed to fetch pod details');
        return;
      }

      const parseResponse = (response: KubectlResponse) => {
        if (!response.success) return null;
        try {
          return typeof response.data === 'string'
            ? JSON.parse(response.data)
            : response.data;
        } catch {
          return null;
        }
      };

      const podData = parseResponse(podRes);
      const eventsData = parseResponse(eventsRes);

      if (!podData) {
        setError('Failed to parse pod data');
        return;
      }

      setPodInfo(podData);

      // Parse metrics from kubectl top output
      // Format: NAME CPU(cores) MEMORY(bytes)
      // Example: my-pod-123 100m 256Mi
      if (metricsRes.success && metricsRes.data) {
        try {
          const metricsLine = typeof metricsRes.data === 'string'
            ? metricsRes.data.trim()
            : '';

          if (metricsLine) {
            const parts = metricsLine.split(/\s+/);
            if (parts.length >= 3) {
              setMetrics({
                cpu: parts[1], // e.g., "100m" or "0.5"
                memory: parts[2], // e.g., "256Mi" or "1Gi"
              });
            }
          }
        } catch (metricsError) {
          console.error('Failed to parse metrics:', metricsError);
          setMetrics(null);
        }
      } else {
        // Metrics server might not be available
        setMetrics(null);
      }

      // Combinar init containers e containers regulares
      const initContainers = (podData.spec?.initContainers || []).map(
        (container: any) => ({
          ...container,
          isInitContainer: true,
        }),
      );
      const regularContainers = (podData.spec?.containers || []).map(
        (container: any) => ({
          ...container,
          isInitContainer: false,
        }),
      );

      setContainers([...initContainers, ...regularContainers]);
      setEvents(eventsData?.items || []);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    if (podName && namespaceName) {
      fetchPodDetails();
    }
  }, [podName, namespaceName, activeConfig?.path]);

  const refetch = () => fetchPodDetails(false);
  const backgroundRefetch = () => fetchPodDetails(true);

  return {
    podInfo,
    containers,
    events,
    metrics,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function useKubectl() {
  const { activeConfig } = useKubeconfigs();

  const executeCommand = async (command: string): Promise<KubectlResponse> => {
    try {
      const response: KubectlResponse =
        await window.electron?.ipcRenderer.executeKubectl(
          command,
          activeConfig?.path,
        );

      // Se houve fallback, apenas log em desenvolvimento
      if (
        response.success &&
        (response as any).fallbackUsed &&
        process.env.NODE_ENV === 'development'
      ) {
        console.info(
          `Command succeeded using fallback: ${(response as any).fallbackUsed}`,
        );
      }

      return response;
    } catch (error) {
      return {
        success: false,
        data: null,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  };

  return {
    executeCommand,
  };
}

export interface CronJobInfo {
  name: string;
  namespace: string;
  schedule: string;
  suspend: boolean;
  active: number;
  lastScheduleTime: string | null;
  nextScheduleTime: string | null;
  successfulJobsHistoryLimit: number;
  failedJobsHistoryLimit: number;
  concurrencyPolicy: string;
  startingDeadlineSeconds: number | null;
  creationTimestamp: string;
  labels: Record<string, string>;
  annotations: Record<string, string>;
}

export interface JobInfo {
  name: string;
  namespace: string;
  completions: number | null;
  parallelism: number | null;
  activeDeadlineSeconds: number | null;
  backoffLimit: number | null;
  succeeded: number;
  failed: number;
  active: number;
  startTime: string | null;
  completionTime: string | null;
  conditions: Array<{
    type: string;
    status: string;
    lastTransitionTime: string;
    reason?: string;
    message?: string;
  }>;
  creationTimestamp: string;
  labels: Record<string, string>;
  annotations: Record<string, string>;
}

export function useCronJobsInfo() {
  const [cronJobs, setCronJobs] = useState<CronJobInfo[]>([]);
  const [namespaces, setNamespaces] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchCronJobs = async (isBackground = false) => {
    try {
      // Only show loading spinner on initial load, not on background refreshes
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      const [cronJobsResponse, namespacesResponse] = await Promise.all([
        window.electron?.ipcRenderer.executeKubectl(
          'kubectl get cronjobs -A -o json',
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          'kubectl get namespaces -o json',
          activeConfig?.path,
        ),
      ]);

      // console.log('CronJobs response:', cronJobsResponse);

      if (cronJobsResponse.success && namespacesResponse.success) {
        let cronJobsData;
        let namespacesData;
        try {
          cronJobsData =
            typeof cronJobsResponse.data === 'string'
              ? JSON.parse(cronJobsResponse.data)
              : cronJobsResponse.data;

          namespacesData =
            typeof namespacesResponse.data === 'string'
              ? JSON.parse(namespacesResponse.data)
              : namespacesResponse.data;
        } catch (parseError) {
          console.error('Error parsing JSON:', parseError);
          setError('Failed to parse data');
          return;
        }

        // Process cronjobs
        const processedCronJobs =
          cronJobsData.items?.map((cronJob: any) => {
            const spec = cronJob.spec || {};
            const status = cronJob.status || {};
            const metadata = cronJob.metadata || {};

            return {
              name: metadata.name || '',
              namespace: metadata.namespace || '',
              schedule: spec.schedule || '',
              suspend: spec.suspend || false,
              active: status.active ? status.active.length : 0,
              lastScheduleTime: status.lastScheduleTime || null,
              nextScheduleTime: status.nextScheduleTime || null,
              successfulJobsHistoryLimit: spec.successfulJobsHistoryLimit || 3,
              failedJobsHistoryLimit: spec.failedJobsHistoryLimit || 1,
              concurrencyPolicy: spec.concurrencyPolicy || 'Allow',
              startingDeadlineSeconds: spec.startingDeadlineSeconds || null,
              creationTimestamp: metadata.creationTimestamp || '',
              labels: metadata.labels || {},
              annotations: metadata.annotations || {},
            };
          }) || [];

        // console.log('Processed cronjobs:', processedCronJobs);
        setCronJobs(processedCronJobs);

        // Extract ALL namespaces from cluster
        const allNamespaces = (namespacesData.items || [])
          .map((ns: any) => ns.metadata.name)
          .sort();
        setNamespaces(allNamespaces);
      } else {
        setError(
          cronJobsResponse.error ||
            namespacesResponse.error ||
            'Failed to fetch cronjobs or namespaces',
        );
      }
    } catch (err) {
      // console.error('Error in fetchCronJobs:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  const refetch = () => fetchCronJobs(false);
  const backgroundRefetch = () => fetchCronJobs(true);

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log('⏳ useCronJobsInfo: Waiting for activeConfig to be loaded');
      setLoading(false);
      return;
    }
    fetchCronJobs();
  }, [activeConfig?.path]);

  return {
    cronJobs,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function useJobsInfo() {
  const [jobs, setJobs] = useState<JobInfo[]>([]);
  const [namespaces, setNamespaces] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchJobs = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      const [jobsResponse, namespacesResponse] = await Promise.all([
        window.electron?.ipcRenderer.executeKubectl(
          'kubectl get jobs -A -o json',
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          'kubectl get namespaces -o json',
          activeConfig?.path,
        ),
      ]);

      if (jobsResponse.success && namespacesResponse.success) {
        let parsedData;
        let namespacesData;
        try {
          parsedData =
            typeof jobsResponse.data === 'string'
              ? JSON.parse(jobsResponse.data)
              : jobsResponse.data;

          namespacesData =
            typeof namespacesResponse.data === 'string'
              ? JSON.parse(namespacesResponse.data)
              : namespacesResponse.data;
        } catch (parseError) {
          console.error('Error parsing JSON:', parseError);
          setError('Failed to parse data');
          return;
        }

        const jobsData =
          parsedData.items?.map((job: any) => ({
            name: job.metadata?.name || '',
            namespace: job.metadata?.namespace || '',
            completions: job.spec?.completions || null,
            parallelism: job.spec?.parallelism || null,
            activeDeadlineSeconds: job.spec?.activeDeadlineSeconds || null,
            backoffLimit: job.spec?.backoffLimit || null,
            succeeded: job.status?.succeeded || 0,
            failed: job.status?.failed || 0,
            active: job.status?.active || 0,
            startTime: job.status?.startTime || null,
            completionTime: job.status?.completionTime || null,
            conditions: job.status?.conditions || [],
            creationTimestamp: job.metadata?.creationTimestamp || '',
            labels: job.metadata?.labels || {},
            annotations: job.metadata?.annotations || {},
          })) || [];

        setJobs(jobsData);

        // Extract all namespaces from the cluster
        const allNamespaces = (namespacesData.items || [])
          .map((ns: any) => ns.metadata.name)
          .sort();
        setNamespaces(allNamespaces);
      } else {
        setError(
          jobsResponse.error ||
            namespacesResponse.error ||
            'Failed to fetch data',
        );
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  const refetch = () => fetchJobs(false);
  const backgroundRefetch = () => fetchJobs(true);

  useEffect(() => {
    if (!activeConfig?.path) {
      console.log('⏳ useJobsInfo: Waiting for activeConfig to be loaded');
      setLoading(false);
      return;
    }
    fetchJobs();
  }, [activeConfig?.path]);

  return {
    jobs,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function useCronJobDetails(cronJobName: string, namespaceName: string) {
  const [cronJobInfo, setCronJobInfo] = useState<any>(null);
  const [jobs, setJobs] = useState<any[]>([]);
  const [events, setEvents] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchCronJobDetails = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      // Get cronjob details
      const cronJobResponse = await window.electron?.ipcRenderer.executeKubectl(
        `kubectl get cronjob ${cronJobName} -n ${namespaceName} -o json`,
        activeConfig?.path,
      );

      if (!cronJobResponse.success) {
        setError(cronJobResponse.error || 'Failed to fetch cronjob details');
        return;
      }

      // Get jobs created by this cronjob
      const jobsResponse = await window.electron?.ipcRenderer.executeKubectl(
        `kubectl get jobs -n ${namespaceName} -l job-name -o json`,
        activeConfig?.path,
      );

      // Get events related to this cronjob
      const eventsResponse = await window.electron?.ipcRenderer.executeKubectl(
        `kubectl get events -n ${namespaceName} --field-selector involvedObject.name=${cronJobName} -o json`,
        activeConfig?.path,
      );

      const parseResponse = (response: KubectlResponse) => {
        if (!response.success) return null;
        try {
          return typeof response.data === 'string'
            ? JSON.parse(response.data)
            : response.data;
        } catch {
          return null;
        }
      };

      const cronJobData = parseResponse(cronJobResponse);
      const jobsData = parseResponse(jobsResponse);
      const eventsData = parseResponse(eventsResponse);

      if (cronJobData) {
        setCronJobInfo(cronJobData);
      }

      if (jobsData) {
        // Filter jobs that belong to this cronjob
        const filteredJobs = (jobsData.items || []).filter((job: any) => {
          const labels = job.metadata?.labels || {};
          return (
            labels['job-name']?.startsWith(cronJobName) ||
            job.metadata?.ownerReferences?.some(
              (ref: any) => ref.kind === 'CronJob' && ref.name === cronJobName,
            )
          );
        });

        // Sort by creation time (newest first)
        filteredJobs.sort((a: any, b: any) => {
          const timeA = new Date(a.metadata?.creationTimestamp || 0).getTime();
          const timeB = new Date(b.metadata?.creationTimestamp || 0).getTime();
          return timeB - timeA;
        });

        setJobs(filteredJobs);
      }

      if (eventsData) {
        // Sort events by time (newest first)
        const sortedEvents = (eventsData.items || []).sort((a: any, b: any) => {
          const timeA = new Date(
            a.firstTimestamp || a.eventTime || 0,
          ).getTime();
          const timeB = new Date(
            b.firstTimestamp || b.eventTime || 0,
          ).getTime();
          return timeB - timeA;
        });
        setEvents(sortedEvents);
      }
    } catch (err) {
      // console.error('Error in fetchCronJobDetails:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  const refetch = () => fetchCronJobDetails(false);
  const backgroundRefetch = () => fetchCronJobDetails(true);

  useEffect(() => {
    if (cronJobName && namespaceName) {
      fetchCronJobDetails();
    }
  }, [cronJobName, namespaceName, activeConfig?.path]);

  return {
    cronJobInfo,
    jobs,
    events,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function useJobDetails(jobName: string, namespaceName: string) {
  const [jobInfo, setJobInfo] = useState<any>(null);
  const [pods, setPods] = useState<any[]>([]);
  const [events, setEvents] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchJobDetails = useCallback(
    async (isBackground = false) => {
      try {
        if (!isBackground) {
          setLoading(true);
        } else {
          setIsRefreshing(true);
        }
        setError(null);

        // Get job details
        const jobResponse = await window.electron?.ipcRenderer.executeKubectl(
          `kubectl get job ${jobName} -n ${namespaceName} -o json`,
          activeConfig?.path,
        );

        if (jobResponse && jobResponse.success) {
          const jobData = JSON.parse(jobResponse.data);
          setJobInfo(jobData);
        } else {
          const errorMsg = jobResponse?.error || 'Erro desconhecido';
          if (errorMsg.includes('NotFound') || errorMsg.includes('not found')) {
            setError(
              `Job "${jobName}" não foi encontrado no namespace "${namespaceName}". O job pode ter sido deletado ou completado.`,
            );
          } else {
            setError(`Erro ao buscar informações do job: ${errorMsg}`);
          }
          return;
        }

        // Get pods for this job using the correct Kubernetes batch label
        const podsCommand = `kubectl get pods -l batch.kubernetes.io/job-name=${jobName} -n ${namespaceName} -o json`;
        const podsResponse = await window.electron?.ipcRenderer.executeKubectl(
          podsCommand,
          activeConfig?.path,
        );

        if (podsResponse && podsResponse.success) {
          const podsData = JSON.parse(podsResponse.data);
          setPods(podsData.items || []);
        }

        // Get events for this job
        const eventsResponse =
          await window.electron?.ipcRenderer.executeKubectl(
            `kubectl get events --field-selector involvedObject.name=${jobName} -n ${namespaceName} -o json`,
            activeConfig?.path,
          );

        if (eventsResponse && eventsResponse.success) {
          const eventsData = JSON.parse(eventsResponse.data);
          setEvents(eventsData.items || []);
        }
      } catch (err) {
        console.error('Error fetching job details:', err);
        setError('Erro ao carregar detalhes do job');
      } finally {
        setLoading(false);
        setIsRefreshing(false);
      }
    },
    [jobName, namespaceName],
  );

  useEffect(() => {
    if (jobName && namespaceName) {
      fetchJobDetails();
    }
  }, [jobName, namespaceName, activeConfig?.path]);

  const refetch = useCallback(() => fetchJobDetails(false), [fetchJobDetails]);
  const backgroundRefetch = useCallback(
    () => fetchJobDetails(true),
    [fetchJobDetails],
  );

  return {
    jobInfo,
    pods,
    events,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}

export function useDaemonSetDetails(
  daemonSetName: string,
  namespaceName: string,
) {
  const [daemonSetInfo, setDaemonSetInfo] = useState<any>(null);
  const [pods, setPods] = useState<any[]>([]);
  const [events, setEvents] = useState<any[]>([]);
  const [configMaps, setConfigMaps] = useState<any[]>([]);
  const [secrets, setSecrets] = useState<any[]>([]);
  const [services, setServices] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const { activeConfig } = useKubeconfigs();

  const fetchDaemonSetDetails = async (isBackground = false) => {
    try {
      if (!isBackground) {
        setLoading(true);
      } else {
        setIsRefreshing(true);
      }
      setError(null);

      // Get daemonset details
      const [
        daemonSetRes,
        podsRes,
        eventsRes,
        configMapsRes,
        secretsRes,
        servicesRes,
      ] = await Promise.all([
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get daemonset ${daemonSetName} -n ${namespaceName} -o json`,
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get pods -n ${namespaceName} -o json`,
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get events -n ${namespaceName} --field-selector involvedObject.kind=DaemonSet,involvedObject.name=${daemonSetName} --sort-by='.lastTimestamp' -o json`,
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get configmaps -n ${namespaceName} -o json`,
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get secrets -n ${namespaceName} -o json`,
          activeConfig?.path,
        ),
        window.electron?.ipcRenderer.executeKubectl(
          `kubectl get services -n ${namespaceName} -o json`,
          activeConfig?.path,
        ),
      ]);

      if (!daemonSetRes.success) {
        setError(daemonSetRes.error || 'Failed to fetch daemonset details');
        return;
      }

      const parseResponse = (response: KubectlResponse) => {
        if (!response.success) return null;
        try {
          return typeof response.data === 'string'
            ? JSON.parse(response.data)
            : response.data;
        } catch {
          return null;
        }
      };

      const daemonSetData = parseResponse(daemonSetRes);
      const podsData = parseResponse(podsRes);
      const eventsData = parseResponse(eventsRes);
      const configMapsData = parseResponse(configMapsRes);
      const secretsData = parseResponse(secretsRes);
      const servicesData = parseResponse(servicesRes);

      setDaemonSetInfo(daemonSetData);

      // Filter pods that belong to this daemonset
      const daemonSetLabels = daemonSetData?.spec?.selector?.matchLabels || {};

      const daemonSetPods = (podsData?.items || []).filter((pod: any) => {
        const podLabels = pod.metadata?.labels || {};

        // Check if all daemonset selector labels match pod labels
        return Object.entries(daemonSetLabels).every(
          ([key, value]) => podLabels[key] === value,
        );
      });

      setPods(daemonSetPods);
      setEvents(eventsData?.items || []);

      // Process ConfigMaps used by the DaemonSet
      const containers = daemonSetData?.spec?.template?.spec?.containers || [];
      const initContainers =
        daemonSetData?.spec?.template?.spec?.initContainers || [];
      const allContainers = [...containers, ...initContainers];

      const usedConfigMaps = new Set<string>();
      const configMapUsage = new Map<string, any>();

      allContainers.forEach((container: any) => {
        // Check environment variables
        (container.env || []).forEach((envVar: any) => {
          if (envVar.valueFrom?.configMapKeyRef) {
            const configMapName = envVar.valueFrom.configMapKeyRef.name;
            const { key } = envVar.valueFrom.configMapKeyRef;
            usedConfigMaps.add(configMapName);

            if (!configMapUsage.has(configMapName)) {
              configMapUsage.set(configMapName, { keys: [], usageType: 'env' });
            }
            configMapUsage.get(configMapName).keys.push(key);
          }
        });

        // Check envFrom
        (container.envFrom || []).forEach((envFrom: any) => {
          if (envFrom.configMapRef) {
            const configMapName = envFrom.configMapRef.name;
            usedConfigMaps.add(configMapName);
            configMapUsage.set(configMapName, {
              keys: [],
              usageType: 'envFrom',
              isFullConfigMap: true,
            });
          }
        });

        // Check volume mounts
        (container.volumeMounts || []).forEach((volumeMount: any) => {
          const volumes = daemonSetData?.spec?.template?.spec?.volumes || [];
          const volume = volumes.find((v: any) => v.name === volumeMount.name);
          if (volume?.configMap) {
            const configMapName = volume.configMap.name;
            usedConfigMaps.add(configMapName);

            if (!configMapUsage.has(configMapName)) {
              configMapUsage.set(configMapName, {
                keys: [],
                usageType: 'volume',
              });
            }

            if (volume.configMap.items) {
              volume.configMap.items.forEach((item: any) => {
                configMapUsage.get(configMapName).keys.push(item.key);
              });
            } else {
              configMapUsage.get(configMapName).isFullConfigMap = true;
            }
          }
        });
      });

      const relatedConfigMaps = (configMapsData?.items || [])
        .filter((cm: any) => usedConfigMaps.has(cm.metadata.name))
        .map((cm: any) => ({
          ...cm,
          usageEntry: configMapUsage.get(cm.metadata.name) || {
            keys: [],
            usageType: 'unknown',
          },
        }));

      setConfigMaps(relatedConfigMaps);

      // Process Secrets used by the DaemonSet
      const usedSecrets = new Set<string>();
      const secretUsage = new Map<string, any>();

      allContainers.forEach((container: any) => {
        // Check environment variables
        (container.env || []).forEach((envVar: any) => {
          if (envVar.valueFrom?.secretKeyRef) {
            const secretName = envVar.valueFrom.secretKeyRef.name;
            const { key } = envVar.valueFrom.secretKeyRef;
            usedSecrets.add(secretName);

            if (!secretUsage.has(secretName)) {
              secretUsage.set(secretName, { keys: [], usageType: 'env' });
            }
            secretUsage.get(secretName).keys.push(key);
          }
        });

        // Check envFrom
        (container.envFrom || []).forEach((envFrom: any) => {
          if (envFrom.secretRef) {
            const secretName = envFrom.secretRef.name;
            usedSecrets.add(secretName);
            secretUsage.set(secretName, {
              keys: [],
              usageType: 'envFrom',
              isFullSecret: true,
            });
          }
        });

        // Check volume mounts
        (container.volumeMounts || []).forEach((volumeMount: any) => {
          const volumes = daemonSetData?.spec?.template?.spec?.volumes || [];
          const volume = volumes.find((v: any) => v.name === volumeMount.name);
          if (volume?.secret) {
            const { secretName } = volume.secret;
            usedSecrets.add(secretName);

            if (!secretUsage.has(secretName)) {
              secretUsage.set(secretName, { keys: [], usageType: 'volume' });
            }

            if (volume.secret.items) {
              volume.secret.items.forEach((item: any) => {
                secretUsage.get(secretName).keys.push(item.key);
              });
            } else {
              secretUsage.get(secretName).isFullSecret = true;
            }
          }
        });
      });

      // Check image pull secrets
      const imagePullSecrets =
        daemonSetData?.spec?.template?.spec?.imagePullSecrets || [];
      imagePullSecrets.forEach((ips: any) => {
        usedSecrets.add(ips.name);
        secretUsage.set(ips.name, { keys: [], usageType: 'imagePullSecret' });
      });

      const relatedSecrets = (secretsData?.items || [])
        .filter((secret: any) => usedSecrets.has(secret.metadata.name))
        .map((secret: any) => ({
          ...secret,
          usageEntry: secretUsage.get(secret.metadata.name) || {
            keys: [],
            usageType: 'unknown',
          },
        }));

      setSecrets(relatedSecrets);

      // Process Services related to the DaemonSet
      const relatedServices = (servicesData?.items || []).filter(
        (service: any) => {
          const serviceSelectors = service.spec?.selector || {};

          // If service has no selectors, it's not related
          if (Object.keys(serviceSelectors).length === 0) {
            return false;
          }

          // Check if service selectors match DaemonSet labels
          return Object.entries(serviceSelectors).every(
            ([key, value]) => daemonSetLabels[key] === value,
          );
        },
      );

      setServices(relatedServices);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    if (daemonSetName && namespaceName) {
      fetchDaemonSetDetails();
    }
  }, [daemonSetName, namespaceName, activeConfig?.path]);

  const refetch = () => fetchDaemonSetDetails(false);
  const backgroundRefetch = () => fetchDaemonSetDetails(true);

  return {
    daemonSetInfo,
    pods,
    events,
    configMaps,
    secrets,
    services,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  };
}
