import { useState, type MouseEvent } from 'react'

import { useToggle } from 'hooks'

import type { MatchPackage } from 'features/BuyMatchPopup/types'
import { SubscriptionType } from 'features/BuyMatchPopup/types'
import { Price } from 'features/Price'
import { T9n } from 'features/T9n'
import { useBuyMatchPopupStore } from 'features/BuyMatchPopup/store'
import { ArrowLoader } from 'features/ArrowLoader'

import { usePackage } from '../RegularPackage/usePackage'
import {
  Wrapper,
  Header,
  Title,
  Button,
  Content,
  Description,
  Body,
  Border,
  SubscriptionTypeText,
  BestChoice,
} from './styled'

type Props = {
  buttonId?: string,
  buttonLexic?: string,
  matchPackage: MatchPackage,
  onButtonClick?: (e: MouseEvent<HTMLButtonElement>, matchPackage?: MatchPackage) => void,
}

export const PackageMobile = ({
  buttonId,
  buttonLexic,
  matchPackage,
  onButtonClick,
}: Props) => {
  const {
    matchPackages,
    setSelectedPackage,
  } = useBuyMatchPopupStore()

  const isSinglePackage = matchPackages.length === 1

  const { isOpen, toggle } = useToggle(isSinglePackage)
  const [loader, setLoader] = useState(false)

  const { firstDescription, priceTextTopLexic } = usePackage(matchPackage)

  const handleButtonClick = (e: MouseEvent<HTMLButtonElement>) => {
    setSelectedPackage(matchPackage)
    onButtonClick?.(e, matchPackage)
    setLoader(true)
  }

  return (
    <Wrapper>
      <Header
        isOpen={isOpen}
        onClick={isSinglePackage ? undefined : toggle}
      >
        <Title t={matchPackage.originalObject.sub.lexic1} />
        <Price
          amount={matchPackage.originalObject.price}
          currency={matchPackage.currency}
          perPeriod={matchPackage.isMonthSubscription ? `per_${SubscriptionType.Month}` : undefined}
        />
      </Header>
      {isOpen && <Border />}
      <Content isOpen={isOpen}>
        <Body>
          <Description>
            {firstDescription}
          </Description>
          <Description>
            <T9n t={matchPackage.originalObject.sub.lexic3} />
          </Description>
          {matchPackage.isMainPackage && (
            <BestChoice>
              <T9n t='best_choice' />
            </BestChoice>
          )}
          <SubscriptionTypeText t={priceTextTopLexic} />
        </Body>
        <Button id={buttonId} onClick={handleButtonClick}>
          {loader
            ? <ArrowLoader disabled />
            : <T9n t={buttonLexic || ''} />}
        </Button>
      </Content>
    </Wrapper>
  )
}
