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

import { Button } from '~/components/ui/button'
import { Select } from '~/components/ui/select'
import type { loader } from '~/routes/_layout'

export const subscribeSchema = z
  .object({
    email: z.string().email('Email tidak valid'),
    password: z.string().min(6, 'Kata sandi minimal 6 karakter'),
    rePassword: z.string().min(6, 'Kata sandi minimal 6 karakter'),
    phone: z.string().min(10, 'No telepon tidak valid'),
    subscribe_plan: z.string().min(1, 'Pilih salah satu subscription'),
  })
  .refine((field) => field.password === field.rePassword, {
    message: 'Kata sandi tidak sama',
    path: ['rePassword'],
  })

export type TSubscribeSchema = z.infer<typeof subscribeSchema>

export default function FormSubscription() {
  const fetcher = useFetcher()
  const loaderData = useRouteLoaderData<typeof loader>('routes/_layout')
  const subscriptions = loaderData?.subscriptionsData

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

  const { handleSubmit } = formMethods

  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/register"
        >
          <Select
            id="subscribe_plan"
            name="subscribe_plan"
            label="Subscription"
            placeholder="Pilih Subscription"
            options={subscriptions}
          />

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