"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useRouter } from "next/navigation"
import { useState } from "react"
import { Dialog } from "react-aria-components"
import { FormProvider, useForm } from "react-hook-form"
import { useIntl } from "react-intl"

import { trpc } from "@/lib/trpc/client"

import { DiamondIcon, EditIcon } from "@/components/Icons"
import MembershipLevelIcon from "@/components/Levels/Icon"
import Modal from "@/components/Modal"
import { ModalContentWithActions } from "@/components/Modal/ModalContentWithActions"
import Button from "@/components/TempDesignSystem/Button"
import Body from "@/components/TempDesignSystem/Text/Body"
import Caption from "@/components/TempDesignSystem/Text/Caption"
import { toast } from "@/components/TempDesignSystem/Toasts"
import useLang from "@/hooks/useLang"

import ModifyContact from "../ModifyContact"

import styles from "./room.module.css"

import {
  type ModifyContactSchema,
  modifyContactSchema,
} from "@/types/components/hotelReservation/myStay/modifyContact"
import { MODAL_STEPS } from "@/types/components/hotelReservation/myStay/myStay"
import type { BookingConfirmation } from "@/types/trpc/routers/booking/confirmation"
import type { User } from "@/types/user"

interface GuestDetailsProps {
  user: User | null
  booking: BookingConfirmation["booking"]
  isMobile?: boolean
}

