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

import { Button } from '~/components/ui/button'
import { Input } from '~/components/ui/input'
import { TitleDashboard } from '~/components/ui/title-dashboard'
import { urlFriendlyCode } from '~/utils/formatter'

export const createSubscribePlanSchema = z.object({
  id: z.string().optional(),
  name: z.string().min(3, 'Nama minimal 3 karakter'),
  code: z.string(),
})
export type TSubscribePlanSchema = z.infer<typeof createSubscribePlanSchema>
type TProperties = {
  subscribePlanData?: TSubscribePlanSchema
}

export const FormSubscribePlanPage = (properties: TProperties) => {
  const { subscribePlanData } = properties || {}
  const fetcher = useFetcher()
  const navigate = useNavigate()
  const formMethods = useRemixForm<TSubscribePlanSchema>({
    mode: 'onSubmit',
    fetcher,
    resolver: zodResolver(createSubscribePlanSchema),
    values: {
      id: subscribePlanData?.id || undefined,
      code: subscribePlanData?.code || '',
      name: subscribePlanData?.name || '',
    },
  })
  const [error, setError] = useState<string>()
  const [disabled, setDisabled] = useState(false)

  const { handleSubmit, watch, setValue } = formMethods
  const watchName = watch('name')

  useEffect(() => {
    if (!fetcher.data?.success) {
      setError(fetcher.data?.message)
      setDisabled(false)
      return
    }
    navigate('/lg-admin/subscribe-plan')
    setDisabled(true)
    setError(undefined)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetcher])

  useEffect(() => {
    setValue('code', urlFriendlyCode(watchName))
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [watchName])

  return (
    <div className="relative">
      <TitleDashboard
        title={`${subscribePlanData ? 'Update' : 'Buat'} Subscribe Plan`}
      />
      <div>
        <RemixFormProvider {...formMethods}>
          <fetcher.Form
            method="post"
            onSubmit={handleSubmit}
            action={`/actions/admin/subscribe-plan/${subscribePlanData ? 'update' : 'create'}`}
            className="space-y-4"
          >
            {error && (
              <div className="text-sm text-red-500 capitalize">{error}</div>
            )}
            <div className="flex items-end justify-between gap-4">
              <Input
                id="name"
                label="Subscribe Plan"
                placeholder="Masukkan Nama Subscribe Plan"
                name="name"
                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="code"
                label="Kode"
                placeholder="Masukkan Kode Subscribe Plan"
                readOnly
                name="code"
                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
                disabled={disabled}
                type="submit"
                size="lg"
                className="text-md h-[42px] rounded-md"
              >
                Save
              </Button>
            </div>
          </fetcher.Form>
        </RemixFormProvider>
      </div>
    </div>
  )
}
