import { useGetDashboard, useUpdateDashboard } from '@/api/buster_rest/dashboards';
import { SaveResetFilePopup } from '@/components/features/popups/SaveResetFilePopup';
import { useIsDashboardChanged } from '@/context/Dashboards';
import { useMemoizedFn } from '@/hooks';
import React from 'react';

export const DashboardSaveFilePopup: React.FC<{ dashboardId: string }> = React.memo(
  ({ dashboardId }) => {
    const { data: dashboardResponse } = useGetDashboard({ id: dashboardId });
    const { isDashboardChanged, onResetDashboardToOriginal } = useIsDashboardChanged({
      dashboardId
    });
    const { mutateAsync: onSaveDashboard, isPending: isSaving } = useUpdateDashboard({
      saveToServer: true
    });

    const onSaveDashboardToServer = useMemoizedFn(() => {
      const dashboard = dashboardResponse?.dashboard;
      onSaveDashboard({
        id: dashboardId,
        name: dashboard?.name,
        description: dashboard?.description,
        config: dashboard?.config,
        file: dashboard?.file
      });
    });

    return (
      <SaveResetFilePopup
        open={isDashboardChanged}
        onReset={onResetDashboardToOriginal}
        onSave={onSaveDashboardToServer}
        isSaving={isSaving}
        showHotsKeys={false}
      />
    );
  }
);
