'use client';
import * as React from 'react';
import dayjs from 'dayjs';
import {
  VehicleAnomalyConfig,
  createDefaultVehicleAnomalyConfig,
  ConfigKey,
  updateDetails as _updateDetails,
  setEnabled as _setEnabled,
  applyDetailsToKeys as _applyDetailsToKeys,
} from '@/shared/_mock/flottes/_anomaly-config';

type VRequired = Required<VehicleAnomalyConfig>;

export function useVehicleConfig(vehicleId: string | undefined) {
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [config, setConfig] = React.useState<VehicleAnomalyConfig>(
    createDefaultVehicleAnomalyConfig()
  );

  const refresh = React.useCallback(async () => {
    setLoading(true);
    try {
      setConfig((c) =>
        _updateDetails(c, 'abnormalConsumption', 'endDate', dayjs().add(30, 'day').toDate())
      );
    } finally {
      setLoading(false);
    }
  }, [vehicleId]);

  React.useEffect(() => {
    refresh();
  }, [refresh]);

  const setEnabled = (key: ConfigKey, enabled: boolean) =>
    setConfig((prev) => _setEnabled(prev, key, enabled));

  const updateDetails = <K extends ConfigKey, F extends keyof VRequired[K]['details']>(
    key: K,
    field: F,
    value: VRequired[K]['details'][F]
  ) => setConfig((prev) => _updateDetails(prev, key, field, value));

  const saveAll = async () => {
    setSaving(true);
    try {
      console.log('SAVE anomaly-config', { vehicleId, payload: config });
    } finally {
      setSaving(false);
    }
  };
  const applyToOthers = React.useCallback(
    (sourceKey: ConfigKey, targetKeys: ConfigKey[], opts?: { copyEnabled?: boolean }) => {
      setConfig((prev) =>
        _applyDetailsToKeys(prev, sourceKey, targetKeys, { copyEnabled: true, ...opts })
      );
    },
    []
  );

  return { loading, saving, config, setEnabled, updateDetails, saveAll, refresh, applyToOthers };
}
