import { useEffect, useState } from 'react'
import { useForm } from '@mantine/form'
import {
  Modal,
  Button,
  Text,
  Box,
  Switch,
  Checkbox,
  FileInput,
  TextInput,
  Group,
  ActionIcon,
} from '@mantine/core'
import { IconPlus, IconTrash } from '@tabler/icons-react'

import { create } from '@/rtk/helpers/CRUD'
import { createDocument } from '@/api/Admin'
import { getHeaderInfo } from '@/rtk/helpers/tokenCreator'
import { notifications } from '@mantine/notifications'

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

const ModalAddDocument = ({ opened, close, getAllData }: MProps) => {
  const [loadingSubmit, setLoadingSubmit] = useState(false)

  const form = useForm({
    initialValues: {
      type: 'file',
      files: [] as { title: string; file: File }[],
      links: [] as { title: string; uri: string }[],
      is_active: true,
    },
  })

  useEffect(() => {
    form.reset()
  }, [])

  const handleCreate = async (values: any) => {
    try {
      if (values.type === 'file' && values.files.length === 0) {
        notifications.show({
          title: 'Error',
          message: 'No files uploaded!!!',
          color: 'red',
        })
        return
      }

      if (values.type === 'link' && values.links.length === 0) {
        notifications.show({
          title: 'Error',
          message: 'No links provided!!!',
          color: 'red',
        })
        return
      }

      setLoadingSubmit(true)
      const header = await getHeaderInfo()
      const formData = new FormData()
      header.headers['Content-Type'] = 'multipart/form-data'

      formData.append('type', values.type)
      formData.append('is_active', values.is_active ? '1' : '0')

      if (values.type === 'file') {
        values.files.forEach((item: any, index: number) => {
          formData.append(`files[${index}][title]`, item.title)
          formData.append(`files[${index}][file]`, item.file)
        })
      } else {
        values.links.forEach((item: any, index: number) => {
          formData.append(`links[${index}][title]`, item.title)
          formData.append(`links[${index}][uri]`, item.uri)
        })
      }

      const res = await create(createDocument, formData, getAllData, header)
      if (res === true) {
        resetForm()
      }
    } catch (error) {
      console.error(error)
    } finally {
      setLoadingSubmit(false)
    }
  }

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

  return (
    <Modal
      opened={opened}
      onClose={resetForm}
      size="lg"
      title={
        <Text fw={700} fz={'lg'}>
          Add Document
        </Text>
      }
    >
      <form onSubmit={form.onSubmit(handleCreate)}>
        <Switch
          style={{ width: 'fit-content' }}
          label={form.values.type === 'file' ? 'Upload files' : 'Enter links'}
          checked={form.values.type === 'file'}
          onChange={(event) =>
            form.setFieldValue(
              'type',
              event.currentTarget.checked ? 'file' : 'link',
            )
          }
          mb={'md'}
          disabled={loadingSubmit}
        />

        {form.values.type === 'file' ? (
          <Box>
            <FileInput
              accept=".doc,.docx,.xls,.xlsx,.pdf"
              label="Upload Doc, Excel, PDF files"
              multiple
              mb="md"
              value={form.values.files.map((file) => file.file)}
              onChange={(files) => {
                if (files) {
                  const newFiles = files.map((file) => ({
                    title: file.name.split('.')[0],
                    file,
                  }))
                  form.setFieldValue('files', newFiles)
                }
              }}
              disabled={loadingSubmit}
              required
            />

            {form.values.files.map((item, index) => (
              <Group key={index} mb={'md'}>
                <TextInput
                  w="50%"
                  label="Title"
                  value={form.values.files[index].title}
                  onChange={(event) =>
                    form.setFieldValue(
                      `files.${index}.title`,
                      event.currentTarget.value,
                    )
                  }
                  maxLength={255}
                  disabled={loadingSubmit}
                  required
                />
                <Text mt={24} w="30%">
                  {item.file?.name}
                </Text>
              </Group>
            ))}
          </Box>
        ) : (
          <Box>
            {form.values.links.map((_, index) => (
              <Group key={index} mb={'md'}>
                <TextInput
                  w="35%"
                  label="Title"
                  value={form.values.links[index].title}
                  onChange={(event) =>
                    form.setFieldValue(
                      `links.${index}.title`,
                      event.currentTarget.value,
                    )
                  }
                  maxLength={255}
                  disabled={loadingSubmit}
                  required
                />
                <TextInput
                  w="50%"
                  label="URL"
                  value={form.values.links[index].uri}
                  onChange={(event) =>
                    form.setFieldValue(
                      `links.${index}.uri`,
                      event.currentTarget.value,
                    )
                  }
                  disabled={loadingSubmit}
                  required
                />
                <ActionIcon
                  color="red"
                  variant="light"
                  onClick={() =>
                    form.setFieldValue(
                      'links',
                      form.values.links.filter((_, i) => i !== index),
                    )
                  }
                  disabled={loadingSubmit}
                  mt={24}
                >
                  <IconTrash size={16} />
                </ActionIcon>
              </Group>
            ))}

            <Button
              leftSection={<IconPlus size={16} />}
              variant="light"
              onClick={() =>
                form.setFieldValue('links', [
                  ...form.values.links,
                  { title: '', uri: '' },
                ])
              }
              disabled={loadingSubmit}
              mb="md"
            >
              Add Link
            </Button>
          </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}>
            Create
          </Button>
        </Box>
      </form>
    </Modal>
  )
}

export default ModalAddDocument
