import { zodResolver } from "@hookform/resolvers/zod"
import * as Sentry from "@sentry/nextjs"
import { useRouter } from "next/navigation"
import { FormProvider, useForm } from "react-hook-form"
import { useIntl } from "react-intl"
import { z } from "zod"

import { Search } from "@/components/Forms/BookingWidget/FormContent/Search"
import { toast } from "@/components/TempDesignSystem/Toasts"

const destinationSearchFormSchema = z.object({
  destinationSearch: z.string().min(1),
})
type DestinationSearchFormSchema = z.infer<typeof destinationSearchFormSchema>

type DestinationSearchFormProps = {
  isMobile?: boolean
}

export function DestinationSearchForm({
  isMobile,
}: DestinationSearchFormProps) {
  const router = useRouter()
  const intl = useIntl()

  const methods = useForm<DestinationSearchFormSchema>({
    defaultValues: {
      destinationSearch: "",
    },
    shouldFocusError: false,
    mode: "onSubmit",
    resolver: zodResolver(destinationSearchFormSchema),
    reValidateMode: "onSubmit",
  })

  return (
    <FormProvider {...methods}>
      <Search
        autoFocus={isMobile}
        alwaysShowResults={isMobile}
        includeTypes={["cities", "hotels", "countries"]}
        variant={isMobile ? "default" : "rounded"}
        handlePressEnter={() => {
          void 0
        }}
        inputName={"destinationSearch"}
        onSelect={(item) => {
          if (!item.url) {
            Sentry.captureMessage(
              "Unable to JumpTo selected location, no URL provided",
              {
                extra: { locationName: item.name },
              }
            )
            toast.error(
              intl.formatMessage(
                { defaultMessage: "Unable to open page for {locationName}" },
                { locationName: item.name }
              )
            )
            return
          }
          router.push(item.url)
        }}
        withSearchButton={!isMobile}
      />
    </FormProvider>
  )
}
