import { useEffect, useState } from 'react'
import { useForm } from '@mantine/form'
import {
  Modal,
  Button,
  Text,
  Box,
  Checkbox,
  FileInput,
  Badge,
  TextInput,
  Group,
} from '@mantine/core'

import { update } from '@/rtk/helpers/CRUD'
import { updateDocument } from '@/api/Admin'
import { getHeaderInfo } from '@/rtk/helpers/tokenCreator'
import {
  IconFileTypeDoc,
  IconFileTypePdf,
  IconFileTypeXls,
} from '@tabler/icons-react'
import ModalFileDocument from './ModalFileDocument'
import { useDisclosure } from '@mantine/hooks'

type MProps = {
  opened: boolean
  close: () => void
  selectDataRow: any
  setSelectDataRow: any
  getAllData: () => void
}

const ModalEditDocument = ({
  opened,
  close,
  selectDataRow,
  setSelectDataRow,
  getAllData,
}: MProps) => {
  const [loadingSubmit, setLoadingSubmit] = useState(false)
  const [selectDataFileRow, setSelectDataFileRow] = useState<any>({})

  const [openedModalFile, { open: openModalFile, close: closeModalFile }] =
    useDisclosure(false)

  const form = useForm({
    initialValues: {
      title: '',
      type: true,
      file: null as File | null,
      uri: '',
      is_active: true,
    },
  })

  useEffect(() => {
    form.setValues({
      title: selectDataRow?.title || '',
      type: selectDataRow?.type === 'file',
      uri: selectDataRow?.uri || '',
      is_active: selectDataRow?.is_active || true,
    })
  }, [selectDataRow])

  const handleUpdate = async (data: any) => {
    try {
      setLoadingSubmit(true)

      let formData: any = {}
      const header = await getHeaderInfo()

      if (data.type) {
        header.headers['Content-Type'] = 'multipart/form-data'
        const tmpFormData = new FormData()

        tmpFormData.append('title', data.title)
        tmpFormData.append('type', 'file')
        tmpFormData.append('is_active', data.is_active ? '1' : '0')
        tmpFormData.append('existing_file', data.uri)

        if (data.file) {
          tmpFormData.append('file', data.file)
        }

        formData = tmpFormData
      } else {
        formData = {
          title: data.title,
          type: 'link',
          uri: data.uri,
          is_active: data.is_active ? '1' : '0',
        }
      }

      const res = await update(
        updateDocument + `?id=${selectDataRow?.id}`,
        formData,
        getAllData,
        header,
      )
      if (res === true) {
        resetForm()
      }
    } catch (error: any) {
      console.error(error)
    } finally {
      setLoadingSubmit(false)
    }
  }

  const getFileTypeIcon = (uri: string) => {
    if (!uri) return null

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

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

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

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

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

  const resetForm = () => {
    close()
    form.reset()
    setSelectDataRow({})
  }

  return (
    <Modal
      opened={opened}
      onClose={resetForm}
      size="lg"
      title={
        <Text fw={700} fz={'lg'}>
          Update Document
        </Text>
      }
    >
      <form
        onSubmit={form.onSubmit((values) => {
          handleUpdate(values)
        })}
      >
        {form.values.type ? (
          <Badge tt="initial" color="orange" mb="md">
            Files
          </Badge>
        ) : (
          <Badge tt="initial" mb="md">
            Links
          </Badge>
        )}

        {form.values.type ? (
          <Box>
            <TextInput
              label="Title"
              key={'title'}
              {...form.getInputProps('title')}
              maxLength={255}
              disabled={loadingSubmit}
              required
              mb={'md'}
            />
            <FileInput
              accept=".doc,.docx,.xls,.xlsx,.pdf"
              label="Upload Doc, Excel, PDF file"
              value={form.values.file}
              onChange={(file) => form.setFieldValue('file', file || null)}
              disabled={loadingSubmit}
              mb={'md'}
            />

            {form.values.file ? (
              ''
            ) : (
              <Group
                w="fit-content"
                style={{ cursor: 'pointer' }}
                mb={'md'}
                title={`File ${form.values.uri
                  .split('.')
                  .pop()
                  ?.toLowerCase()} detail`}
              >
                {getFileTypeIcon(form.values.uri)}

                <Text>.{form.values.uri.split('.').pop()?.toLowerCase()}</Text>
              </Group>
            )}
          </Box>
        ) : (
          <Box>
            <TextInput
              label="Title"
              key={'title'}
              {...form.getInputProps('title')}
              maxLength={255}
              disabled={loadingSubmit}
              required
              mb={'md'}
            />
            <TextInput
              label="Enter URI"
              key={'uri'}
              {...form.getInputProps('uri')}
              disabled={loadingSubmit}
              required
              mb={'md'}
            />
          </Box>
        )}

        <Checkbox
          label="Is Active"
          mb={'md'}
          checked={form.values.is_active}
          onChange={(event) =>
            form.setFieldValue('is_active', event.currentTarget.checked)
          }
          disabled={loadingSubmit}
        />

        <Box ta="center" mt="lg">
          <Button color="green" type="submit" loading={loadingSubmit}>
            Update
          </Button>
        </Box>
      </form>

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

export default ModalEditDocument
