'use client'

// React Imports
import { useState } from 'react'

// Next Imports
import Link from 'next/link'

// MUI Imports
import useMediaQuery from '@mui/material/useMediaQuery'
import { styled, useTheme } from '@mui/material/styles'
import Typography from '@mui/material/Typography'
import IconButton from '@mui/material/IconButton'
import InputAdornment from '@mui/material/InputAdornment'

// Third-party Imports
import classnames from 'classnames'

// Type Imports
import type { SystemMode } from '@core/types'

// Component Imports
import Logo from '@components/layout/shared/Logo'
import CustomTextField from '@core/components/mui/TextField'

// Config Imports

// Hook Imports
import { useImageVariant } from '@core/hooks/useImageVariant'
import { useSettings } from '@core/hooks/useSettings'
import { useTranslations } from 'next-intl'

// Util Imports
import { email, InferInput, minLength, nonEmpty, object, pipe, string } from 'valibot'
import { Controller, SubmitHandler, useForm } from 'react-hook-form'
import { valibotResolver } from '@hookform/resolvers/valibot'
import { useAuth } from '@/hooks'
import Button from '@/@core/components/mui/Button'

// Styled Custom Components
const LoginIllustration = styled('img')(({ theme }) => ({
  zIndex: 2,
  blockSize: 'auto',
  maxBlockSize: 680,
  maxInlineSize: '100%',
  margin: theme.spacing(12),
  [theme.breakpoints.down(1536)]: {
    maxBlockSize: 550
  },
  [theme.breakpoints.down('lg')]: {
    maxBlockSize: 450
  }
}))

const MaskImg = styled('img')({
  blockSize: 'auto',
  maxBlockSize: 355,
  inlineSize: '100%',
  position: 'absolute',
  insetBlockEnd: 0,
  zIndex: -1
})

type ErrorType = {
  message: string[]
}

type FormData = InferInput<typeof schema>

const schema = object({
  identifier: pipe(string(), minLength(1, 'This field is required'), email('Email is invalid')),
  password: pipe(
    string(),
    nonEmpty('This field is required'),
    minLength(8, 'Password must be at least 8 characters long')
  )
})

const LoginV2 = ({ mode }: { mode: SystemMode }) => {
  // States
  const [isPasswordShown, setIsPasswordShown] = useState(false)
  const [errorState, setErrorState] = useState<ErrorType | null>(null)
  const t = useTranslations('LOGIN')

  // Vars
  const darkImg = '/images/pages/auth-mask-dark.png'
  const lightImg = '/images/pages/auth-mask-light.png'
  const darkIllustration = '/images/illustrations/auth/v2-login-dark.png'
  const lightIllustration = '/images/illustrations/auth/v2-login-light.png'
  const borderedDarkIllustration = '/images/illustrations/auth/v2-login-dark-border.png'
  const borderedLightIllustration = '/images/illustrations/auth/v2-login-light-border.png'

  // Hooks
  const { settings } = useSettings()
  const theme = useTheme()
  const hidden = useMediaQuery(theme.breakpoints.down('md'))
  const authBackground = useImageVariant(mode, lightImg, darkImg)

  const characterIllustration = useImageVariant(
    mode,
    lightIllustration,
    darkIllustration,
    borderedLightIllustration,
    borderedDarkIllustration
  )

  const handleClickShowPassword = () => setIsPasswordShown(show => !show)

  const {
    control,
    handleSubmit,
    formState: { errors }
  } = useForm<FormData>({
    resolver: valibotResolver(schema),
    defaultValues: {
      identifier: '',
      password: ''
    }
  })

  const { login, loginFireBase } = useAuth()

  const onSubmit: SubmitHandler<FormData> = async (data: FormData) => {
    login?.mutate({ identifier: data?.identifier, password: data?.password })
  }

  return (
    <div className='flex bs-full justify-center'>
      <div className='flex justify-center items-center bs-full bg-backgroundPaper min-bs-[100dvh] p-6 md:p-12 w-full'>
        <Link href='/' className='absolute block-start-5 sm:block-start-[33px] inline-start-6 sm:inline-start-[38px]'>
          <Logo />
        </Link>
        <div className='flex flex-col gap-6 w-full max-w-[440px]'>
          <div className='flex flex-col gap-1'>
            <Typography variant='h4' className='font-semibold'>
              {t('titlePrefix')} <span className='text-primary'>{t('brand')}</span>
            </Typography>
            <Typography color='text.secondary'>{t('subtitle')}</Typography>
          </div>
          <div className='flex flex-col gap-2 rounded-lg border border-divider p-4 bg-actionHover/50'>
            <div className='flex items-center gap-2'>
              <i className='tabler-shield-check text-textSecondary' />
              <Typography variant='body2' color='text.secondary'>
                {t('valueProps.security')}
              </Typography>
            </div>
            <div className='flex items-center gap-2'>
              <i className='tabler-link text-textSecondary' />
              <Typography variant='body2' color='text.secondary'>
                {t('valueProps.fastLinks')}
              </Typography>
            </div>
            <div className='flex items-center gap-2'>
              <i className='tabler-chart-bar text-textSecondary' />
              <Typography variant='body2' color='text.secondary'>
                {t('valueProps.tracking')}
              </Typography>
            </div>
          </div>
          <form
            noValidate
            autoComplete='off'
            action={() => {}}
            onSubmit={handleSubmit(onSubmit)}
            className='flex flex-col gap-6'
          >
            <Controller
              name='identifier'
              control={control}
              rules={{ required: true }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  autoFocus
                  fullWidth
                  type='email'
                  label={t('fields.email')}
                  placeholder={t('placeholders.email')}
                  onChange={e => {
                    field.onChange(e.target.value)
                    errorState !== null && setErrorState(null)
                  }}
                  {...((errors.identifier || errorState !== null) && {
                    error: true,
                    helperText: errors?.identifier?.message || errorState?.message[0]
                  })}
                />
              )}
            />
            <Controller
              name='password'
              control={control}
              rules={{ required: true }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  fullWidth
                  label={t('fields.password')}
                  placeholder={t('placeholders.password')}
                  id='login-password'
                  type={isPasswordShown ? 'text' : 'password'}
                  onChange={e => {
                    field.onChange(e.target.value)
                    errorState !== null && setErrorState(null)
                  }}
                  slotProps={{
                    input: {
                      endAdornment: (
                        <InputAdornment position='end'>
                          <IconButton
                            edge='end'
                            onClick={handleClickShowPassword}
                            onMouseDown={e => e.preventDefault()}
                          >
                            <i className={isPasswordShown ? 'tabler-eye' : 'tabler-eye-off'} />
                          </IconButton>
                        </InputAdornment>
                      )
                    }
                  }}
                  {...(errors.password && { error: true, helperText: errors.password.message })}
                />
              )}
            />

            <Button
              fullWidth
              variant='contained'
              type='submit'
              disabled={login?.isPending || loginFireBase?.isPending}
              isLoading={login?.isPending || loginFireBase?.isPending}
              withoutTranslation
            >
              {t('actions.login')}
            </Button>
          </form>
        </div>
      </div>
    </div>
  )
}

export default LoginV2
