/* eslint-disable no-console */
import { Visibility, VisibilityOff } from '@mui/icons-material'
import {
  Alert,
  Box,
  Button,
  IconButton,
  InputAdornment,
  Stack,
  Typography,
  styled,
} from '@mui/material'
import axiosBase from 'axios'
import DeviceDetector from 'device-detector-js'
import Cookies from 'js-cookie'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { Link } from 'react-router-dom'
import { campxLogoPrimary } from '../assets/images'
import axios from '../config/axios'
import adminAxios from '../utils/adminAxios'
import ActionButton from './ActionButton'
import { FormTextField } from './HookForm'
import Image from './Image/Image'
import ResetPassword from './ResetPassword'

export function LoginForm({
  loginUrl,
  close,
}: {
  loginUrl?: string
  close: any
}) {
  const [showPassword, setShowPassword] = useState(false)
  const [forgotMail, setForgotMail] = useState(null)
  const [forgotPassword, setForgotPassword] = useState(true)
  const [resetPassword, setResetPassword] = useState(false)
  const { handleSubmit, control } = useForm()
  const [error, setError] = useState('')
  const [deviceState, setDeviceState] = useState({
    deviceInformation: {
      deviceType: 'browser',
      clientName: 'unknown',
      os: 'unknown',
      osVersion: 'unknown',
      latitude: null,
      longitude: null,
      tokenType: 'WEB',
    },
    isLocationAllowed: true,
  })

  const onSubmit = async (values) => {
    try {
      const res = await axiosBase({
        method: 'POST',
        baseURL: process.env.REACT_APP_API_HOST,
        url: loginUrl ? loginUrl : `/auth-server/auth/login`,
        data: {
          ...values,
          ...deviceState.deviceInformation,
        },
      })
      Cookies.set('campx_tenant', res?.data?.subDomain)
      Cookies.set('campx_session_key', res.data?.token)
      Cookies.set('campx_institution', res.data?.institutionCode)
      window.location.reload();
    } catch (err) {
      // eslint-disable-next-line no-console
      console.log(err)
      setError(err?.response?.data?.message ?? 'Server Error')
    }
  }

  const [mailSent, setMailSent] = useState(false)

  async function handleSendMail() {
    try {
      await axios
        .get(
          `https://api.campx.dev/auth-server/auth/forgot-password?email=${forgotMail}`,
        )
        .then((res) => {
          setForgotMail(null)
          setMailSent(true)
          setError(null)
        })
    } catch (err) {
      if (!forgotMail) {
        setError('Email should not be empty')
        setMailSent(false)
      } else {
        setError(err.response.data.message ?? 'Server Error')
        setMailSent(false)
      }
    }
  }

  useEffect(() => {
    navigator.geolocation.getCurrentPosition((position) => {
      setDeviceState((s) => ({
        ...s,
        deviceInformation: {
          ...s.deviceInformation,
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
        },
      }))
    })
    navigator.permissions
      .query({ name: 'geolocation' })
      .then((permissionStatus) => {
        if (permissionStatus.state === 'denied') {
          setDeviceState((s) => ({
            ...s,
            isLocationAllowed: false,
          }))
        }
      })

    const detector = new DeviceDetector()
    const deviceInfo = detector.parse(navigator.userAgent)
    setDeviceState((s) => ({
      ...s,
      deviceInformation: {
        ...s.deviceInformation,
        clientName: deviceInfo.client?.name || s.deviceInformation.clientName,
        os: deviceInfo.os?.name || s.deviceInformation.os,
        osVersion: deviceInfo.os?.version || s.deviceInformation.osVersion,
      },
    }))

    const restLink = window.location.pathname.split('/')[1]
    if (restLink == 'reset-password') {
      setResetPassword(true)
    }
  }, [])

  return (
    <Box sx={{ position: 'relative', height: '100%' }}>
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'center',
          margin: '30px 0',
          flexDirection: 'column',
          gap: '10px',
          alignItems: 'center',
        }}
      >
        <Image alt="" height="auto" width={'200px'} src={campxLogoPrimary} />
        <Typography variant="body2">Developer Login</Typography>
      </Box>
      {resetPassword ? (
        <>
          <ResetPassword />
        </>
      ) : forgotPassword ? (
        <form onSubmit={handleSubmit(onSubmit)}>
          <Stack gap={'30px'} sx={{ display: resetPassword ? 'none' : 'flex' }}>
            <FormTextField
              control={control}
              name="username"
              label="User ID"
              required
            />
            <FormTextField
              control={control}
              name="password"
              label="Password"
              type={showPassword ? 'text' : 'password'}
              required
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton
                      size="small"
                      aria-label="toggle password visibility"
                      onClick={() => setShowPassword((prev) => !prev)}
                      edge="end"
                    >
                      {showPassword ? <VisibilityOff /> : <Visibility />}
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
            {!deviceState.isLocationAllowed && (
              <Alert severity="warning" sx={{ marginTop: '20px' }}>
                Please Enable Location Services
              </Alert>
            )}
            <ActionButton type="submit">Login</ActionButton>
            <Typography
              variant="h6"
              align="right"
              onClick={() => setForgotPassword(false)}
            >
              <StyledLink to="/">Forgot Password</StyledLink>
            </Typography>
          </Stack>
        </form>
      ) : (
        <>
          <Stack gap={'30px'}>
            <FormTextField
              control={control}
              name="email"
              label="Email"
              required
              onChange={(e) => setForgotMail(e.target.value)}
            />
            <Button onClick={() => handleSendMail()}>Send Email</Button>

            <Typography
              variant="subtitle2"
              onClick={() => {
                setForgotPassword(true)
                setError('')
                setMailSent(false)
              }}
              align="right"
            >
              <StyledLink to="/">Login here</StyledLink>
            </Typography>

            {mailSent && (
              <Alert severity="success">
                Reset password link has been sent to your email.
              </Alert>
            )}
          </Stack>
        </>
      )}

      {error && (
        <Alert severity="error" sx={{ marginTop: '20px' }}>
          {error}
        </Alert>
      )}
    </Box>
  )
}

