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

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 default function FormSubscription() {
  const { setIsSubscribeOpen, setIsSuccessOpen } = useNewsContext()
  const fetcher = useFetcher()
  const [error, setError] = useState<string>()
  const loaderData = useRouteLoaderData<typeof loader>('routes/_news')
  const { subscriptionsData: subscriptions } = loaderData || {}

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

  const { handleSubmit } = formMethods

  useEffect(() => {
    if (!fetcher.data?.success) {
      setError(fetcher.data?.message)
      return
    }

    setError(undefined)
    setIsSubscribeOpen(false)
    setIsSuccessOpen('payment')
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetcher])

  return (
    <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="Subscription"
            placeholder="Pilih Subscription"
            options={subscriptions}
          />

          {error && (
            <div className="text-sm text-red-500 capitalize">{error}</div>
          )}

          <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>
  )
}
