"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { usePathname, 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 { profileEdit } from "@scandic-hotels/common/constants/routes/myPages"
import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"
import Modal from "@scandic-hotels/design-system/Modal"
import { ModalContentWithActions } from "@scandic-hotels/design-system/Modal/ModalContentWithActions"
import { OldDSButton as Button } from "@scandic-hotels/design-system/OldDSButton"
import { toast } from "@scandic-hotels/design-system/Toast"
import { Typography } from "@scandic-hotels/design-system/Typography"
import { trpc } from "@scandic-hotels/trpc/client"

import { isWebview } from "@/constants/routes/webviews"

import MembershipLevelIcon from "@/components/Levels/Icon"
import useLang from "@/hooks/useLang"

import ModifyContact from "../ModifyContact"

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

import type { Guest } from "@scandic-hotels/trpc/routers/booking/output"

import {
  type ModifyContactSchema,
  modifyContactSchema,
} from "@/types/components/hotelReservation/myStay/modifyContact"
import { MODAL_STEPS } from "@/types/components/hotelReservation/myStay/myStay"
import type { SafeUser } from "@/types/user"

interface GuestDetailsProps {
  refId: string
  guest: Guest
  isCancelled: boolean
  user: SafeUser
}

export default function GuestDetails({
  refId,
  guest,
  isCancelled,
  user,
}: GuestDetailsProps) {
  const intl = useIntl()
  const lang = useLang()
  const router = useRouter()
  const utils = trpc.useUtils()
  const [currentStep, setCurrentStep] = useState(MODAL_STEPS.INITIAL)
  const [isLoading, setIsLoading] = useState(false)
  const pathname = usePathname()

  const [isModifyGuestDetailsOpen, setIsModifyGuestDetailsOpen] =
    useState(false)

  const form = useForm<ModifyContactSchema>({
    resolver: zodResolver(modifyContactSchema),
    defaultValues: {
      firstName: guest.firstName,
      lastName: guest.lastName,
      email: guest.email,
      phoneNumber: guest.phoneNumber,
      countryCode: guest.countryCode,
    },
  })

  const isFirstStep = currentStep === MODAL_STEPS.INITIAL

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

  const updateGuest = trpc.booking.update.useMutation({
    onMutate: () => setIsLoading(true),
    onSuccess: (data) => {
      if (data) {
        utils.booking.get.invalidate({
          refId: data.refId,
        })

        toast.success(
          intl.formatMessage({
            id: "myStay.guestDetails.updatedSuccess",
            defaultMessage: "Guest details updated",
          })
        )
        setIsModifyGuestDetailsOpen(false)
        setCurrentStep(MODAL_STEPS.INITIAL)
      } else {
        toast.error(
          intl.formatMessage({
            id: "myStay.guestDetails.updatedError",
            defaultMessage: "Failed to update guest details",
          })
        )
      }
    },
    onError: () => {
      toast.error(
        intl.formatMessage({
          id: "myStay.guestDetails.updatedError",
          defaultMessage: "Failed to update guest details",
        })
      )
    },
    onSettled: () => {
      setIsLoading(false)
    },
  })

  async function onSubmit(data: ModifyContactSchema) {
    updateGuest.mutate({
      refId,
      guest: {
        email: data.email,
        phoneNumber: data.phoneNumber,
        countryCode: data.countryCode,
      },
      language: lang,
    })
  }

  function handleModifyMemberDetails() {
    const expirationTime = Date.now() + 10 * 60 * 1000
    sessionStorage.setItem(
      "myStayReturnRoute",
      JSON.stringify({
        path: window.location.href,
        expiry: expirationTime,
      })
    )
    router.push(profileEdit[lang])
  }

  return (
    <div className={styles.guestDetails}>
      {isMemberBooking && user.membership && (
        <div className={styles.userDetails}>
          <div className={styles.userDetailsTitle}>
            <Typography variant="Title/Overline/sm">
              <p>
                {intl.formatMessage({
                  id: "myStay.yourMemberLevel",
                  defaultMessage: "Your member level",
                })}
              </p>
            </Typography>
          </div>
          <div className={styles.memberLevel}>
            <MembershipLevelIcon
              level={user.membership.membershipLevel}
              color="red"
              rows={1}
              className={styles.memberLevelIcon}
            />
          </div>
          <div className={styles.totalPoints}>
            <div className={styles.totalPointsText}>
              <MaterialIcon icon="diamond" color="Icon/Intense" />

              <Typography variant="Title/Overline/sm">
                <p>
                  {intl.formatMessage({
                    id: "myStay.myTotalPoints",
                    defaultMessage: "My total points",
                  })}
                </p>
              </Typography>
            </div>

            <Typography variant="Body/Paragraph/mdRegular">
              <p>{user.membership.currentPoints}</p>
            </Typography>
          </div>
        </div>
      )}
      <div className={styles.guest}>
        <Typography variant="Body/Paragraph/mdBold">
          <p>
            {guest.firstName} {guest.lastName}
          </p>
        </Typography>
        {isMemberBooking && user.membership && (
          <Typography variant="Body/Paragraph/mdRegular">
            <p className={styles.memberNumber}>
              {intl.formatMessage(
                {
                  id: "myStay.membershipId",
                  defaultMessage: "Membership ID: {nr}",
                },
                {
                  nr: user.membership.membershipNumber,
                }
              )}
            </p>
          </Typography>
        )}
        <div className={styles.contactInfoMobile}>
          <Typography variant="Body/Supporting text (caption)/smRegular">
            <p>{guest.email}</p>
          </Typography>
          <Typography variant="Body/Supporting text (caption)/smRegular">
            <p>{guest.phoneNumber}</p>
          </Typography>
        </div>
        <div className={styles.contactInfoDesktop}>
          <Typography variant="Body/Paragraph/mdRegular">
            <p>{guest.email}</p>
          </Typography>
          <Typography variant="Body/Paragraph/mdRegular">
            <p>{guest.phoneNumber}</p>
          </Typography>
        </div>
      </div>
      {!isWebview(pathname) && (
        <>
          {isMemberBooking ? (
            <Button
              variant="icon"
              color="burgundy"
              intent="secondary"
              onClick={handleModifyMemberDetails}
              disabled={isCancelled}
              size="small"
            >
              <MaterialIcon
                icon="edit"
                color="Icon/Interactive/Default"
                size={20}
              />
              <Typography variant="Body/Paragraph/mdRegular">
                <span>
                  {intl.formatMessage({
                    id: "myStay.guestDetails.modifyGuestDetails",
                    defaultMessage: "Modify guest details",
                  })}
                </span>
              </Typography>
            </Button>
          ) : (
            <>
              <Button
                variant="icon"
                color="burgundy"
                intent="secondary"
                onClick={() =>
                  setIsModifyGuestDetailsOpen(!isModifyGuestDetailsOpen)
                }
                disabled={isCancelled}
                size="small"
              >
                <MaterialIcon
                  icon="edit"
                  color={
                    isCancelled
                      ? "Icon/Interactive/Disabled"
                      : "Icon/Interactive/Default"
                  }
                  size={20}
                />
                <Typography variant="Body/Paragraph/mdRegular">
                  <span>
                    {intl.formatMessage({
                      id: "myStay.guestDetails.modifyGuestDetails",
                      defaultMessage: "Modify guest details",
                    })}
                  </span>
                </Typography>
              </Button>
              {isModifyGuestDetailsOpen && (
                <Modal
                  withActions
                  hideHeader
                  isOpen={isModifyGuestDetailsOpen}
                  onToggle={setIsModifyGuestDetailsOpen}
                >
                  <Dialog
                    aria-label={intl.formatMessage({
                      id: "myStay.guestDetails.modifyGuestDetails",
                      defaultMessage: "Modify guest details",
                    })}
                  >
                    {({ close }) => (
                      <FormProvider {...form}>
                        <ModalContentWithActions
                          title={intl.formatMessage({
                            id: "myStay.guestDetails.modifyGuestDetails",
                            defaultMessage: "Modify guest details",
                          })}
                          onClose={() => setIsModifyGuestDetailsOpen(false)}
                          content={
                            guest && (
                              <ModifyContact
                                guest={guest}
                                isFirstStep={isFirstStep}
                              />
                            )
                          }
                          primaryAction={{
                            label: isFirstStep
                              ? intl.formatMessage({
                                  id: "myStay.modifyContact.saveUpdates",
                                  defaultMessage: "Save updates",
                                })
                              : intl.formatMessage({
                                  id: "common.confirm",
                                  defaultMessage: "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: "common.back",
                                  defaultMessage: "Back",
                                })
                              : intl.formatMessage({
                                  id: "common.cancel",
                                  defaultMessage: "Cancel",
                                }),
                            onClick: () => {
                              close()
                              setCurrentStep(MODAL_STEPS.INITIAL)
                            },
                          }}
                        />
                      </FormProvider>
                    )}
                  </Dialog>
                </Modal>
              )}
            </>
          )}
        </>
      )}
    </div>
  )
}