export const StyledLink = styled(Link)({
  textDecoration: 'none',
  color: 'black',
})

export default LoginForm

const SuperAdminLoginForm = ({ close }) => {
  const [showPassword, setShowPassword] = useState(false)
  const [loading, setLoading] = useState(false)
  const { handleSubmit, control } = useForm({
    defaultValues: null,
  })
  const [error, setError] = useState('')

  const onSubmit = async (values) => {
    setLoading(true)
    try {
      const res = await adminAxios.post(`/auth/login`, values)
      Cookies.set('campx_admin_session_key', res?.data?.cookie)

      setLoading(false)
      window.location.href = '/campx'
    } catch (err) {
      setLoading(false)
      setError(err.response.data.message ?? 'Server Error')
    }
  }

  const onError = (e) => {
    console.log(e)
  }

  return (
    <Box width={'100%'} marginTop="20px">
      <form onSubmit={handleSubmit(onSubmit, onError)}>
        <Stack gap={'40px'}>
          <Typography variant="h6" textAlign={'center'}>
            Sign in to Super Admin Account
          </Typography>
          <FormTextField
            control={control}
            name="username"
            label="Username/Email"
            required
          />
          <FormTextField
            control={control}
            name="password"
            label="Password"
            type={showPassword ? 'text' : 'password'}
            required
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    size="small"
                    aria-label="toggle password visibility"
                    onClick={() => setShowPassword((prev) => !prev)}
                    edge="end"
                  >
                    {showPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />
          <ActionButton
            type="submit"
            fullWidth
            disabled={loading}
            loading={loading}
          >
            Login
          </ActionButton>
        </Stack>
      </form>
      {error && (
        <Alert severity="error" sx={{ marginTop: '20px' }}>
          {error}
        </Alert>
      )}
    </Box>
  )
}
