'use client'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import * as z from 'zod'
import { useMutation, useQuery } from '@tanstack/react-query'
import { Button } from '@/components/ui/button'
import { DatePickerWithRange } from '@/components/ui/daterange'
import { addDays } from 'date-fns'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { useEffect } from 'react'
import Image from 'next/image'
import { toast, Toaster } from 'sonner'
import { useRouter } from 'next/navigation'
import {
  bookRoom,
  getRoomDetails,
  RoomBooking as BookingInterface,
} from '@/action'
import { urlFor } from '@/config/sanity'
import LoadingSpinner from '@/app/loading'

const formSchema = z.object({
  roomId: z.string().min(1, 'Room ID is required.'),
  roomType: z.string().default('x'),
  checkInDate: z.string().nonempty('Check-in date is required.'),
  checkOutDate: z.string().nonempty('Check-out date is required.'),
  guestName: z.string().trim().min(2, 'name is required.'),
  guestEmail: z.string().trim().email('Enter a valid email address.'),
  guestPhone: z
    .string()
    .trim()
    .min(10, 'Phone number must be at least 10 digits.'),
  paymentStatus: z.enum(['pending', 'completed', 'failed']).default('pending'),
  note: z.string().optional(),
  capacity: z.object({
    adults: z.coerce.number().min(0, 'Number of adults cannot be negative.'),
    children: z.coerce.number().default(0),
  }),
})

export default function RoomBooking({ params }: { params: { _id: string } }) {
  const router = useRouter()
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      roomId: params._id,
      checkInDate: '',
      checkOutDate: '',
      guestName: '',
      guestEmail: '',
      guestPhone: '',
      paymentStatus: 'pending',
      note: '',
      capacity: {
        adults: 1,
        children: 0,
      },
    },
  })

  const { data, isLoading } = useQuery({
    queryKey: [`load-room-${params?._id}`],
    queryFn: async () => {
      return (await getRoomDetails(params?._id)).room
    },
  })

  const room: BookingInterface = data && data
  const bookingMutation = useMutation({
    mutationKey: ['booking'],
    mutationFn: async (data: z.infer<typeof formSchema>) => {
      const bookingData: BookingInterface = {
        ...data,
        _type: 'roomBooking',
        price: room?.price,
        totalCount: room?.totalCount,
        bookingCount: room?.bookingCount,
        status: room?.status,
      }
      return await bookRoom(bookingData)
    },
  })

  useEffect(() => {
    if (data) {
      form.setValue('roomType', data?.roomType)
    }
  }, [data, form])

  const { isPending } = bookingMutation

  const onSubmit = (data: z.infer<typeof formSchema>) => {
    bookingMutation.mutate(data, {
      onSuccess: () => {
        toast.success('Booking successful!')
        form.reset()
      },
      onError: () => {
        toast('Booking failed, please try again.')
      },
    })
  }

  if (isLoading) return <LoadingSpinner />

  return (
    <div className="flex flex-col lg:flex-row w-full justify-center lg:justify-between p-4 gap-6">
      {/* Room Information Section */}
      <div className="lg:w-1/2 w-full flex flex-col items-start p-4">
        <Image
          src={urlFor(data?.images[0])?.toString()}
          alt="Room Image"
          width={500}
          height={300}
          className="rounded-lg mb-4 w-full object-cover"
        />
        <h2 className="text-2xl font-semibold mb-3 uppercase">
          {data?.roomType}
        </h2>
        <p className="text-base mb-4 text-justify">{data?.description}</p>
        <div>
          <p className="text-lg mb-4 font-light">
            Starting from{' '}
            <span className="text-3xl font-semibold">NPR {room.price}</span> per
            night
          </p>
          <p
            className={`text-lg font-semibold mb-8 ${room.status === 'online' ? 'text-green-400' : 'text-red-400'}`}
          >
            {room?.status === 'online' ? 'Available' : 'Offline'}
          </p>
        </div>

        {/* Capacity */}
        <div className="bg-gray-100 p-6 rounded-lg shadow-sm mb-6">
          <h3 className="text-2xl font-bold text-gray-800 mb-4 uppercase">
            Capacity
          </h3>
          <div className="space-y-2 text-gray-700">
            <p>
              <strong className="text-gray-800">Adults:</strong>{' '}
              {room.capacity.adults}
            </p>
            <p>
              <strong className="text-gray-800">Children:</strong>{' '}
              {room.capacity.children}
            </p>
          </div>
        </div>

        {/* Amenities */}
        <div className="bg-gray-100 p-6 rounded-lg shadow-sm">
          <h3 className="text-2xl font-bold text-gray-800 mb-4 uppercase">
            Amenities
          </h3>
          <ul className="space-y-2 list-disc list-inside">
            {data.amenities?.map((amenity: any) => (
              <li key={amenity._key} className="text-gray-700">
                <strong className="font-semibold text-gray-800">
                  {amenity.category}:
                </strong>{' '}
                {amenity.amenitiesList.join(', ')}
              </li>
            ))}
          </ul>
        </div>
      </div>

      {/* Booking Form Section */}
      <div className="lg:w-1/2 w-full p-4 sticky  self-start top-10 bg-white rounded-lg shadow-md flex flex-col items-center">
        <h2 className="text-xl font-semibold text-center w-full mb-6">
          Room Booking
        </h2>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="w-full flex flex-col gap-y-6"
          >
            <FormField
              control={form.control}
              name="checkInDate"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Check-In Date</FormLabel>
                  <FormControl>
                    <DatePickerWithRange
                      initialRange={{
                        from: new Date(),
                        to: addDays(new Date(), 1),
                      }}
                      onChange={(e) => {
                        form.setValue(
                          'checkInDate',
                          e?.from?.toString() as string,
                          { shouldValidate: true }
                        )
                        form.setValue(
                          'checkOutDate',
                          e?.to?.toString() as string,
                          { shouldValidate: true }
                        )
                      }}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="guestName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Name</FormLabel>
                  <FormControl>
                    <Input {...field} placeholder="Enter your name" />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="guestEmail"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Email</FormLabel>
                  <FormControl>
                    <Input {...field} placeholder="Enter your email" />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="guestPhone"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Phone</FormLabel>
                  <FormControl>
                    <Input {...field} placeholder="Enter your phone number" />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="note"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Additional Notes</FormLabel>
                  <FormControl>
                    <Textarea
                      {...field}
                      placeholder="Enter any additional notes"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="capacity.adults"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Number of Adults</FormLabel>
                  <FormControl>
                    <Input type="number" {...field} min={0} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="capacity.children"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Number of Children</FormLabel>
                  <FormControl>
                    <Input type="number" {...field} min={0} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <Button type="submit" className="w-full mt-4" disabled={isPending}>
              {isPending ? 'Processing...' : 'Book Now'}
            </Button>
          </form>
        </Form>
      </div>
      <Toaster position="top-center" />
    </div>
  )
}
