"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 { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"
import { Typography } from "@scandic-hotels/design-system/Typography"

import { profileEdit } from "@/constants/routes/myPages"
import { trpc } from "@/lib/trpc/client"

import MembershipLevelIcon from "@/components/Levels/Icon"
import Modal from "@/components/Modal"
import { ModalContentWithActions } from "@/components/Modal/ModalContentWithActions"
import Button from "@/components/TempDesignSystem/Button"
import { toast } from "@/components/TempDesignSystem/Toasts"
import useLang from "@/hooks/useLang"

import ModifyContact from "../ModifyContact"

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

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"
import type { Guest } from "@/server/routers/booking/output"

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 [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({
            defaultMessage: "Guest details updated",
          })
        )
        setIsModifyGuestDetailsOpen(false)
        setCurrentStep(MODAL_STEPS.INITIAL)
      } else {
        toast.error(
          intl.formatMessage({
            defaultMessage: "Failed to update guest details",
          })
        )
      }
    },
    onError: () => {
      toast.error(
        intl.formatMessage({
          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({
                  defaultMessage: "Your member tier",
                })}
              </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({
                    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(
                {
                  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>
      {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({
                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({
                  defaultMessage: "Modify guest details",
                })}
              </span>
            </Typography>
          </Button>
          {isModifyGuestDetailsOpen && (
            <Modal
              withActions
              hideHeader
              isOpen={isModifyGuestDetailsOpen}
              onToggle={setIsModifyGuestDetailsOpen}
            >
              <Dialog
                aria-label={intl.formatMessage({
                  defaultMessage: "Modify guest details",
                })}
              >
                {({ close }) => (
                  <FormProvider {...form}>
                    <ModalContentWithActions
                      title={intl.formatMessage({
                        defaultMessage: "Modify guest details",
                      })}
                      onClose={() => setIsModifyGuestDetailsOpen(false)}
                      content={
                        guest && (
                          <ModifyContact
                            guest={guest}
                            isFirstStep={isFirstStep}
                          />
                        )
                      }
                      primaryAction={{
                        label: isFirstStep
                          ? intl.formatMessage({
                              defaultMessage: "Save updates",
                            })
                          : intl.formatMessage({
                              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({
                              defaultMessage: "Back",
                            })
                          : intl.formatMessage({
                              defaultMessage: "Cancel",
                            }),
                        onClick: () => {
                          close()
                          setCurrentStep(MODAL_STEPS.INITIAL)
                        },
                      }}
                    />
                  </FormProvider>
                )}
              </Dialog>
            </Modal>
          )}
        </>
      )}
    </div>
  )
}
