import { Alert, Box, Button, styled, Typography } from '@mui/material'
import Cookies from 'js-cookie'
import { useEffect, useState } from 'react'
import {
  internalserver,
  nointernet,
  pagenotfound,
  permissiondenied,
  unauth,
} from '../../assets/images'
import axios from '../../config/axios'
import { openRootModal } from '../../contexts/RootModal'
import { PermissionsStore } from '../../shared-state'
import { useModal } from '../DrawerWrapper/DrawerWrapper'

const StyledAlert = styled(Alert)(({ theme }) => ({
  height: '60px',
  border: `1px solid ${theme.palette.error.main}`,
  display: 'flex',
  alignItems: 'center',
  '& .MuiAlert-message': {
    padding: 0,
  },
  '& .MuiTypography-root': {
    margin: 0,
  },
  position: 'relative',
  '& .retryBtn': {
    color: '#661b2a',
    position: 'absolute',
    right: 8,
    top: 8,
  },
}))

const StyledBox = styled(Box)(({ theme }) => ({
  width: '100%',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  justifyContent: 'center',
}))

export default function ErrorFallback({ error, resetErrorBoundary }) {
  if (error?.response?.status) {
    switch (error?.response?.status) {
      case 401:
        return <UnAuth resetBoundary={resetErrorBoundary} />

      case 500:
        return (
          <InternalServer resetBoundary={resetErrorBoundary} error={error} />
        )

      case 403:
        return <PemissionDenied resetBoundary={resetErrorBoundary} />

      default:
        return (
          <InternalServer resetBoundary={resetErrorBoundary} error={error} />
        )
    }
  }

  if (error?.message === 'Network Error') {
    return <NoInternet resetBoundary={resetErrorBoundary} />
  }

  return (
    <Box sx={{ marginTop: '16px', padding: '20px' }}>
      <StyledAlert severity="error">
        {error?.response?.data?.message ?? error?.message}
        <Button
          className="retryBtn"
          onClick={() => resetErrorBoundary()}
          size="small"
          color="error"
          variant="outlined"
        >
          Try Again
        </Button>
      </StyledAlert>
    </Box>
  )
}

export function PageNotFound({ resetBoundary }) {
  return (
    <>
      <StyledBox>
        <img
          src={pagenotfound}
          alt="page not found"
          width={470}
          style={{ marginTop: '20px' }}
        />
        <Typography variant="h1">Page Not Found.</Typography>
        <Button sx={{ marginTop: '20px' }} onClick={() => resetBoundary()}>
          Try Again
        </Button>
      </StyledBox>
    </>
  )
}

export function NoInternet({ resetBoundary }) {
  return (
    <>
      <StyledBox>
        <img src={nointernet} alt="No Internet Found" width={470} />
        <Typography variant="h1">No Internet Found.</Typography>
        <Button sx={{ marginTop: '20px' }} onClick={() => resetBoundary()}>
          Try Again
        </Button>
      </StyledBox>
    </>
  )
}

export function PemissionDenied({ resetBoundary }) {
  return (
    <>
      <StyledBox>
        <img src={permissiondenied} alt="permission denied" width={470} />
        <Typography variant="h1">Permission Denied.</Typography>
        <Button sx={{ marginTop: '20px' }} onClick={() => resetBoundary()}>
          Try Again
        </Button>
      </StyledBox>
    </>
  )
}

export function InternalServer({ resetBoundary, error }) {
  return (
    <>
      <StyledBox>
        <img src={internalserver} alt="internal server error" width={470} />
        <Typography variant="h1" marginTop={'20px'}>
          Internal Server Error.
        </Typography>
        <Typography variant="body1">
          {error?.response?.data?.message
            ? typeof error?.response?.data?.message === 'string'
              ? error?.response?.data?.message
              : JSON.stringify(error?.response?.data?.message)
            : 'Internal Server Error'}
        </Typography>
        <Button
          size="small"
          variant="outlined"
          sx={{ marginTop: '20px' }}
          onClick={() => resetBoundary()}
        >
          Try Again
        </Button>
      </StyledBox>
    </>
  )
}

export function UnAuth({ resetBoundary }) {
  const modal = useModal()
  const [username, setUsername] = useState('')
  const [loading, setLoading] = useState(false)

  const url = window.location.origin
  const origin = window?.location?.origin?.split('.')
  const isDevelopment =
    process.env.NODE_ENV === 'development' ||
    origin?.slice(-2).join('.') === 'campx.dev'
  const isSetup = window.location.hostname.split('.').includes('setup')
  const sessionCookie = Cookies.get('campx_session_key')

  const appinit = async () => {
    setLoading(true)
    await axios
      .get('/auth/my-permissions')
      .then((res) => {
        setUsername(res.data.user.fullName)
        PermissionsStore.update((s) => {
          s.permissions = {
            ...res.data?.permissions,
            can_settings_view: 1,
            can_dashboard_view: 1,
            can_individual_pages_view: 1,
          } as any
        })
        setLoading(false)
      })
      .catch((e) => {
        openRootModal({
          key: 'login',
        })
      })
  }
  function LoginPage() {
    if (isDevelopment) {
      if (!sessionCookie) {
        openRootModal({
          key: 'login',
        })
      } else {
        appinit()
      }
    } else {
      if (!sessionCookie) {
        window.location.replace(`https://www.id.campx.in/?redirect_to=${url}`)
      } else {
        appinit()
      }
    }
  }

  useEffect(() => {
    if (!isDevelopment && !isSetup) {
      window.location.replace(`https://www.id.campx.in/?redirect_to=${url}`)
    }
  }, [isDevelopment])

  return (
    <>
      <StyledBox>
        <img src={unauth} alt="unauthorized" width={470} />
        <Typography variant="h1" marginTop={'20px'}>
          UnAuthorized.
        </Typography>
        <Box
          sx={{
            display: 'flex',
            marginTop: '20px',
          }}
        >
          <Button
            variant="outlined"
            sx={{ marginRight: '10px' }}
            onClick={() => resetBoundary()}
          >
            Try Again
          </Button>

          <Button onClick={() => LoginPage()}>Click here to Login</Button>
        </Box>
      </StyledBox>
    </>
  )
}
