import { zodResolver } from '@hookform/resolvers/zod'
import { useEffect } from 'react'
import toast from 'react-hot-toast'
import { useFetcher, useNavigate } from 'react-router'
import { RemixFormProvider, useRemixForm } from 'remix-hook-form'
import { z } from 'zod'

import type { TAdResponse } from '~/apis/common/get-ads'
import { Button } from '~/components/ui/button'
import { Input } from '~/components/ui/input'
import { InputFile } from '~/components/ui/input-file'
import { TitleDashboard } from '~/components/ui/title-dashboard'
import { dateInput } from '~/utils/formatter'

export const adsSchema = z.object({
  id: z.string().optional(),
  image: z.string().url({
    message: 'Gambar must be a valid URL',
  }),
  url: z.string().url({
    message: 'URL must be valid',
  }),
  start_date: z.string().min(1, {
    message: 'Tanggal mulai is required',
  }),
  end_date: z.string().min(1, {
    message: 'Tanggal berakhir is required',
  }),
})
export type TAdsSchema = z.infer<typeof adsSchema>
type TProperties = {
  adData?: TAdResponse
}

export const FormAdvertisementsPage = (properties: TProperties) => {
  const { adData } = properties || {}
  const fetcher = useFetcher()
  const navigate = useNavigate()
  const formMethods = useRemixForm<TAdsSchema>({
    mode: 'onSubmit',
    fetcher,
    resolver: zodResolver(adsSchema),
    values: {
      id: adData?.id || undefined,
      image: adData?.image_url || '',
      url: adData?.url || '',
      start_date: adData?.start_date ? dateInput(adData.start_date) : '',
      end_date: adData?.end_date ? dateInput(adData.end_date) : '',
    },
  })

  const { handleSubmit } = formMethods

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

    if (fetcher.data?.success) {
      toast.success(`Banner iklan berhasil ${adData ? 'diupdate' : 'dibuat'}!`)
      navigate('/lg-admin/advertisements')
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetcher.data])

  return (
    <div className="relative">
      <TitleDashboard title={`${adData ? 'Update' : 'Buat'} Banner Iklan`} />
      <div>
        <RemixFormProvider {...formMethods}>
          <fetcher.Form
            method="post"
            onSubmit={handleSubmit}
            action={`/actions/admin/advertisements/${adData ? 'update' : 'create'}`}
            className="space-y-4"
          >
            <div className="flex items-end justify-between gap-4">
              <InputFile
                id="image"
                label="Gambar"
                placeholder="Masukkan Url Gambar"
                name="image"
                className="border-0 bg-white shadow read-only:bg-gray-100 focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none disabled:bg-gray-100"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="flex-1"
                category="ads"
              />
              <Input
                id="url"
                label="Link"
                placeholder="Masukkan Url Link"
                name="url"
                className="border-0 bg-white shadow read-only:bg-gray-100 focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none disabled:bg-gray-100"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="flex-1"
              />
              <Button
                isLoading={fetcher.state !== 'idle'}
                disabled={fetcher.state !== 'idle'}
                type="submit"
                size="lg"
                className="text-md h-[42px] rounded-md"
              >
                Save
              </Button>
            </div>
            <div className="flex items-end justify-between gap-4">
              <Input
                id="start_date"
                label="Tanggal Mulai"
                type="date"
                name="start_date"
                className="border-0 bg-white shadow read-only:bg-gray-100 focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none disabled:bg-gray-100"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="flex-1"
              />
              <Input
                id="end_date"
                label="Tanggal Berakhir"
                type="date"
                name="end_date"
                className="border-0 bg-white shadow read-only:bg-gray-100 focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none disabled:bg-gray-100"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="flex-1"
              />
            </div>
          </fetcher.Form>
        </RemixFormProvider>
      </div>
    </div>
  )
}
