'use client'

import { Button } from '@/components/shadcn/ui/button'
import {
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Form,
} from '@/components/shadcn/ui/form'
import { Input } from '@/components/shadcn/ui/input'
import Spinner from '@/components/Spinner'
import { zodResolver } from '@hookform/resolvers/zod'
import { Search } from 'lucide-react'
import React, { Dispatch, SetStateAction } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { Order } from '@/lib/types/order'
import { toast } from 'react-toastify'
import { AxiosError } from 'axios'
import { useAppSelector } from '@/lib/redux-hooks'
import reservationService from '@/lib/services/reservation-service'

const searchFormSchema = z.object({
  billing_name: z
    .string({
      required_error: 'Billing Name is required',
    })
    .min(1, {
      message: 'Billing Name is required',
    })
    .max(255, { message: 'Billing Name must be less than 255 characters' }),
  billing_email: z.string().email('Invalid email address'),
})

interface SearchFormProps {
  searching: boolean
  setSearching: Dispatch<SetStateAction<boolean>>
  handleOrdersFound: (orders: Order[]) => void
}

const SearchForm: React.FC<SearchFormProps> = ({
  searching,
  setSearching,
  handleOrdersFound,
}) => {
  const merchant = useAppSelector((state) => state.merchant)
  const form = useForm<z.infer<typeof searchFormSchema>>({
    resolver: zodResolver(searchFormSchema),
    defaultValues: {
      billing_name: '',
      billing_email: '',
    },
  })

  function onSubmit(data: z.infer<typeof searchFormSchema>) {
    setSearching(true)

    const fetchOrder = async () => {
      try {
        const orders = await reservationService.getReservations(
          data.billing_name,
          data.billing_email,
          merchant.id,
        )

        setSearching(false)
        handleOrdersFound(orders)
      } catch (error: any) {
        setSearching(false)

        if (error instanceof AxiosError) {
          switch (error.status) {
            case 400:
              toast.error('Bad request, please try again.')
              break
          }
        }

        toast.error('Something went wrong, please try again later.')
      }
    }

    fetchOrder()
  }

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit)}
        className="grid grid-cols-12 gap-4 place-items-end"
      >
        {/* Billing Name */}
        <FormField
          control={form.control}
          name="billing_name"
          render={({ field }) => (
            <FormItem className="col-span-12 md:col-span-5 relative w-full">
              <FormLabel>Billing Name</FormLabel>
              <FormControl>
                <Input placeholder="Enter billing_name..." {...field} />
              </FormControl>
              <FormMessage className="md:absolute md:-bottom-6" />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="billing_email"
          render={({ field }) => (
            <FormItem className="col-span-12 md:col-span-5 relative w-full">
              <FormLabel>Billing Email</FormLabel>
              <FormControl>
                <Input placeholder="Enter your email address..." {...field} />
              </FormControl>
              <FormMessage className="md:absolute md:-bottom-6" />
            </FormItem>
          )}
        />

        <Button
          type="submit"
          className="col-span-12 md:col-span-2 h-11 uppercase focus:ring-2 focus:ring-blue-400 bg-blue-800 hover:bg-blue-700 text-white w-full"
          color="blue"
          disabled={searching}
        >
          {searching ? (
            <>
              <Spinner color="white" size="sm" />
              <span>SEARCHING...</span>
            </>
          ) : (
            <>
              <Search className="w-4 h-4 sm:w-5 sm:h-5" />
              <span>SEARCH</span>
            </>
          )}
        </Button>
      </form>
    </Form>
  )
}

export default SearchForm
