/**
 * Copyright (c) 2023-present Plane Software, Inc. and contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 * See the LICENSE file for details.
 */

// plane imports
import { observer } from "mobx-react";
import type { EProductSubscriptionEnum, TBillingFrequency } from "@plane/types";
import { calculateYearlyDiscount, cn } from "@plane/utils";

type TPlanFrequencyToggleProps = {
  subscriptionType: EProductSubscriptionEnum;
  monthlyPrice: number;
  yearlyPrice: number;
  selectedFrequency: TBillingFrequency;
  setSelectedFrequency: (frequency: TBillingFrequency) => void;
};

export const PlanFrequencyToggle = observer(function PlanFrequencyToggle(props: TPlanFrequencyToggleProps) {
  const { monthlyPrice, yearlyPrice, selectedFrequency, setSelectedFrequency } = props;
  // derived values
  const yearlyDiscount = calculateYearlyDiscount(monthlyPrice, yearlyPrice);

  return (
    <div className="flex w-full cursor-pointer items-center py-1">
      <div className="flex w-full space-x-1 rounded-md bg-layer-3 p-0.5">
        <button
          type="button"
          onClick={() => setSelectedFrequency("month")}
          className={cn(
            "w-full rounded-sm px-1 py-0.5 text-center text-caption-sm-medium leading-5",
            selectedFrequency === "month"
              ? "border border-subtle-1 bg-layer-2 text-primary shadow-raised-100"
              : "text-tertiary hover:text-secondary"
          )}
        >
          Monthly
        </button>
        <button
          type="button"
          onClick={() => setSelectedFrequency("year")}
          className={cn(
            "w-full rounded-sm px-1 py-0.5 text-center text-caption-sm-medium leading-5",
            selectedFrequency === "year"
              ? "border border-subtle-1 bg-layer-2 text-primary shadow-raised-100"
              : "text-tertiary hover:text-secondary"
          )}
        >
          Yearly
          {yearlyDiscount > 0 && (
            <span className="ml-1.5 rounded-full bg-accent-primary px-1 py-0.5 text-caption-xs-regular text-on-color">
              -{yearlyDiscount}%
            </span>
          )}
        </button>
      </div>
    </div>
  );
});