export default function GuestDetails({
  user,
  booking,
  isMobile = false,
}: GuestDetailsProps) {
  const intl = useIntl()
  const lang = useLang()
  const router = useRouter()
  const [currentStep, setCurrentStep] = useState(MODAL_STEPS.INITIAL)
  const [isLoading, setIsLoading] = useState(false)
  const [guestDetails, setGuestDetails] = useState<
    BookingConfirmation["booking"]["guest"]
  >(booking.guest)
  const [isModifyGuestDetailsOpen, setIsModifyGuestDetailsOpen] =
    useState(false)

  const isFirstStep = currentStep === MODAL_STEPS.INITIAL

  const form = useForm<ModifyContactSchema>({
    resolver: zodResolver(modifyContactSchema),
    defaultValues: {
      firstName: booking.guest.firstName ?? "",
      lastName: booking.guest.lastName ?? "",
      email: booking.guest.email ?? "",
      phoneNumber: booking.guest.phoneNumber ?? "",
      countryCode: booking.guest.countryCode ?? "",
    },
  })
  const containerClass = isMobile
    ? styles.guestDetailsMobile
    : styles.guestDetailsDesktop

  const isMemberBooking =
    booking.guest.membershipNumber === user?.membership?.membershipNumber

  const updateGuest = trpc.booking.update.useMutation({
    onMutate: () => setIsLoading(true),
    onSuccess: () => {
      setIsLoading(false)
      toast.success(intl.formatMessage({ id: "Guest details updated" }))
      setIsModifyGuestDetailsOpen(false)
    },
    onError: () => {
      setIsLoading(false)
      toast.error(intl.formatMessage({ id: "Failed to update guest details" }))
    },
  })

  async function onSubmit(data: ModifyContactSchema) {
    if (booking.confirmationNumber) {
      updateGuest.mutate({
        confirmationNumber: booking.confirmationNumber,
        guest: {
          email: data.email,
          phoneNumber: data.phoneNumber,
          countryCode: data.countryCode,
        },
      })
      setGuestDetails({ ...guestDetails, ...data })
    }
  }

  function handleModifyMemberDetails() {
    const expirationTime = Date.now() + 10 * 60 * 1000
    sessionStorage.setItem(
      "myStayReturnRoute",
      JSON.stringify({
        path: window.location.pathname,
        expiry: expirationTime,
      })
    )
    router.push(`/${lang}/scandic-friends/my-pages/profile/edit`)
  }

  return (
    <div className={containerClass}>
      {isMemberBooking && (
        <div className={styles.userDetails}>
          <div className={styles.row}>
            <div className={styles.rowTitle}>
              <Caption
                type="bold"
                color="burgundy"
                textTransform="uppercase"
                textAlign="center"
              >
                {intl.formatMessage({ id: "Your member tier" })}
              </Caption>
            </div>
            <MembershipLevelIcon
              level={user.membership!.membershipLevel}
              color="red"
              height={isMobile ? "40" : "20"}
              width={isMobile ? "80" : "40"}
            />
          </div>
          <div className={styles.totalPoints}>
            {isMobile && (
              <div>
                <DiamondIcon color="uiTextHighContrast" />
              </div>
            )}
            <Caption
              type="bold"
              color="uiTextHighContrast"
              textTransform="uppercase"
            >
              {intl.formatMessage({ id: "Total points" })}
            </Caption>

            <Body color="uiTextHighContrast" className={styles.totalPointsText}>
              {user.membership!.currentPoints}
            </Body>
          </div>
        </div>
      )}
      <div className={styles.guest}>
        <Body textTransform="bold" color="uiTextHighContrast">
          {guestDetails.firstName} {guestDetails.lastName}
        </Body>
        {isMemberBooking && (
          <Body color="uiTextHighContrast">
            {intl.formatMessage(
              { id: "Member no. {nr}" },
              {
                nr: user.membership!.membershipNumber,
              }
            )}
          </Body>
        )}
        <Caption color="uiTextHighContrast">{guestDetails.email}</Caption>
        <Caption color="uiTextHighContrast">{guestDetails.phoneNumber}</Caption>
      </div>
      {isMemberBooking ? (
        <Button
          variant="icon"
          color="burgundy"
          intent={isMobile ? "secondary" : "text"}
          onClick={handleModifyMemberDetails}
        >
          <EditIcon color="burgundy" width={20} height={20} />
          <Caption color="burgundy">
            {intl.formatMessage({ id: "Modify guest details" })}
          </Caption>
        </Button>
      ) : (
        <>
          <Button
            variant="icon"
            color="burgundy"
            intent="text"
            onClick={() =>
              setIsModifyGuestDetailsOpen(!isModifyGuestDetailsOpen)
            }
          >
            <EditIcon color="burgundy" width={20} height={20} />
            <Caption color="burgundy">
              {intl.formatMessage({ id: "Modify guest details" })}
            </Caption>
          </Button>
          <Modal
            withActions
            hideHeader
            isOpen={isModifyGuestDetailsOpen}
            onToggle={setIsModifyGuestDetailsOpen}
          >
            <Dialog>
              {({ close }) => (
                <FormProvider {...form}>
                  <ModalContentWithActions
                    title={intl.formatMessage({ id: "Modify guest details" })}
                    onClose={() => setIsModifyGuestDetailsOpen(false)}
                    content={
                      <ModifyContact
                        guest={booking.guest}
                        isFirstStep={isFirstStep}
                      />
                    }
                    primaryAction={{
                      label: isFirstStep
                        ? intl.formatMessage({ id: "Save updates" })
                        : intl.formatMessage({ id: "Confirm" }),
                      onClick: isFirstStep
                        ? () => setCurrentStep(MODAL_STEPS.CONFIRMATION)
                        : () => {
                            form.handleSubmit(onSubmit)()
                          },
                      disabled: !form.formState.isValid || isLoading,
                      intent: isFirstStep ? "secondary" : "primary",
                    }}
                    secondaryAction={{
                      label: isFirstStep
                        ? intl.formatMessage({ id: "Back" })
                        : intl.formatMessage({ id: "Cancel" }),
                      onClick: () => {
                        close()
                        setCurrentStep(MODAL_STEPS.INITIAL)
                      },
                    }}
                  />
                </FormProvider>
              )}
            </Dialog>
          </Modal>
        </>
      )}
    </div>
  )
}
