import { useState } from 'react';

import { Box, Button } from 'components/common';
import { RadioInput } from 'components/inputs/RadioInput';
import { ExternalLink } from 'components/router/ExternalLink';

import {
  SubscriptionPlans,
  SubscriptionPlansProps,
} from 'components/billing/SubscriptionPlans';
import { call } from 'utils/call';

interface SelectPlanScreenProps {
  plans: SubscriptionPlansProps['items'];
  currentPlan: string;
  currentBillingCycle: string;
  defaultPlan?: string;
  defaultbillingCycle?: string;
  status: string;
  onConfirm?: (selected: string, billingCycle: string) => void;
}

export const SelectPlanScreen = ({
  plans,
  currentPlan,
  currentBillingCycle,
  defaultPlan = currentPlan,
  defaultbillingCycle = 'annual',
  status,
  onConfirm,
}: SelectPlanScreenProps) => {
  const [selectedPlan, setSelectedPlan] = useState(defaultPlan);
  const [billingCycle, setBillingCycle] = useState(defaultbillingCycle);

  const handlePackageChange: React.ChangeEventHandler<HTMLInputElement> = (
    ev
  ) => {
    setSelectedPlan(ev.target.value);
  };

  const changeBillingCycle: React.ChangeEventHandler<HTMLInputElement> = (
    ev
  ) => {
    setBillingCycle(ev.target.value);
  };

  const handleConfirm = () => {
    call(onConfirm, selectedPlan, billingCycle);
  };

  const isSamePlan =
    status === 'active' &&
    currentPlan === selectedPlan &&
    currentBillingCycle === billingCycle;

  return (
    <Box spacingY={10} style={{ paddingBottom: 100 }}>
      <Box spacingY={5}>
        <Box display="flex" justify="between" paddingX={4}>
          <Box className="bold">Billing cycle</Box>
          <Box className="fz14" display="flex" align="center" spacing={2}>
            <RadioInput
              name="billingCycle"
              value="monthly"
              checked={billingCycle === 'monthly'}
              onChange={changeBillingCycle}
            >
              Monthly
            </RadioInput>
            <RadioInput
              name="billingCycle"
              value="annual"
              checked={billingCycle === 'annual'}
              onChange={changeBillingCycle}
            >
              Annual
            </RadioInput>
          </Box>
        </Box>
        <SubscriptionPlans
          items={plans}
          inputName="package"
          currentPlan={currentPlan}
          billingCycle={billingCycle}
          checked={selectedPlan}
          onChange={handlePackageChange}
        />
        <Box>
          <ExternalLink
            className="link fz14"
            href="https://fansifter.com/pricing"
          >
            Learn more about plans on the pricing page
          </ExternalLink>
        </Box>
      </Box>
      <Box display="flex" justify="end">
        <Button
          onClick={handleConfirm}
          size="l"
          disabled={!onConfirm || isSamePlan}
        >
          Finalize and confirm
        </Button>
      </Box>
    </Box>
  );
};
