import { useThemeConfig } from '@/components/Layout/ThemeProvider';
import { SimpleForm } from '@/components/ra-forms/SimpleForm';
import { Toolbar } from '@/components/ra-forms/Toolbar';
import { TextInput } from '@/components/ra-inputs';
import { Alert, AlertTitle, Grid } from '@mui/material';
import {
  EditContextProvider,
  ResourceContextProvider,
  required,
  useAuthProvider,
  useNotify,
  useTranslate
} from 'ra-core';
import { useCallback, useState } from 'react';
import { SaveButton } from 'react-admin';
import { useQueryClient } from 'react-query';

function ChangePasswordForm({ onSuccess, firstAccess }: ChangePasswordFormProps): JSX.Element {
  const { spacing } = useThemeConfig();
  const [saving, setSaving] = useState(false);
  const authProvider = useAuthProvider();
  const translate = useTranslate();
  const notify = useNotify();
  const queryClient = useQueryClient();
  const handleSubmit = useCallback(
    (data: any) => {
      const { oldPassword, newPassword } = data;
      setSaving(true);
      authProvider
        ?.changePassword(oldPassword, newPassword)
        .then(() => {
          notify('ra.auth.password_changed');
          queryClient.invalidateQueries(['auth', 'getIdentity']);
          onSuccess();
        })
        .catch((error: any) => {
          notify(error?.message || error?.toString(), { type: 'error' });
        })
        .finally(() => setSaving(false));
    },
    [authProvider, onSuccess, notify, queryClient]
  );
  return (
    <ResourceContextProvider value="user/change-password">
      <EditContextProvider
        value={{
          record: {},
          resource: 'user/change-password',
          // @ts-ignore
          save: handleSubmit
        }}
      >
        <SimpleForm
          onSubmit={handleSubmit}
          toolbar={
            <Toolbar>
              <SaveButton disabled={saving} />
            </Toolbar>
          }
        >
          <Grid container spacing={spacing}>
            {firstAccess === true && (
              <Grid item xs={12}>
                <Alert severity="warning">
                  <AlertTitle>{translate('ra.auth.first_access.change_password')}</AlertTitle>
                  {translate('ra.auth.first_access.change_password_helper')}
                </Alert>
              </Grid>
            )}
            <Grid item xs={12}>
              <TextInput source="oldPassword" type="password" validate={required()} />
            </Grid>
            <Grid item xs={12}>
              <TextInput source="newPassword" type="password" validate={required()} />
            </Grid>
          </Grid>
        </SimpleForm>
      </EditContextProvider>
    </ResourceContextProvider>
  );
}
type ChangePasswordFormProps = {
  onSuccess: () => void;
  firstAccess?: boolean;
};

export { ChangePasswordForm };
export type { ChangePasswordFormProps };
