import { useMemo } from 'react';
import type { DeploymentPageFormState, MonitoringFormState } from './useDeploymentPageState';

export interface PerTabDirty {
  monitoring: boolean;
  resources: boolean;
  variables: boolean;
  sensitiveKeys: boolean;
  anyLocalEdit: boolean;
}

// Normalize free-text numeric fields (user types "1.0" / "1" / "1.00" — all equal).
// NaN compares as NaN through JSON, which is harmless since both sides coerce the same.
function normalizeMonitoring(m: MonitoringFormState): Omit<MonitoringFormState, 'samplingRate'> & { samplingRate: number } {
  const { samplingRate, ...rest } = m;
  return { ...rest, samplingRate: parseFloat(samplingRate) };
}

export function useFormDirty(
  form: DeploymentPageFormState,
  serverState: DeploymentPageFormState,
  stagedJar: File | null,
): PerTabDirty {
  return useMemo(() => {
    const monitoring =
      JSON.stringify(normalizeMonitoring(form.monitoring)) !==
      JSON.stringify(normalizeMonitoring(serverState.monitoring));
    const resources = JSON.stringify(form.resources) !== JSON.stringify(serverState.resources);
    const variables = JSON.stringify(form.variables) !== JSON.stringify(serverState.variables);
    const sensitiveKeys = JSON.stringify(form.sensitiveKeys) !== JSON.stringify(serverState.sensitiveKeys);
    const anyLocalEdit = monitoring || resources || variables || sensitiveKeys || !!stagedJar;
    return { monitoring, resources, variables, sensitiveKeys, anyLocalEdit };
  }, [form, serverState, stagedJar]);
}
