'use client'

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

// Next Imports
import Link from 'next/link'
import { useLocale, useTranslations } from 'next-intl'

// MUI Imports
import Typography from '@mui/material/Typography'
import IconButton from '@mui/material/IconButton'
import InputAdornment from '@mui/material/InputAdornment'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Chip from '@mui/material/Chip'
import Stack from '@mui/material/Stack'

// 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'

// Hook Imports
import { useSettings } from '@core/hooks/useSettings'

// 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'

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 featureHighlights = [
  { icon: 'tabler-chart-line', color: 'primary' as const, key: 'features.analytics' },
  { icon: 'tabler-tools-kitchen-2', color: 'success' as const, key: 'features.menuManagement' },
  { icon: 'tabler-shopping-cart', color: 'warning' as const, key: 'features.orderTracking' }
] as const

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

  // Hooks
  const { settings } = useSettings()
  const { login } = useAuth()
  const locale = useLocale()
  const t = useTranslations('login')

  // Vars
  const scenicImage = '/images/xmenu3.jpg'
  const isArabic = locale === 'ar'
  const direction = isArabic ? 'rtl' : 'ltr'

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

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

  const isLoading = login?.isPending

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

  return (
    <div className='flex bs-full justify-center'>
      <div
        className={classnames('flex bs-full flex-1 min-bs-[100dvh] relative max-md:hidden overflow-hidden', {
          'border-ie': settings.skin === 'bordered'
        })}
        style={{
          backgroundImage: `linear-gradient(120deg, rgba(12,17,28,0.75), rgba(12,17,28,0.35)), url(${scenicImage})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center'
        }}
      >
        <Box
          sx={{
            position: 'absolute',
            inset: 0,
            background: 'radial-gradient(circle at 20% 25%, rgba(99,102,241,0.35), transparent 55%)'
          }}
        />
      </div>

      <div className='flex justify-center items-center bs-full bg-backgroundPaper !min-is-full p-6 md:!min-is-[unset] md:p-12 md:is-[500px] relative overflow-hidden'>
        <Box
          className='absolute inset-0 pointer-events-none'
          sx={{
            background: 'radial-gradient(circle at 10% 15%, rgba(99,102,241,0.12), transparent 45%)'
          }}
        />
        <Link
          href={'/'}
          className='absolute block-start-5 sm:block-start-[33px] inline-start-6 sm:inline-start-[38px] z-[2]'
        >
          <Logo />
        </Link>

        <Box
          className='flex flex-col gap-8 is-full sm:is-auto md:is-full sm:max-is-[420px] md:max-is-[unset] mt-3 mbs-11 sm:mbs-14 md:mbs-0 relative z-[1]'
          dir={direction}
        >
          <div className='flex flex-col gap-3 text-center md:text-start'>
            <div className='flex items-center justify-center md:justify-start gap-2'>
              <i className='tabler-chef-hat text-primary' style={{ fontSize: '2rem' }} />
              <Typography variant='h4' className='font-semibold'>
                {t('welcomeHeading')}
              </Typography>
            </div>
            <Typography color='text.secondary'>{t('welcomeBody')}</Typography>
          </div>

          <Card elevation={0} className='border border-divider'>
            <CardContent className='flex flex-col gap-3'>
              <Typography variant='subtitle2'>{t('featureTitle')}</Typography>
              <div className='grid grid-cols-3 gap-3'>
                {featureHighlights.map(feature => (
                  <div key={feature.key} className='flex flex-col items-center gap-2 text-center'>
                    <Box
                      className='flex items-center justify-center rounded-lg text-white'
                      sx={{
                        width: 40,
                        height: 40,
                        bgcolor: `${feature.color}.main`
                      }}
                    >
                      <i className={feature.icon} style={{ fontSize: '1.25rem' }} />
                    </Box>
                    <Typography variant='caption' className='font-medium leading-tight'>
                      {t(feature.key)}
                    </Typography>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>

          <form
            noValidate
            autoComplete='off'
            action={() => {}}
            onSubmit={handleSubmit(onSubmit)}
            className='flex flex-col gap-5'
          >
            <Controller
              name='identifier'
              control={control}
              rules={{ required: true }}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  autoFocus
                  fullWidth
                  type='email'
                  label={t('emailLabel')}
                  placeholder={t('emailPlaceholder')}
                  autoComplete='email'
                  onChange={e => {
                    field.onChange(e.target.value)
                    errorState !== null && setErrorState(null)
                  }}
                  slotProps={{
                    input: {
                      startAdornment: (
                        <InputAdornment position='start'>
                          <i className='tabler-mail' />
                        </InputAdornment>
                      )
                    }
                  }}
                  {...((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('passwordLabel')}
                  placeholder={t('passwordPlaceholder')}
                  id='login-password'
                  type={isPasswordShown ? 'text' : 'password'}
                  autoComplete='current-password'
                  onChange={e => {
                    field.onChange(e.target.value)
                    errorState !== null && setErrorState(null)
                  }}
                  slotProps={{
                    input: {
                      startAdornment: (
                        <InputAdornment position='start'>
                          <i className='tabler-lock' />
                        </InputAdornment>
                      ),
                      endAdornment: (
                        <InputAdornment position='end'>
                          <IconButton
                            edge='end'
                            onClick={handleClickShowPassword}
                            onMouseDown={e => e.preventDefault()}
                            aria-label='toggle password visibility'
                          >
                            <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={isLoading}
              isLoading={isLoading}
              withoutTranslation={true}
              size='large'
              className='transition-transform hover:scale-[1.02]'
            >
              {isLoading ? t('buttonLoading') : t('buttonIdle')}
            </Button>
          </form>
        </Box>
      </div>
    </div>
  )
}

export default LoginV2
