import React, { useRef } from 'react';
import { useMutation, useQueryClient } from 'react-query';
import { useIntl } from 'react-intl';
import {
  SettingsPageTitle,
  useFocusWhenNavigate,
  useNotification,
  useRBAC,
  useTracking,
} from '@strapi/helper-plugin';
import { HeaderLayout, Layout, ContentLayout } from '@strapi/design-system/Layout';
import { Main } from '@strapi/design-system/Main';
import { Stack } from '@strapi/design-system/Stack';
import { Button } from '@strapi/design-system/Button';
import Check from '@strapi/icons/Check';
import adminPermissions from '../../../../permissions';
import { useConfigurations } from '../../../../hooks';
// import CustomizationInfos from './components/CustomizationInfos';
import { postProjectSettings } from './utils/api';
import getFormData from './utils/getFormData';

const ApplicationInfosPage = () => {
  const inputsRef = useRef();
  const toggleNotification = useNotification();
  const { trackUsage } = useTracking();
  const { formatMessage } = useIntl();
  const queryClient = useQueryClient();
  useFocusWhenNavigate();
  const { updateProjectSettings } = useConfigurations();

  const {
    allowedActions: { canUpdate },
  } = useRBAC(adminPermissions.settings['project-settings']);
  // const canSubmit = canRead && canUpdate;

  // const { data } = useQuery('project-settings', fetchProjectSettings, { enabled: canRead });

  const submitMutation = useMutation((body) => postProjectSettings(body), {
    async onSuccess({ menuLogo, authLogo }) {
      await queryClient.invalidateQueries('project-settings', { refetchActive: true });
      updateProjectSettings({ menuLogo: menuLogo?.url, authLogo: authLogo?.url });
    },
  });

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!canUpdate) return;

    const inputValues = inputsRef.current.getValues();
    const formData = getFormData(inputValues);

    submitMutation.mutate(formData, {
      onSuccess() {
        const { menuLogo, authLogo } = inputValues;

        if (menuLogo.rawFile) {
          trackUsage('didChangeLogo', {
            logo: 'menu',
          });
        }

        if (authLogo.rawFile) {
          trackUsage('didChangeLogo', {
            logo: 'auth',
          });
        }

        toggleNotification({
          type: 'success',
          message: formatMessage({ id: 'app', defaultMessage: 'Saved' }),
        });
      },
      onError() {
        toggleNotification({
          type: 'warning',
          message: { id: 'notification.error', defaultMessage: 'An error occurred' },
        });
      },
    });
  };

  return (
    <Layout>
      <SettingsPageTitle name="Application" />
      <Main>
        <HeaderLayout
          title={formatMessage({ id: 'Settings.application.title', defaultMessage: 'Overview' })}
          subtitle={formatMessage({
            id: 'Settings.application.description',
            defaultMessage: 'Administration panel’s global information',
          })}
          primaryAction={
            <Button onClick={handleSubmit} startIcon={<Check />}>
              {formatMessage({ id: 'global.save', defaultMessage: 'Save' })}
            </Button>
          }
        />
        <ContentLayout>
          <Stack spacing={6}>
            {/* {data && (
              <CheckPermissions permissions={permissions}>
                <Form ref={inputsRef} projectSettingsStored={data} />
              </CheckPermissions>
            )} */}
          </Stack>
        </ContentLayout>
      </Main>
    </Layout>
  );
};

export default ApplicationInfosPage;
