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

import Card from "../../../components/Card";
import CardContent from "../../../components/Card/CardContent";
import CardFieldSelect from "../../../components/Card/CardFieldSelect";
import CardFieldText from "../../../components/Card/CardFieldText";
import CardHeader from "../../../components/Card/CardHeader";
import CardRow from "../../../components/Card/CardRow";
import { useApi } from "../../../contexts/ApiContext";
import { useI18n } from "../../../contexts/I18nContext";
import { ContribComponent } from "../../../types";
import { ProductAssetsGallery } from "../components/ProductAssetsGallery";
import { ProductAssetsTable } from "../components/ProductAssetsTable";
import { ProductPropertyField } from "../components/ProductPropertyField";
import { ArticleProductResponse } from "../types/contrib";
import { ProductItemTypeOption, ProductPropertiesData } from "../types/product";

const ArticleProductCard: ContribComponent<ArticleProductResponse> = ({ data, params }) => {
  const { t } = useI18n();
  const api = useApi();
  const [productItemTypes, setProductItemTypes] = useState<ProductItemTypeOption[]>([]);

  const { code: articleCode } = params as { code: string };
  const { product, assets } = data;

  const articleAssets = assets.filter(
    (asset) => asset.article_code == articleCode || asset.article_code == "",
  );
  const imageAssets = articleAssets.filter((asset) => asset.asset_type == "image");
  const otherAssets = articleAssets.filter((asset) => asset.asset_type !== "image");

  const productProperties = product.properties as ProductPropertiesData;
  const productItemType = productItemTypes.find((itemType) => itemType.name == product.item_type);
  const productPropertiesList = productItemType ? productItemType.product_properties : [];
  const productPropertiesRows = productPropertiesList.reduce<(typeof productPropertiesList)[]>(
    (rows, prop, index) => {
      if (index % 2 === 0) rows.push([prop]);
      else rows[rows.length - 1].push(prop);
      return rows;
    },
    [],
  );

  useEffect(() => {
    api.operations["pim.item_types:options"].call({}).then(async (response) => {
      if (response.ok) {
        setProductItemTypes(await response.json());
      }
    });
  }, []);

  return (
    <Card columns={2} isEditable={false}>
      <CardHeader title="Product" />

      <CardContent>
        <CardRow>
          <CardFieldText formName="name" label={t("Name")} required={true} value={product.name} />
          <CardFieldSelect
            formName="item_type"
            label={t("Type")}
            options={productItemTypes.map((itemType) => ({
              id: itemType.name,
              label: itemType.name,
            }))}
            required={true}
            size={1}
            value={
              product.item_type ? { id: product.item_type, label: product.item_type } : undefined
            }
          />
        </CardRow>
        <CardRow>
          <CardFieldText
            formName="description"
            label={t("Description")}
            required={true}
            value={product.description}
          />
        </CardRow>
      </CardContent>

      {productPropertiesRows.length > 0 && (
        <>
          <CardHeader title={t("Properties")} />

          <CardContent>
            {productPropertiesRows.map((row, index) => (
              <CardRow key={index}>
                {row.map((prop) => (
                  <ProductPropertyField
                    key={prop.name}
                    property={prop}
                    value={productProperties[prop.name]}
                  />
                ))}
              </CardRow>
            ))}
          </CardContent>
        </>
      )}

      {articleAssets.length > 0 && <CardHeader title={t("Assets")} />}

      {imageAssets.length > 0 && (
        <CardContent
          sx={{
            width: "100%",
            height: 400,
            overflowY: "scroll",
            paddingTop: 0,
            paddingBottom: 0,
            paddingLeft: 3,
            paddingRight: 3,
          }}
        >
          <ProductAssetsGallery assets={imageAssets} />
        </CardContent>
      )}

      {otherAssets.length > 0 && <ProductAssetsTable assets={otherAssets} />}
    </Card>
  );
};

export default ArticleProductCard;
