import {
  deleteFile,
  getAllFilesInProfiles,
  updateProfileFolder,
} from '@/api/Admin'
import { Xdelete } from '@/rtk/helpers/CRUD'
import { get } from '@/rtk/helpers/apiService'
import { getAccessToken } from '@/rtk/localStorage'
import {
  Box,
  Button,
  FileInput,
  Group,
  Modal,
  RenderTreeNodePayload,
  Stack,
  Text,
  TextInput,
  Tooltip,
  Tree,
} from '@mantine/core'
import {
  IconFileTypeDocx,
  IconFileTypePdf,
  IconFolder,
  IconFolderOpen,
  IconFolderX,
  IconListCheck,
  IconPhoto,
} from '@tabler/icons-react'
import axios from 'axios'
import { useEffect, useState } from 'react'
import classes from './AllProfiles.module.css'

interface FileIconProps {
  name: string
  isFolder: boolean
  expanded: boolean
}

type TFileProfile = {
  label: string
  type: string
  value: string
  children?: TFileProfile[]
}

const AllProfiles = () => {
  const [treeData, setTreeData] = useState([])
  const [cv, setCv] = useState<File>()
  const [idCard, setIdCard] = useState<File>()
  const [transcript, setTranscript] = useState<File>()
  const [universityDiploma, setUniversityDiploma] = useState<File>()
  const [otherFiles, setOtherFiles] = useState([{ file: null, type: '' }])
  const [data, setData] = useState<TFileProfile[]>([])
  const [currentName, setCurrentName] = useState<string>('')
  const [openedProfile, setOpenedProfile] = useState(false)
  function FileIcon({ name, isFolder, expanded }: FileIconProps) {
    if (name.endsWith('.pdf')) {
      return <IconFileTypePdf size={14} />
    }

    if (name.endsWith('.doc') || name.endsWith('.docx')) {
      return <IconFileTypeDocx size={14} />
    }

    if (
      name.endsWith('.jpg') ||
      name.endsWith('.png') ||
      name.endsWith('.jpeg') ||
      name.endsWith('.webp')
    ) {
      return <IconPhoto size={14} />
    }

    if (isFolder) {
      return expanded ? (
        <IconFolderOpen
          color="var(--mantine-color-yellow-9)"
          size={14}
          stroke={2.5}
        />
      ) : (
        <IconFolder
          color="var(--mantine-color-yellow-9)"
          size={14}
          stroke={2.5}
        />
      )
    }

    return (
      <IconFolderX color="var(--mantine-color-red-9)" size={14} stroke={2.5} />
    )
  }

  function Leaf({
    node,
    expanded,
    hasChildren,
    elementProps,
  }: RenderTreeNodePayload) {
    return (
      <Group gap={5} {...elementProps}>
        {!node.children ? (
          <a href={node.value} target="_blank">
            <FileIcon
              name={node.value}
              isFolder={hasChildren}
              expanded={expanded}
            />
            <span>{node.label}</span>
          </a>
        ) : (
          <>
            <FileIcon
              name={node.value}
              isFolder={hasChildren}
              expanded={expanded}
            />
            <span>{node.label}</span>
            <Tooltip label="Upload">
              <IconListCheck
                color="green"
                width={15}
                height={15}
                style={{
                  display: node.label !== 'others' ? 'block' : 'none',
                  cursor: 'pointer',
                  zIndex: 100000,
                }}
                onClick={() => {
                  setCurrentName(node.label!.toString())
                  setOpenedProfile(true)
                }}
              />
            </Tooltip>
          </>
        )}
      </Group>
    )
  }

  const handleOtherFileChange = (
    index: number,
    field: string,
    value: File | string,
  ) => {
    const updatedFiles: any = [...otherFiles]
    updatedFiles[index][field] = value
    setOtherFiles(updatedFiles)
  }

  const addOtherFileInput = () => {
    setOtherFiles([...otherFiles, { file: null, type: '' }])
  }

  const handleSubmit = async (e: any) => {
    e.preventDefault()
    const formData = new FormData()

    // Append each selected file to FormData
    for (let i = 0; i < otherFiles.length; i++) {
      if (otherFiles[i].file !== null && otherFiles[i].type !== '') {
        formData.append(
          'files[]',
          handleChangeFileName(otherFiles[i].file!, `__${otherFiles[i].type}`)!,
        )
      }
    }

    if (cv) {
      formData.append('files[]', cv)
    }

    if (idCard) {
      formData.append('files[]', idCard)
    }

    if (transcript) {
      formData.append('files[]', transcript)
    }

    if (universityDiploma) {
      formData.append('files[]', universityDiploma)
    }

    formData.append('name', currentName)

    const token = await getAccessToken()
    try {
      const response = await axios.post(updateProfileFolder, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: `Bearer ${token}`,
        },
      })

      if (response.status === 200) {
        getAllFile()
        getTree()
        setOtherFiles([])
      }
    } catch (error) {
      console.error('Error uploading files', error)
    }
  }

  const getAllFile = async () => {
    try {
      const res = await get(getAllFilesInProfiles, {
        root_folder: '/storage/profiles/' + currentName,
      })
      if (res.status === true) {
        setData(res.data)
      }
    } catch (error) {
      console.log(error)
    }
  }

  const removeFile = async (url: string) => {
    try {
      await Xdelete(deleteFile, { file_url: url }, getAllFile)
      getTree()
    } catch (error) {
      console.log(error)
    }
  }
  const getTree = async () => {
    try {
      const res = await get(getAllFilesInProfiles, {
        root_folder: '/storage/profiles',
      })
      if (res.status === true) {
        setTreeData(res.data)
      }
    } catch (error) {
      console.log(error)
    }
  }

  const handleChangeFileName = (e: File, newName: string) => {
    const originalFile = e // Get the original file
    const extend = originalFile.name.split('.')[1]
    if (originalFile) {
      const newFileName = `${newName}.${extend}` // Create new file name
      const newFile = new File([originalFile], newFileName, {
        type: originalFile.type,
      }) // Create new file object

      return newFile // Save the new file object for further processing
    }
  }

  const checkFileExist = (nameField: string) => {
    const file = data.find((f) => f.label.includes(nameField))
    return file
  }

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

  useEffect(() => {
    getAllFile()
  }, [currentName])
  return (
    <div>
      <div className={classes.title}>
        <h3>
          <Text>Admin/</Text>
          Profiles
        </h3>
      </div>
      <Box ml={'lg'}>
        <Tree
          classNames={classes}
          selectOnClick
          clearSelectionOnOutsideClick
          data={treeData}
          renderNode={(payload) => <Leaf {...payload} />}
        />
        <Modal
          size={'lg'}
          opened={openedProfile}
          onClose={() => {
            setOpenedProfile(false)
          }}
        >
          <Box>
            <form onSubmit={handleSubmit}>
              <Stack>
                <Box
                  style={{ display: checkFileExist('cv') ? 'flex' : 'none' }}
                >
                  <Text>CV</Text>
                  <a href={checkFileExist('cv')?.value} target="_blank">
                    <Text>{`: ${checkFileExist('cv')?.label}`}</Text>
                  </a>
                  <Button
                    variant="outline"
                    size="xs"
                    color="red"
                    ml={'sm'}
                    onClick={() => {
                      removeFile(checkFileExist('cv')?.value!)
                    }}
                  >
                    Delete
                  </Button>
                </Box>
                <FileInput
                  label={'CV'}
                  placeholder="Tải lên CV"
                  style={{ display: checkFileExist('cv') ? 'none' : 'block' }}
                  onChange={(e) => {
                    0
                    setCv(handleChangeFileName(e!, 'cv'))
                  }}
                  accept=".pdf,.doc,.docx"
                />
                <Box
                  style={{
                    display: checkFileExist('idCard') ? 'flex' : 'none',
                  }}
                >
                  <Text>CCCD</Text>
                  <a href={checkFileExist('idCard')?.value} target="_blank">
                    <Text>{`: ${checkFileExist('idCard')?.label}`}</Text>
                  </a>
                  <Button
                    variant="outline"
                    size="xs"
                    color="red"
                    ml={'sm'}
                    onClick={() => {
                      removeFile(checkFileExist('idCard')?.value!)
                    }}
                  >
                    Delete
                  </Button>
                </Box>

                <FileInput
                  label="CCCD"
                  style={{
                    display: checkFileExist('idCard') ? 'none' : 'block',
                  }}
                  placeholder="Tải lên CCCD"
                  onChange={(e) => {
                    setIdCard(handleChangeFileName(e!, 'idCard'))
                  }}
                  accept=".jpg,.jpeg,.png,.pdf"
                />
                <Box
                  style={{
                    display: checkFileExist('transcript') ? 'flex' : 'none',
                  }}
                >
                  <Text>Bảng điểm</Text>
                  <a href={checkFileExist('transcript')?.value} target="_blank">
                    <Text>{`: ${checkFileExist('transcript')?.label}`}</Text>
                  </a>
                  <Button
                    variant="outline"
                    size="xs"
                    color="red"
                    ml={'sm'}
                    onClick={() => {
                      removeFile(checkFileExist('transcript')?.value!)
                    }}
                  >
                    Delete
                  </Button>
                </Box>
                <FileInput
                  label="Bảng điểm"
                  style={{
                    display: checkFileExist('transcript') ? 'none' : 'block',
                  }}
                  placeholder="Tải lên bảng điểm"
                  onChange={(e) => {
                    setTranscript(handleChangeFileName(e!, 'transcript'))
                  }}
                  accept=".pdf"
                />

                <Box
                  style={{
                    display: checkFileExist('universityDiploma')
                      ? 'flex'
                      : 'none',
                  }}
                >
                  <Text>Bằng đại học</Text>
                  <a
                    href={checkFileExist('universityDiploma')?.value}
                    target="_blank"
                  >
                    <Text>{`: ${
                      checkFileExist('universityDiploma')?.label
                    }`}</Text>
                  </a>
                  <Button
                    variant="outline"
                    size="xs"
                    color="red"
                    ml={'sm'}
                    onClick={() => {
                      removeFile(checkFileExist('universityDiploma')?.value!)
                    }}
                  >
                    Delete
                  </Button>
                </Box>
                <FileInput
                  label="Bằng đại học"
                  style={{
                    display: checkFileExist('universityDiploma')
                      ? 'none'
                      : 'block',
                  }}
                  placeholder="Tải lên bằng đại học"
                  onChange={(e) => {
                    setUniversityDiploma(
                      handleChangeFileName(e!, 'universityDiploma'),
                    )
                  }}
                  accept=".pdf,.jpg,.jpeg,.png"
                />

                <Text>Danh sách file khác:</Text>
                <Box>
                  {data
                    .find((f) => f.label === 'others')
                    ?.children?.map((c, index) => {
                      return (
                        <Box
                          key={index}
                          style={{
                            display: 'flex',
                            marginBottom: '5px',
                          }}
                        >
                          <a href={c?.value} target="_blank">
                            <Text>{`${c?.label}`}</Text>
                          </a>
                          <Button
                            variant="outline"
                            size="xs"
                            color="red"
                            ml={'sm'}
                            onClick={() => {
                              removeFile(c?.value!)
                            }}
                          >
                            Delete
                          </Button>
                        </Box>
                      )
                    })}
                </Box>
                {otherFiles.map((fileInput, index) => (
                  <Group key={index}>
                    <FileInput
                      placeholder="Chọn file"
                      onChange={(file) =>
                        handleOtherFileChange(index, 'file', file!)
                      }
                      w={'30%'}
                    />
                    <TextInput
                      placeholder="Nhập tên file (không cần phần mở rộng)"
                      value={fileInput.type}
                      w={'65%'}
                      onChange={(e) =>
                        handleOtherFileChange(
                          index,
                          'type',
                          e.currentTarget.value,
                        )
                      }
                    />
                  </Group>
                ))}
                <Button type="button" onClick={addOtherFileInput}>
                  Thêm file khác
                </Button>

                <Button type="submit" color="blue">
                  Save
                </Button>
              </Stack>
            </form>
          </Box>
        </Modal>
      </Box>
    </div>
  )
}

export default AllProfiles
