import React from "react";
import { useState } from "react";

import FormControlLabel from "@mui/material/FormControlLabel";
import Switch from "@mui/material/Switch";
import Typography from "@mui/material/Typography";

import Card from "../../../components/Card";
import CardActions from "../../../components/Card/CardActions";
import CardCancelButton from "../../../components/Card/CardCancelButton";
import CardContent from "../../../components/Card/CardContent";
import CardFieldNumber from "../../../components/Card/CardFieldNumber";
import CardFieldSelect from "../../../components/Card/CardFieldSelect";
import CardHeader from "../../../components/Card/CardHeader";
import CardRow from "../../../components/Card/CardRow";
import CardSaveButton from "../../../components/Card/CardSaveButton";
import LabeledValue from "../../../components/LabeledValue";
import { useApi } from "../../../contexts/ApiContext";
import { useCardContext } from "../../../contexts/CardContext";
import { useI18n } from "../../../contexts/I18nContext";
import { useUser } from "../../../contexts/UserContext";
import { ContribComponent } from "../../../types";
import { hasPermission } from "../../../util/has_permission";
import { SubscriptionPlan } from "../types/plan";

interface RecurringSwitchProps {
  isRecurring: boolean;
  onToggle: (checked: boolean) => void;
}

const RecurringSwitch: React.FC<RecurringSwitchProps> = ({ isRecurring, onToggle }) => {
  const { isEditing } = useCardContext();
  const { t } = useI18n();

  return isEditing ? (
    <FormControlLabel
      control={<Switch checked={isRecurring} onChange={(_, checked) => onToggle(checked)} />}
      label={
        <Typography color="textSecondary" variant="subtitle2">
          {t("Recurring")}
        </Typography>
      }
      labelPlacement="top"
    />
  ) : (
    <LabeledValue label={t("Recurring")} value={isRecurring ? "Yes" : "No"} />
  );
};

const SubscriptionPlanCard: ContribComponent<SubscriptionPlan> = ({ data, refresh }) => {
  const [isRecurring, setIsRecurring] = useState(Boolean(data.periodicity != null));
  const api = useApi();
  const { t } = useI18n();
  const { user } = useUser();

  const handleSave = async (formData: unknown) => {
    const action = api.operations["subscription.contrib:article-plan-update"];
    const response = await action.call({
      params: { code: data.code },
      body: formData as Omit<SubscriptionPlan, "code">,
    });

    if (response.ok) {
      refresh();
      return t("Plan updated successfully.");
    } else {
      console.error("[ARTICLE_SUBSCRIPTION_PLAN]", response);
      throw new Error("updating plan.");
    }
  };

  return (
    <Card
      isEditable={hasPermission(user, "subscription.change_subscription")}
      onSubmit={handleSave}
    >
      <CardHeader title="Subscription Plan" />
      <CardContent>
        <CardRow>
          <RecurringSwitch isRecurring={isRecurring} onToggle={setIsRecurring} />
          <CardFieldNumber
            disabled={!isRecurring}
            formName="nth"
            label={t("Frequency")}
            min={1}
            required={false}
            value={data.nth}
          />
          <CardFieldSelect
            disabled={!isRecurring}
            formName="periodicity"
            label={t("Periodicity")}
            options={[
              { label: "MONTH", id: "MONTH" },
              { label: "DAY", id: "DAY" },
            ]}
            required={false}
            value={
              isRecurring
                ? { label: data.periodicity ?? "", id: data.periodicity ?? "" }
                : undefined
            }
          />
        </CardRow>
      </CardContent>
      <CardActions>
        <CardCancelButton />
        <CardSaveButton />
      </CardActions>
    </Card>
  );
};

export default SubscriptionPlanCard;
