import { FormProvider, useForm } from 'react-hook-form';

import Stack from '@material-hu/mui/Stack';
import { appearFromBottom, slideInUp } from '@material-hu/utils/animations';

import Button from '@material-hu/components/design-system/Buttons/Button';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { LAYOUT_SX } from '../constants';

import GeneralSection from './components/GeneralSection';
import MessagesSection from './components/MessagesSection';
import ModulesSection from './components/ModulesSection';
import SettingsError from './components/SettingsError';
import SettingsSkeleton from './components/SettingsSkeleton';
import useGetAgentConfig from './hooks/useGetAgentConfig';
import useUpdateAgentConfig from './hooks/useUpdateAgentConfig';
import { type AgentSettingsFormValues } from './types';

const AgentsSettings = () => {
  const { t } = useLokaliseTranslation('agents');

  const { data, isLoading, isError, refetch } = useGetAgentConfig();
  const { mutate: saveConfig, isLoading: isSaving } = useUpdateAgentConfig();

  const form = useForm<AgentSettingsFormValues>({
    values: data,
  });

  const handleSave = form.handleSubmit(values => {
    saveConfig(values, {
      onSuccess: () => {
        form.reset(values);
      },
    });
  });

  if (isLoading) return <SettingsSkeleton />;

  if (isError)
    return (
      <SettingsError
        onRetry={() => refetch()}
        isLoading={isLoading}
      />
    );

  return (
    <FormProvider {...form}>
      <Stack
        sx={{
          gap: 4,
          mb: 4,
          animation: `${appearFromBottom} 300ms ease-in-out`,
          ...LAYOUT_SX,
        }}
      >
        <GeneralSection />

        <MessagesSection />

        <ModulesSection />
      </Stack>

      <Stack
        sx={{
          backgroundColor: theme =>
            theme.palette.new.background.layout.tertiary,
          position: 'sticky',
          bottom: 0,
          py: 2,
          zIndex: 1000,
          animation: `${slideInUp} 300ms ease-out 500ms backwards`,
        }}
      >
        <Stack sx={LAYOUT_SX}>
          <Button
            variant="primary"
            onClick={handleSave}
            loading={isSaving}
            size="large"
            disabled={!form.formState.isDirty}
            sx={{ width: 256, ml: 'auto' }}
          >
            {t('general:save_changes')}
          </Button>
        </Stack>
      </Stack>
    </FormProvider>
  );
};

export default AgentsSettings;
