'use client';

import { z as zod } from 'zod';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { faEye, faEyeSlash } from '@fortawesome/free-solid-svg-icons';

import Link from '@mui/material/Link';
import Alert from '@mui/material/Alert';
import Stack from '@mui/material/Stack';
import IconButton from '@mui/material/IconButton';
import LoadingButton from '@mui/lab/LoadingButton';
import InputAdornment from '@mui/material/InputAdornment';

import { paths } from 'src/routes/paths';
import { useRouter } from 'src/routes/hooks';
import { RouterLink } from 'src/routes/components';

import { useBoolean } from 'src/hooks/use-boolean';

import { FontAwesome } from 'src/shared/components/fontawesome';
import { Form, Field } from 'src/shared/components/hook-form';

import { useAuthContext } from 'src/auth/hooks';
import { signInWithPassword } from 'src/auth/context/jwt';

// ----------------------------------------------------------------------

export type SignInSchemaType = zod.infer<typeof SignInSchema>;

export const SignInSchema = zod.object({
  email: zod
    .string()
    .min(1, { message: 'Email is required!' })
    .email({ message: 'Email must be a valid email address!' }),
  password: zod
    .string()
    .min(1, { message: 'Password is required!' })
    .min(6, { message: 'Password must be at least 6 characters!' }),
});

// ----------------------------------------------------------------------

export function JwtSignInView() {
  const router = useRouter();

  const { checkUserSession } = useAuthContext();

  const [errorMsg, setErrorMsg] = useState('');

  const password = useBoolean();

  const defaultValues = {
    email: 'admin12345.alae@example.com',
    password: 'admin12345',
  };

  const methods = useForm<SignInSchemaType>({
    resolver: zodResolver(SignInSchema),
    defaultValues,
  });

  const {
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

  const onSubmit = handleSubmit(async (data) => {
    try {
      await signInWithPassword({ username: data.email, password: data.password });
      await checkUserSession?.();

      router.refresh();
    } catch (error: any) {
      console.error(error);

      const rawMessage =
        typeof error === 'string' ? error : error?.response?.data?.message || error?.message || '';

      const message = (() => {
        const msg = rawMessage.toLowerCase();
        console.log(msg);

        if (msg.includes('user not found')) return 'Utilisateur non trouvé.';
        if (msg.includes('parents, and children do not have access to the back office.'))
          return 'Accès refusé. Les parents et enfants n’ont pas accès au back office.';
        if (msg.includes('your account has been blocked')) return 'Votre compte a été bloqué.';
        if (msg.includes('your account has been suspended')) return 'Votre compte a été suspendu.';
        if (msg.includes('your account has been deleted.')) return 'Votre compte a été supprimé.';

        return 'Une erreur est survenue. Veuillez réessayer.';
      })();

      setErrorMsg(message);
    }
  });

  const renderForm = (
    <Stack spacing={3}>
      <Field.Text name="email" label="Adresse e-mail" InputLabelProps={{ shrink: true }} />

      <Stack spacing={1.5}>
        <Link
          component={RouterLink}
          href={paths.auth.forgotPassword}
          variant="body2"
          color="inherit"
          sx={{ alignSelf: 'flex-end' }}
        >
          Mot de passe oublié ?
        </Link>

        <Field.Text
          name="password"
          label="Mot de passe"
          placeholder="6+ characters"
          type={password.value ? 'text' : 'password'}
          InputLabelProps={{ shrink: true }}
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <IconButton onClick={password.onToggle} edge="end">
                  <FontAwesome icon={password.value ? faEye : faEyeSlash} />
                </IconButton>
              </InputAdornment>
            ),
          }}
        />
      </Stack>

      <LoadingButton
        fullWidth
        color="inherit"
        size="large"
        type="submit"
        variant="contained"
        loading={isSubmitting}
        loadingIndicator="Sign in..."
      >
        Login
      </LoadingButton>
    </Stack>
  );

  return (
    <>
      <Alert severity="info" sx={{ mb: 3 }}>
        Use <strong>{defaultValues.email}</strong>
        {' with password '}
        <strong>{defaultValues.password}</strong>
      </Alert>

      {!!errorMsg && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {errorMsg}
        </Alert>
      )}

      <Form methods={methods} onSubmit={onSubmit}>
        {renderForm}
      </Form>
    </>
  );
}
