import { Dialog, DialogBackdrop, DialogPanel, Input } from '@headlessui/react'
import { zodResolver } from '@hookform/resolvers/zod'
import { useEffect, type ChangeEvent } from 'react'
import toast from 'react-hot-toast'
import { useFetcher } from 'react-router'
import { RemixFormProvider, useRemixForm } from 'remix-hook-form'
import { z } from 'zod'

import { Button } from '~/components/ui/button'
import { uploadCategorySchema, useAdminContext } from '~/contexts/admin'

export const uploadSchema = z.object({
  file: z.instanceof(File),
  category: uploadCategorySchema,
})

export type TUploadSchema = z.infer<typeof uploadSchema>

export const DialogUpload = () => {
  const { isUploadOpen, setUploadedFile, setIsUploadOpen } = useAdminContext()
  const fetcher = useFetcher()
  const maxFileSize = 10 * 1024 // 10MB

  const formMethods = useRemixForm<TUploadSchema>({
    mode: 'onSubmit',
    fetcher,
    resolver: zodResolver(uploadSchema),
  })

  const { handleSubmit, register, setValue } = formMethods

  useEffect(() => {
    if (!fetcher.data?.success && fetcher.data?.message) {
      toast.error(fetcher.data.message)
    }

    if (fetcher.data?.success) {
      setUploadedFile(fetcher.data.uploadData.data.file_url)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetcher.data])

  const handleChange = async function (event: ChangeEvent<HTMLInputElement>) {
    event.preventDefault()
    if (event.target.files && event.target.files[0]) {
      const files: File[] = [...event.target.files]

      onChange(files, event)
    }
  }

  const onChange = async function (
    files: File[],
    event: ChangeEvent<HTMLInputElement>,
  ) {
    const file = files[0]
    const img = new Image()

    if (!file.type.startsWith('image/')) {
      toast.error('Please upload an image file.')
      return
    }

    if (file.size > maxFileSize * 1024) {
      toast.error(`File size is too big!`)
      return
    }

    img.addEventListener('load', () => {
      handleFiles(event)
    })

    img.src = URL.createObjectURL(file)
  }

  const handleFiles = (event: ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files
    if (files && files.length > 0) {
      const file = files[0]
      setValue('file', file)
    }
  }

  return (
    <Dialog
      open={!!isUploadOpen}
      onClose={() => {
        if (fetcher.state === 'idle') {
          setIsUploadOpen(undefined)
        }
      }}
      className="relative z-50"
      transition
    >
      <DialogBackdrop
        className="fixed inset-0 bg-black/50 duration-300 ease-out data-[closed]:opacity-0"
        transition
      />
      <div className="fixed inset-0 flex w-screen justify-center overflow-y-auto p-0 max-sm:bg-white sm:items-center sm:p-4">
        <DialogPanel
          transition
          className="max-w-lg space-y-6 rounded-lg bg-white p-8 duration-300 ease-out data-[closed]:scale-95 data-[closed]:opacity-0 sm:shadow-lg"
        >
          <RemixFormProvider {...formMethods}>
            <fetcher.Form
              method="post"
              onSubmit={handleSubmit}
              className="space-y-4"
              action="/actions/admin/upload"
              encType="multipart/form-data"
            >
              <Input
                type="file"
                id="input-file-upload"
                accept="image/*"
                className="h-[42px] w-full cursor-pointer rounded-md border border-[#DFDFDF] p-2"
                onChange={handleChange}
              />
              <input
                type="hidden"
                id="input-file-upload-type"
                value={isUploadOpen}
                {...register('category')}
              />
              <Button
                disabled={fetcher.state !== 'idle'}
                isLoading={fetcher.state !== 'idle'}
                type="submit"
                className="w-full rounded-md py-2"
              >
                Upload
              </Button>
            </fetcher.Form>
          </RemixFormProvider>
        </DialogPanel>
      </div>
    </Dialog>
  )
}
