import React, { useRef } from 'react';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import { useIntl } from 'react-intl';
import {
  SettingsPageTitle,
  useFocusWhenNavigate,
  CheckPermissions,
  useNotification,
  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 { useConfigurations } from '../../../../hooks';
import Form from './components/Form';
import { fetchProjectSettings, postProjectSettings } from './utils/api';
import getFormData from './utils/getFormData';

const permissions = [{ action: 'admin::project-settings.update', subject: null }];

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

  const { data } = useQuery('project-settings', fetchProjectSettings);

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

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

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

        if (menuLogo.rawFile) {
          trackUsage('didChangeLogo');
        }
      },
      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;
