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

import { Button } from '~/components/ui/button'
import { Input } from '~/components/ui/input'
import { InputFile } from '~/components/ui/input-file'
import { useAdminContext } from '~/contexts/admin'
import type { loader } from '~/routes/_admin.lg-admin'

export const profileSchema = z.object({
  name: z.string().min(1, 'Wajib diisi'),
  email: z.string().email('Email tidak valid'),
  profile_picture: z.string().url({
    message: 'URL tidak valid',
  }),
})

export type TProfileSchema = z.infer<typeof profileSchema>

export const DialogProfile = () => {
  const { editProfile, setEditProfile } = useAdminContext()
  const loaderData = useRouteLoaderData<typeof loader>('routes/_admin.lg-admin')
  const { staffData } = loaderData || {}
  const fetcher = useFetcher()

  const formMethods = useRemixForm<TProfileSchema>({
    mode: 'onSubmit',
    fetcher,
    resolver: zodResolver(profileSchema),
    values: {
      name: staffData?.name || '',
      email: staffData?.email || '',
      profile_picture: staffData?.profile_picture || '',
    },
  })

  const { handleSubmit } = formMethods

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

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

  return (
    <Dialog
      open={editProfile}
      onClose={() => {
        if (fetcher.state === 'idle') {
          setEditProfile(false)
        }
      }}
      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="w-full 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"
        >
          <DialogTitle
            as="h3"
            className="text-xl font-bold"
          >
            Update Profile
          </DialogTitle>
          <RemixFormProvider {...formMethods}>
            <fetcher.Form
              method="post"
              onSubmit={handleSubmit}
              className="space-y-4"
              action="/actions/admin/profile"
            >
              <Input
                name="name"
                id="name"
                label="Nama"
                placeholder="Enter your name"
              />
              <Input
                id="email"
                label="Email"
                placeholder="Contoh: legal@legalgo.id"
                name="email"
              />
              <InputFile
                name="profile_picture"
                id="profile_picture"
                label="Gambar Profil"
                placeholder="Unggah gambar profil Anda"
                category="profile_picture"
              />
              <Button
                disabled={fetcher.state !== 'idle'}
                isLoading={fetcher.state !== 'idle'}
                type="submit"
                className="w-full rounded-md py-2"
              >
                Simpan
              </Button>
            </fetcher.Form>
          </RemixFormProvider>
        </DialogPanel>
      </div>
    </Dialog>
  )
}
