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

import type { TSubscribePlanResponse } from '~/apis/common/get-subscribe-plan'
import { Button } from '~/components/ui/button'
import { Input } from '~/components/ui/input'
import { Select } from '~/components/ui/select'
import { TitleDashboard } from '~/components/ui/title-dashboard'
import { urlFriendlyCode } from '~/utils/formatter'

export const subscribePlanSchema = z.object({
  id: z.string().optional(),
  name: z.string().min(3, 'Nama minimal 3 karakter'),
  code: z.string(),
  length: z.preprocess(Number, z.number().min(1, 'Length minimal 1')),
  price: z.preprocess(Number, z.number().min(1, 'Harga minimal 1')),
  status: z.string().min(1, 'Status is required'),
})
export type TSubscribePlanSchema = z.infer<typeof subscribePlanSchema>
type TProperties = {
  subscribePlanData?: TSubscribePlanResponse
}

export const FormSubscribePlanPage = (properties: TProperties) => {
  const { subscribePlanData } = properties || {}
  const fetcher = useFetcher()
  const navigate = useNavigate()
  const formMethods = useRemixForm<TSubscribePlanSchema>({
    mode: 'onSubmit',
    fetcher,
    resolver: zodResolver(subscribePlanSchema),
    values: {
      id: subscribePlanData?.id || undefined,
      code: subscribePlanData?.code || '',
      name: subscribePlanData?.name || '',
      length: subscribePlanData?.length || 0,
      price: subscribePlanData?.price || 0,
      status: subscribePlanData?.status.toString() || '',
    },
  })

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

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

    if (fetcher.data?.success) {
      toast.success(
        `Subscribe Plan berhasil ${subscribePlanData ? 'diupdate' : 'dibuat'}!`,
      )
      navigate('/lg-admin/subscribe-plan')
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetcher.data])

  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"
          >
            <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={fetcher.state !== 'idle'}
                isLoading={fetcher.state !== 'idle'}
                type="submit"
                size="lg"
                className="text-md h-[42px] rounded-md"
              >
                Save
              </Button>
            </div>
            <div className="flex items-end justify-between gap-4">
              <Input
                id="length"
                label="Length"
                type="number"
                placeholder="Masukkan Subscribe Plan Length (days)"
                name="length"
                className="border-0 bg-white shadow read-only:bg-gray-100 focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="flex-1"
              />
              <Input
                id="price"
                label="Harga"
                placeholder="Masukkan Harga"
                type="number"
                name="price"
                className="border-0 bg-white shadow read-only:bg-gray-100 focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="flex-1"
              />

              <Select
                id="status"
                name="status"
                label="Status"
                placeholder="Pilih Status"
                options={[
                  { value: 1, name: 'Aktif' },
                  { value: 0, name: 'Nonaktif' },
                ]}
                className="border-0 bg-white shadow focus:ring-1 focus:ring-[#2E2F7C] focus:outline-none"
                labelClassName="text-sm font-medium text-[#363636]"
                containerClassName="flex-1"
              />
            </div>
          </fetcher.Form>
        </RemixFormProvider>
      </div>

      <DevTool control={control} />
    </div>
  )
}
