"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { FormProvider, useForm } from "react-hook-form"

import { useMyStayStore } from "@/stores/my-stay"

import CancelStayConfirmation from "./Confirmation"
import FinalConfirmation from "./FinalConfirmation"

import {
  type CancelStayFormValues,
  cancelStaySchema,
} from "@/types/components/hotelReservation/myStay/cancelStay"

interface StepsProps {
  closeModal: () => void
}

export default function Steps({ closeModal }: StepsProps) {
  const [confirm, setConfirm] = useState(false)
  const rooms = useMyStayStore((state) => state.rooms)

  const methods = useForm<CancelStayFormValues>({
    mode: "onSubmit",
    reValidateMode: "onChange",
    resolver: zodResolver(cancelStaySchema),
    values: {
      rooms: rooms.map((room, idx) => ({
        // Single room booking
        checked: rooms.length === 1,
        refId: room.refId,
        id: idx + 1,
      })),
    },
  })

  function handleSubmit(data: CancelStayFormValues) {
    const checkedRooms = data.rooms.filter((r) => r.checked)
    if (checkedRooms.length) {
      setConfirm(true)
    }
  }

  const stepOne = !confirm
  const stepTwo = confirm
  return (
    <FormProvider {...methods}>
      {/* Step 1 */}
      {stepOne ? (
        <CancelStayConfirmation
          closeModal={closeModal}
          onSubmit={handleSubmit}
        />
      ) : null}
      {/* Step 2 */}
      {stepTwo ? <FinalConfirmation closeModal={closeModal} /> : null}
    </FormProvider>
  )
}
