import { useFormContext, useWatch } from "react-hook-form"
import { useIntl } from "react-intl"
import { useMediaQuery } from "usehooks-ts"

import { Button } from "@scandic-hotels/design-system/Button"
import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"

import {
  AncillaryStepEnum,
  useAddAncillaryStore,
} from "@/stores/my-stay/add-ancillary-flow"

import { trackAddAncillary } from "@/utils/tracking/myStay"

import { type AncillaryQuantityFormData, quantitySchema } from "../../schema"

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

import type { ActionButtonsProps } from "@/types/components/myPages/myStay/ancillaries"

export default function ActionButtons({
  togglePriceDetails,
  isPriceDetailsOpen,
  isSubmitting,
}: ActionButtonsProps) {
  const {
    currentStep,
    isBreakfast,
    prevStep,
    prevStepMobile,
    selectQuantity,
    selectDeliveryTime,
    selectQuantityAndDeliveryTime,
    selectedAncillary,
    breakfastData,
  } = useAddAncillaryStore((state) => ({
    currentStep: state.currentStep,
    isBreakfast: state.isBreakfast,
    prevStep: state.prevStep,
    prevStepMobile: state.prevStepMobile,
    selectQuantity: state.selectQuantity,
    selectDeliveryTime: state.selectDeliveryTime,
    selectQuantityAndDeliveryTime: state.selectQuantityAndDeliveryTime,
    selectedAncillary: state.selectedAncillary,
    breakfastData: state.breakfastData,
  }))
  const isMobile = useMediaQuery("(max-width: 767px)")
  const { setError } = useFormContext()

  const intl = useIntl()
  const isConfirmStep = currentStep === AncillaryStepEnum.confirmation
  const confirmLabel = intl.formatMessage({
    defaultMessage: "Confirm",
  })
  const continueLabel = intl.formatMessage({
    defaultMessage: "Continue",
  })
  const quantityWithCard = useWatch<AncillaryQuantityFormData>({
    name: "quantityWithCard",
  })
  const quantityWithPoints = useWatch<AncillaryQuantityFormData>({
    name: "quantityWithPoints",
  })
  function handleNextStep() {
    if (currentStep === AncillaryStepEnum.selectQuantity) {
      const validatedQuantity = quantitySchema.safeParse({
        quantityWithCard,
        quantityWithPoints,
      })
      if (validatedQuantity.success) {
        trackAddAncillary(
          selectedAncillary,
          quantityWithCard,
          quantityWithPoints,
          breakfastData
        )
        if (isMobile) {
          selectQuantityAndDeliveryTime()
        } else {
          selectQuantity()
        }
      } else {
        setError("quantityWithCard", validatedQuantity.error.issues[0])
      }
    } else if (currentStep === AncillaryStepEnum.selectDelivery) {
      selectDeliveryTime()
    }
  }

  return (
    <div className={isConfirmStep ? styles.confirmButtons : ""}>
      {isConfirmStep && (
        <Button
          type="button"
          typography="Body/Supporting text (caption)/smBold"
          size="Small"
          variant="Text"
          onPress={togglePriceDetails}
          className={styles.priceButton}
        >
          {intl.formatMessage({
            defaultMessage: "Price details",
          })}
          <MaterialIcon
            icon={
              isPriceDetailsOpen ? "keyboard_arrow_up" : "keyboard_arrow_down"
            }
            size={20}
            color="Icon/Interactive/Accent"
          />
        </Button>
      )}
      <div className={styles.buttons}>
        <Button
          typography="Body/Supporting text (caption)/smBold"
          type="button"
          variant="Text"
          size="Small"
          color="Primary"
          onPress={isMobile ? prevStepMobile : prevStep}
        >
          {intl.formatMessage({
            defaultMessage: "Back",
          })}
        </Button>
        {isConfirmStep && (
          <Button
            type="submit"
            typography="Body/Supporting text (caption)/smBold"
            variant="Primary"
            size="Small"
            isDisabled={isSubmitting}
            form="add-ancillary-form-id"
          >
            {confirmLabel}
          </Button>
        )}
        {!isConfirmStep && (
          <Button
            type="button"
            typography="Body/Supporting text (caption)/smBold"
            variant={isBreakfast ? "Primary" : "Secondary"}
            size="Small"
            isDisabled={isSubmitting}
            onPress={handleNextStep}
          >
            {continueLabel}
          </Button>
        )}
      </div>
    </div>
  )
}
