'use client';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Divider from '@mui/material/Divider';
import Stack from '@mui/material/Stack';
import { TextField, Alert } from '@mui/material';
import Typography from '@mui/material/Typography';
import NextLink from 'next/link';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { loginSchema, LoginInput, AuthLoginProps } from '../interfaces/types';
import { useAuth } from '../hooks/useAuth';
import CustomFormLabel from '../components/forms/theme-elements/CustomFormLabel';
import AuthSocialButtons from './AuthSocialButtons';

const AuthLogin = ({ title, subtitle, subtext }: AuthLoginProps) => {
  const { loginMutation } = useAuth();

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginInput>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      username: '',
      password: '',
    },
  });

  const onSubmit = (data: LoginInput) => {
    loginMutation.mutate(data);
  };

  return (
    <>
      {title ? (
        <Typography fontWeight="700" variant="h4" mb={1}>
          {title}
        </Typography>
      ) : null}

      {subtext}

      <AuthSocialButtons title="Entrar com" />
      <Box mt={4} mb={2}>
        <Divider>
          <Typography
            component="span"
            color="textSecondary"
            variant="h6"
            fontWeight="400"
            position="relative"
            px={2}
          >
            ou faça login com
          </Typography>
        </Divider>
      </Box>

      {loginMutation.isError && (
        <Box mt={3}>
          <Alert severity="error">
            {(() => {
              const error = loginMutation.error;
              if (error && typeof error === 'object' && 'response' in error) {
                const axiosError = error as {
                  response?: { data?: { message?: string } };
                };
                return (
                  axiosError.response?.data?.message || 'Erro ao realizar login'
                );
              }
              return 'Erro ao realizar login';
            })()}
          </Alert>
        </Box>
      )}

      <form onSubmit={handleSubmit(onSubmit)}>
        <Stack>
          <Box>
            <CustomFormLabel htmlFor="username">Usuário</CustomFormLabel>
            <TextField
              id="username"
              variant="outlined"
              fullWidth
              {...register('username')}
              error={!!errors.username}
              helperText={errors.username?.message}
            />
          </Box>
          <Box>
            <CustomFormLabel htmlFor="password">Senha</CustomFormLabel>
            <TextField
              id="password"
              type="password"
              variant="outlined"
              fullWidth
              {...register('password')}
              error={!!errors.password}
              helperText={errors.password?.message}
            />
          </Box>
          <Stack
            justifyContent="flex-end"
            direction="row"
            alignItems="center"
            my={2}
            spacing={1}
          >
            <Typography
              fontWeight="500"
              sx={{
                textDecoration: 'none',
                color: 'primary.main',
              }}
            >
              <NextLink
                href="/"
                style={{ textDecoration: 'none', color: 'inherit' }}
              >
                Esqueceu sua senha ?
              </NextLink>
            </Typography>
          </Stack>
        </Stack>
        <Box>
          <Button
            color="primary"
            variant="contained"
            size="large"
            fullWidth
            type="submit"
            disabled={loginMutation.isPending}
          >
            {loginMutation.isPending ? 'Entrando...' : 'Entrar'}
          </Button>
        </Box>
      </form>
      {subtitle}
    </>
  );
};

export default AuthLogin;
