import Button from "@/components/Forms/Button";
import Input from "@/components/Forms/Input";
import InputSelectComponent from "@/components/Forms/InputSelect";
import ModalComponente from "@/components/Modal/ModalComponente";
import ReactTable from "@/components/ReactTable/ReactTable";
import { listarProductCategoriesHelte } from "@/requests/CRM/APIHelte/listarProductCategoriesHelte";
import { listarProductsFromCategoryHelte } from "@/requests/CRM/APIHelte/listarProductsFromCategoryHelte";
import { GetForm, GetGallery } from "@/utils";
import { Plus } from "lucide-react";
import { useEffect, useState } from "react";

const NewItemKitHelteForm = ({ budget_id, submitEditItemKit }: any) => {
  const [productCategoriesHelte, setProductCategoriesHelte] = useState<any[]>(
    [],
  );
  const [selectedCategory, setSelectedCategory] = useState(0);
  const [tableKey, setTableKey] = useState(0);
  const [productInfo, setProductInfo] = useState<any>({});
  const [isAddingProduct, setIsAddingProduct] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const { openGallery, setGallery } = GetGallery();
  const { handleSubmit, ...formItem } = GetForm();

  useEffect(() => {
    listarProductCategoriesHelte().then((res) => {
      setProductCategoriesHelte(res);
    });
  }, []);

  const [columns, setColumns] = useState([
    { header: "ID", accessorKey: "id" },
    { header: "Nome", accessorKey: "name" },
    { header: "Imagem", accessorKey: "img" },
    { header: "Categoria", accessorKey: "category" },
  ]);

  const formatProducts = async (data: any) => {
    setGallery(data.map((e: any) => ({ src: e.img, name: e.name })));
    const newData = data.map((e: any, index: number) => {
      if (e.category.id == "1") {
        const potenciaNominal = e.datasheet.find(
          (e: any) => e.name == "Potência Nominal",
        );
        e.potency =
          potenciaNominal?.si == "W"
            ? Number(potenciaNominal?.value) / 1000 + "kW"
            : potenciaNominal?.value + potenciaNominal.si;
      }

      e.category = e.category.name;
      e.img = (
        <img
          src={e.img}
          alt={e.img}
          style={{ width: "100%", height: "100%", objectFit: "cover" }}
          onClick={() => openGallery(index)}
        />
      );

      return e;
    });
    return newData;
  };

  function submitEdicaoItem(data: any) {
    setIsLoading(true);
    return submitEditItemKit({
      id: productInfo.id,
      quantity: +data.quantity,
    }).finally(() => setIsLoading(false));
  }

  return (
    <div>
      <div className="flex flex-col gap-3" onClick={(e) => e.stopPropagation()}>
        <InputSelectComponent
          label="Categoria"
          options={productCategoriesHelte.map((category) => ({
            value: category.id,
            label: category.name,
          }))}
          onChange={(e: any) => {
            let newColumns = [
              { header: "ID", accessorKey: "id" },
              { header: "Nome", accessorKey: "name" },
              { header: "Imagem", accessorKey: "img" },
              { header: "Categoria", accessorKey: "category" },
            ];
            if (e.value == "1") {
              newColumns = [
                { header: "ID", accessorKey: "id" },
                { header: "Nome", accessorKey: "name" },
                { header: "Imagem", accessorKey: "img" },
                { header: "Potência", accessorKey: "potency" },
                { header: "Categoria", accessorKey: "category" },
              ];
            }
            setColumns(newColumns);
            setSelectedCategory(e.value);
            setTableKey(tableKey + 1);
          }}
          width="w-[200px]"
        />

        {tableKey != 0 && (
          <ReactTable
            key={tableKey}
            columns={columns}
            formatFunction={formatProducts}
            listFunction={async () =>
              listarProductsFromCategoryHelte({
                budget_id,
                id: selectedCategory,
              })
            }
            idCol="id"
            pageName="Produto"
            actionButtons={(
              data: any,
              updateTable: any,
              setIsLoading: any,
              { idCol, pageName, editFunction }: any,
            ) => [
              {
                className: `navButton`,
                onClick: (e: any) => {
                  setProductInfo(data);
                  setIsAddingProduct(true);
                },
                content: <Plus />,
              },
            ]}
          />
        )}
        {isAddingProduct && (
          <ModalComponente
            hasForm={false}
            header={productInfo.name}
            defaultW="w-[400px]"
            opened={isAddingProduct}
            onClose={() => setIsAddingProduct(false)}
            hasSaveButton={false}
          >
            <div className="flex flex-col gap-3">
              <div>
                <Input
                  name="quantity"
                  label="Quantidade"
                  formulario={formItem}
                  onKeyDown={(e: any) => {
                    e.stopPropagation();
                    if (e.key.includes("Enter")) {
                      e.preventDefault();
                      handleSubmit(submitEdicaoItem)(e);
                    }
                  }}
                  mascara="numerico"
                  required
                  error="Informe a quantidade"
                />
              </div>
              <div className="flex flex-row justify-end gap-2">
                <Button
                  loading={isLoading}
                  onClick={handleSubmit(submitEdicaoItem)}
                >
                  Confirmar
                </Button>
                <Button
                  className="bg-error"
                  onClick={() => setIsAddingProduct(false)}
                >
                  Cancelar
                </Button>
              </div>
            </div>
          </ModalComponente>
        )}
      </div>
    </div>
  );
};

export default NewItemKitHelteForm;
