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

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 CardHeader from "../../../components/Card/CardHeader";
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 { Measurements } from "../types/article";

export interface MeasurementsCardProps {
  measurements?: Measurements;
  setMeasurements: (measurements: Measurements) => void;
}

export interface MeasurementsCardFormValues {
  length: number;
  width: number;
  height: number;
  weight: number;
}

export const MeasurementsCard: React.FC<MeasurementsCardProps> = ({
  measurements,
  setMeasurements,
}) => {
  const params = useParams();
  const api = useApi();
  const { t } = useI18n();
  const { user } = useUser();

  const handleSubmit = async (values: MeasurementsCardFormValues) => {
    const action = api.operations["catalog.article:update"];
    if (!action) {
      throw new Error('Invalid action "catalog.article:update".');
    }

    const { length, width, height, weight } = values;

    const response = await action.call({
      params,
      body: {
        measurements: {
          dimensions: length && width && height ? { length, width, height } : null,
          weight: weight || null,
        },
      },
    });

    if (response.ok) {
      const updatedArticle = await response.json();
      setMeasurements(updatedArticle.measurements);
      return t("Measurements updated successfully.");
    } else {
      console.error("[MEASUREMENTS_CARDS]", response);
      throw new Error("updating article measurement fields.");
    }
  };

  return (
    <>
      <Card<MeasurementsCardFormValues>
        columns={3}
        isEditable={hasPermission(user, "catalog.change_article")}
        onSubmit={handleSubmit}
      >
        <CardHeader title={t("Measurements")} />

        <CardContent>
          <CardRow>
            <CardFieldNumber
              adornment="mm"
              formName="width"
              label={t("Width")}
              max={32767}
              min={0}
              value={measurements?.dimensions?.width}
            />
            <CardFieldNumber
              adornment="mm"
              formName="height"
              label={t("Height")}
              max={32767}
              min={0}
              value={measurements?.dimensions?.height}
            />
          </CardRow>

          <CardRow>
            <CardFieldNumber
              adornment="mm"
              formName="length"
              label={t("Length")}
              max={32767}
              min={0}
              value={measurements?.dimensions?.length}
            />
            <CardFieldNumber
              adornment="g"
              formName="weight"
              label={t("Weight")}
              max={32767}
              min={0}
              value={measurements?.weight}
            />
          </CardRow>
        </CardContent>

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