import { useEffect, useState } from 'react'
import { get } from '@/rtk/helpers/apiService'
import { deleteDocument, listDocument } from '@/api/Admin'
import { Xdelete } from '@/rtk/helpers/CRUD'
import { useSelector } from 'react-redux'
import { RootState } from '@/rtk/store'

import { Anchor, Box, Button, Dialog, Group, Loader, Text } from '@mantine/core'
import { useDisclosure } from '@mantine/hooks'
import { notifications } from '@mantine/notifications'
import {
  IconEdit,
  IconFileTypeDoc,
  IconFileTypePdf,
  IconFileTypeXls,
  IconLink,
  IconX,
} from '@tabler/icons-react'
import DataTableAll from '@/components/DataTable/DataTable'
import ModalFileDocument from './ModalFileDocument'

import classes from './Document.module.css'
import ModalAddDocument from './ModalAddDocument'
import ModalEditDocument from './ModalEditDocument'

interface TDocument {
  id: number
  title: string
  uri: string
  type: string
  is_active: boolean
  created_at: string
  updated_at: string
}

type RequestPagination = {
  data: TDocument[]
  status: boolean
}

const Document = () => {
  const user = useSelector((state: RootState) => state.authentication)

  const [loader, setLoader] = useState<boolean>(false)
  const [rows, setRows] = useState<RequestPagination>({
    data: [],
    status: true,
  })
  const [selectDataRow, setSelectDataRow] = useState<any>({})

  const [openedModalAdd, { open: openModalAdd, close: closeModalAdd }] =
    useDisclosure(false)
  const [openedModalEdit, { open: openModalEdit, close: closeModalEdit }] =
    useDisclosure(false)
  const [openedModalFile, { open: openModalFile, close: closeModalFile }] =
    useDisclosure(false)

  const [openedDialogDelete, setOpenedDialogDelete] = useState(false)
  const [deleteLoader, setDeleteLoader] = useState<boolean>(false)

  useEffect(() => {
    getAllData()
  }, [])

  const getAllData = async () => {
    try {
      setLoader(true)
      const params = {}
      const res = await get(listDocument, params)
      if (res.status) {
        setRows(res)
      }
    } catch (error: any) {
      notifications.show({
        title: 'Error',
        message: error.message ?? error,
        color: 'red',
      })
    } finally {
      setLoader(false)
    }
  }

  const handleDelete = async (id: number | undefined) => {
    try {
      setDeleteLoader(true)
      await Xdelete(deleteDocument, { id: id }, getAllData)
      setSelectDataRow({})
      setOpenedDialogDelete(false)
    } catch (error) {
      console.log(error)
    } finally {
      setDeleteLoader(false)
    }
  }

  const getFileTypeIcon = (row: TDocument) => {
    const uri = row?.uri
    if (!uri) return null

    const extension = uri.split('.').pop()?.toLowerCase()

    if (['doc'].includes(extension!)) {
      return (
        <a
          href={`${import.meta.env.VITE_BACKEND_URL}${
            import.meta.env.VITE_BACKEND_URL?.includes('localhost')
              ? ''
              : 'image/'
          }${uri}`}
          download={row.title}
          target="_self"
        >
          <IconFileTypeDoc style={{ color: '#1e62c1' }} />
        </a>
      )
    }

    if (['xls', 'xlsx'].includes(extension!)) {
      return (
        <a
          href={`${import.meta.env.VITE_BACKEND_URL}${
            import.meta.env.VITE_BACKEND_URL?.includes('localhost')
              ? ''
              : 'image/'
          }${uri}`}
          download={row.title}
          target="_self"
        >
          <IconFileTypeXls style={{ color: '#0e864b' }} />
        </a>
      )
    }

    if (['docx'].includes(extension!)) {
      return (
        <IconFileTypeDoc
          onClick={() => {
            openModalFile()
            setSelectDataRow(row)
          }}
          style={{ color: '#1e62c1' }}
        />
      )
    }

    return (
      <IconFileTypePdf
        onClick={() => {
          openModalFile()
          setSelectDataRow(row)
        }}
        style={{ color: '#ff1b0e' }}
      />
    )
  }

  const columns = [
    {
      name: 'title',
      size: '50%',
      header: 'Title',
    },
    {
      name: 'uri',
      size: '45%',
      header: 'URI',
      render: (row: TDocument) => {
        return (
          <Box>
            {row.type === 'file' ? (
              <Box
                w="fit-content"
                style={{ cursor: 'pointer' }}
                title={`File .${row?.uri
                  .split('.')
                  .pop()
                  ?.toLowerCase()} detail`}
              >
                {getFileTypeIcon(row)}
              </Box>
            ) : (
              <Anchor
                ta="start"
                href={row?.uri}
                target="_blank"
                title={row?.uri}
              >
                <IconLink />
              </Anchor>
            )}
          </Box>
        )
      },
    },
    {
      name: '#',
      size: '5%',
      header: 'Action',
      render: (row: TDocument) => {
        if (!user.user.user.permission.includes('admin')) {
          return ''
        }

        return (
          <Box className={classes.optionIcon}>
            <IconEdit
              className={classes.editIcon}
              onClick={() => {
                setSelectDataRow(row)
                openModalEdit()
              }}
              width={20}
              height={20}
            />
            <IconX
              className={classes.deleteIcon}
              onClick={() => {
                setOpenedDialogDelete(true)
                setSelectDataRow(row)
              }}
              width={20}
              height={20}
            />
          </Box>
        )
      },
    },
  ]

  return (
    <Box>
      <div className={classes.title}>
        <h3>
          <Text>Admin/</Text>
          Documents
        </h3>

        {user.user.user.permission.includes('admin') ? (
          <Button onClick={() => openModalAdd()} disabled={loader}>
            + Add
          </Button>
        ) : (
          ''
        )}
      </div>

      <Box mt={'md'}>
        {loader ? (
          <Box ta={'center'}>
            <Loader size={40} mt={'15%'} />
          </Box>
        ) : (
          <DataTableAll
            data={rows.data}
            columns={columns}
            size=""
            searchInput
          />
        )}
      </Box>

      {openedModalFile && (
        <ModalFileDocument
          opened={openedModalFile}
          close={closeModalFile}
          selectDataRow={selectDataRow}
          setSelectDataRow={setSelectDataRow}
        />
      )}

      {openedModalAdd && (
        <ModalAddDocument
          opened={openedModalAdd}
          close={closeModalAdd}
          getAllData={getAllData}
        />
      )}

      {openedModalEdit && (
        <ModalEditDocument
          opened={openedModalEdit}
          close={closeModalEdit}
          selectDataRow={selectDataRow}
          setSelectDataRow={setSelectDataRow}
          getAllData={getAllData}
        />
      )}

      {openedDialogDelete && (
        <Dialog
          opened={openedDialogDelete}
          className={classes.dialog}
          withCloseButton
          onClose={() => {
            setSelectDataRow({})
            setOpenedDialogDelete(false)
          }}
          size="lg"
          radius="md"
          position={{ top: 30, right: 10 }}
        >
          <Box
            className={classes.dialogText}
            size="sm"
            mb="xs"
            fw={500}
            pr={20}
          >
            <Text ta="center">
              Do you want to delete the document <b>{selectDataRow?.title}</b> ?
            </Text>

            <Group justify="center" m={10}>
              <Button
                fw={700}
                size="xs"
                variant="filled"
                color="red"
                onClick={async () => handleDelete(selectDataRow?.id)}
                disabled={deleteLoader}
              >
                Yes
              </Button>
              <Button
                fw={700}
                size="xs"
                variant="filled"
                color="gray"
                onClick={() => {
                  setSelectDataRow({})
                  setOpenedDialogDelete(false)
                }}
                disabled={deleteLoader}
              >
                Cancel
              </Button>
            </Group>
          </Box>
        </Dialog>
      )}
    </Box>
  )
}

export default Document
