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/_layout'

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 [disabled, setDisabled] = useState(false)
  const loaderData = useRouteLoaderData<typeof loader>('routes/_layout')
  const subscriptions = loaderData?.subscriptionsData

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

  const { handleSubmit } = formMethods

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

    setDisabled(true)
    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
            disabled={disabled}
            type="submit"
            className="mt-5 w-full rounded-md bg-[#2E2F7C] py-2 text-white transition hover:bg-blue-800"
          >
            Lanjutkan
          </Button>
        </fetcher.Form>
      </RemixFormProvider>
    </div>
  )
}
