import type { LayoutType } from '@/@types/theme'
import Loading from '@/components/shared/Loading'
import { Alert, Button } from '@/components/ui'
import { store, useStoreState } from '@/store'
import { Suspense, useEffect } from 'react'
import { ErrorBoundary } from 'react-error-boundary'
import { MdArrowBack } from 'react-icons/md'
import { Navigate, useLocation } from 'react-router-dom'
import DialogProvider from './shared/DialogContext'
import DialogShowComponent from './shared/DialogContext/DialogShowComponent'
import UiDialog from './shared/UiDialog'
import { DynamicRouter } from '@/routes/dynamicRouter'

interface ViewsProps {
  pageContainerType?: 'default' | 'gutterless' | 'contained'
  layout?: LayoutType
}

function fallbackRender({ error, resetErrorBoundary }: { error: Error; resetErrorBoundary: any }) {
  return (
    <Alert showIcon className="mb-4" type="danger">
      <h5>{error.name ?? 'Hata!'}</h5>
      <div>{error.message}</div>
      <Button size="xs" className="mt-2" variant="default" onClick={resetErrorBoundary}>
        <MdArrowBack />
      </Button>
    </Alert>
  )
}

const Views = (props: ViewsProps) => {
  const { setWarning, removeError } = store.getActions().base.messages
  const { errors, warning } = useStoreState((state) => state.base.messages)
  const location = useLocation()

  useEffect(() => {
    setWarning('')
  }, [location, setWarning])

  return (
    <ErrorBoundary fallbackRender={fallbackRender}>
      <Suspense fallback={<Loading loading={true} />}>
        {!!warning?.length && (
          <Alert showIcon className="mb-4" type="warning">
            {warning.map((w, i) => (
              <div key={i}>{w}</div>
            ))}
          </Alert>
        )}
        {errors?.some((e) => e.statusCode === '403' || e.statusCode === '401') && (
          <Navigate to="/access-denied" replace />
        )}
        {errors?.map((e) => (
          <UiDialog
            key={e.id}
            isOpen={true}
            type={'danger'}
            onConfirm={() => {
              removeError(e.id)
            }}
            onClose={() => {
              removeError(e.id)
            }}
            title={e.title}
          >
            {e.message}
            <p>{e.statusCode}</p>
            <small className="italic">{e.cid}</small>
          </UiDialog>
        ))}
        <DialogProvider>
          <DialogShowComponent />
          <DynamicRouter />
        </DialogProvider>
      </Suspense>
    </ErrorBoundary>
  )
}

export default Views
