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 { DialogNews } from '~/components/dialog/news'
import { Button } from '~/components/ui/button'
import { Combobox } from '~/components/ui/combobox'
import { useNewsContext } from '~/contexts/news'
import type { loader } from '~/routes/_news'

export const subscribeSchema = z.object({
  subscribe_plan: z
    .object({
      id: z.string(),
      code: z.string(),
      name: z.string(),
    })
    .optional()
    .nullable()
    .refine((data) => !!data, {
      message: 'Please select a subscription',
    }),
})

export type TSubscribeSchema = z.infer<typeof subscribeSchema>

export const DialogSubscribePlan = () => {
  const { setIsSubscribeOpen, setIsSuccessOpen, isSubscribeOpen } =
    useNewsContext()
  const fetcher = useFetcher()
  const loaderData = useRouteLoaderData<typeof loader>('routes/_news')
  const { subscribePlanData: subscribePlan } = loaderData || {}

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

  const { handleSubmit } = formMethods

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

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

  return (
    <DialogNews
      isOpen={isSubscribeOpen}
      onClose={() => {
        if (fetcher.state === 'idle') {
          setIsSubscribeOpen(false)
        }
      }}
      description="Selamat Datang, silakan Pilih Subscribe Plan Anda untuk melanjutkan!"
    >
      <div className="flex flex-col items-center justify-center">
        <RemixFormProvider {...formMethods}>
          <fetcher.Form
            method="post"
            onSubmit={handleSubmit}
            className="w-full max-w-md"
            action="/actions/subscribe"
          >
            <Combobox
              id="subscribe_plan"
              name="subscribe_plan"
              label="Subscribe Plan"
              placeholder="Pilih Subscribe Plan"
              options={subscribePlan}
            />

            <Button
              isLoading={fetcher.state !== 'idle'}
              disabled={fetcher.state !== 'idle'}
              type="submit"
              className="mt-5 w-full rounded-md py-2"
            >
              Lanjutkan
            </Button>
          </fetcher.Form>
        </RemixFormProvider>
      </div>
    </DialogNews>
  )
}
