import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

import AddCircleIcon from "@mui/icons-material/AddCircle";
import RemoveCircleIcon from "@mui/icons-material/RemoveCircle";
import { Stack } from "@mui/material";

import Card from "../../../components/Card";
import CardActions from "../../../components/Card/CardActions";
import CardCancelButton from "../../../components/Card/CardCancelButton";
import CardContent from "../../../components/Card/CardContent";
import CardFieldCheckbox from "../../../components/Card/CardFieldCheckbox";
import CardFieldSelect from "../../../components/Card/CardFieldSelect";
import CardFieldText from "../../../components/Card/CardFieldText";
import CardHeader from "../../../components/Card/CardHeader";
import CardPill from "../../../components/Card/CardPill";
import CardRow from "../../../components/Card/CardRow";
import CardSaveButton from "../../../components/Card/CardSaveButton";
import { useApi } from "../../../contexts/ApiContext";
import { useI18n } from "../../../contexts/I18nContext";
import { useUser } from "../../../contexts/UserContext";
import { hasPermission } from "../../../util/has_permission";
import { SHOW_PRICE_RULES } from "../flags";
import { PriceListDetail, PriceRuleOption } from "../types/price_list";

export interface PriceListProps {
  priceList: PriceListDetail;
  setPriceList: (priceList: PriceListDetail) => void;
}

export interface PriceListCardFormValues {
  name: string;
  is_active: string;
  is_tax_included: string;
  site_code: string;
  price_rule: PriceRuleOption;
}

export const PriceListCard: React.FC<PriceListProps> = ({ priceList, setPriceList }) => {
  const params = useParams();
  const api = useApi();
  const { t } = useI18n();
  const { user } = useUser();

  const [siteCodes, setSiteCodes] = useState<string[]>([]);
  const [priceRules, setPriceRules] = useState<PriceRuleOption[]>([]);

  const handleSubmit = async ({
    is_active,
    is_tax_included,
    ...values
  }: PriceListCardFormValues) => {
    const action = api.operations["pricing.price_list:update"];
    if (!action) {
      throw new Error('Invalid action "pricing.price_list:update".');
    }

    const response = await action.call({
      params,
      body: {
        is_active: is_active === "on",
        is_tax_included: is_tax_included === "on",
        ...values,
      },
    });

    if (response.ok) {
      const updatedPriceList = await response.json();
      setPriceList(updatedPriceList);
      return t("Price list updated successfully.");
    } else {
      console.error("[PRICE_LIST_CARD]", response);
      throw new Error("updating price list fields.");
    }
  };

  useEffect(() => {
    api.operations["pricing.price_list:options"]
      .call({
        params,
      })
      .then(async (response) => {
        if (response.ok) {
          const { site_codes, price_rules } = await response.json();
          setSiteCodes(site_codes);
          setPriceRules(price_rules);
        }
      });
  }, []);

  return (
    <Card<PriceListCardFormValues>
      isCompact
      isEditable={hasPermission(user, "pricing.change_pricelist")}
      onSubmit={handleSubmit}
    >
      <CardHeader title={t("Price List")}>
        <Stack direction="row" gap={1}>
          <CardPill
            color={priceList.is_active ? "success" : "error"}
            label={priceList.is_active ? t("Active") : t("Inactive")}
          />
          <CardPill
            color={priceList.is_tax_included ? "info" : "warning"}
            icon={priceList.is_tax_included ? <AddCircleIcon /> : <RemoveCircleIcon />}
            label={priceList.is_tax_included ? t("Includes Tax") : t("Excludes Tax")}
          />
        </Stack>
      </CardHeader>

      <CardContent>
        <CardRow>
          <CardFieldText formName="name" label={t("Name")} value={priceList.name} />
        </CardRow>

        <CardRow>
          <CardFieldSelect
            formName="site_code"
            label={t("Site")}
            options={siteCodes.map((siteCode) => ({
              label: siteCode,
              id: siteCode,
            }))}
            value={{ label: priceList.site_code, id: priceList.site_code }}
          />
        </CardRow>

        <CardRow>
          <CardFieldText formName="channel" label={t("Channel")} value={priceList.channel} />
        </CardRow>

        <CardRow isReadable={false}>
          <CardFieldCheckbox
            formName="is_active"
            isReadable={false}
            label={t("Active")}
            value={priceList.is_active}
          />

          <CardFieldCheckbox
            formName="is_tax_included"
            isReadable={false}
            label={t("Includes Tax")}
            value={priceList.is_tax_included}
          />
        </CardRow>

        {SHOW_PRICE_RULES && (
          <CardRow>
            <CardFieldSelect
              formName="price_rule"
              label={t("Price rule")}
              options={priceRules.map((priceRule) => ({
                label: priceRule.name,
                id: priceRule.id,
              }))}
              value={
                priceList.price_rule
                  ? {
                      label: priceList.price_rule.name,
                      id: priceList.price_rule.id,
                    }
                  : undefined
              }
            />
          </CardRow>
        )}
      </CardContent>

      <CardActions>
        <CardCancelButton />
        <CardSaveButton />
      </CardActions>
    </Card>
  );
};

export default PriceListCard;
