import React from "react";

import CardFieldAutoComplete from "../../../components/Card/CardFieldAutoComplete";
import CardFieldNumber from "../../../components/Card/CardFieldNumber";
import CardFieldText from "../../../components/Card/CardFieldText";
import { ProductProperty, ProductPropertyValue } from "../types/product";

export interface ProductPropertyFieldProps {
  property: ProductProperty;
  value: ProductPropertyValue;
  formName?: string;
}

export const ProductPropertyField: React.FC<ProductPropertyFieldProps> = ({
  property,
  value,
  formName,
}) => {
  switch (property.type) {
    case "string": {
      const currentValue = value as string;
      return (
        <CardFieldText
          formName={formName ?? property.name}
          label={property.title}
          required={property.required}
          value={currentValue}
        />
      );
    }

    case "integer": {
      const currentValue = parseInt(value as string);
      return (
        <CardFieldNumber
          formName={formName ?? property.name}
          label={property.title}
          max={property.max_value}
          min={property.min_value}
          required={property.required}
          value={Number.isNaN(currentValue) ? undefined : currentValue}
        />
      );
    }

    case "array": {
      const currentValue = value as string[];

      return (
        <CardFieldAutoComplete
          autoSelect
          clearOnBlur
          freeSolo
          fallback={"—"}
          formName={formName ?? property.name}
          label={property.title}
          required={property.required}
          value={(currentValue ?? []).map((val: ProductPropertyValue) => ({
            id: val as string,
            label: val as string,
          }))}
        />
      );
    }
  }

  return <></>;
};
