import React, { useState, useContext } from "react";
import "../../components/Filters/Filters.css";
import "./Adjustments.css";
import Table from "../../components/Table/HotelTable copy";
import { redirect } from "react-router-dom";
import { langContext } from "../../context/LenguageContext";
import ExcelExportButton from "../../components/ExcelExportButton";

//**////** */ */  VERIFICAR POR QUE MANDA DISCARD Y NO AJUSTMENT  solo el endpoint  /products/stockadjusmentset
export default function Adjustments() {
  const { lang } = useContext(langContext);
  const [adjustments, setAdjustments] = useState([]);
  const [productSearch, setProductSearch] = useState('');
  const [saving, setSaving] = useState(false);

  React.useEffect(() => {
    fetch(import.meta.env.VITE_API_BASE_URL + "/products")
      .then((res) => res.json())
      .then((data) => {
        if (Array.isArray(data.data)) {
          setAdjustments(
            data.data.map((prod) => ({
              productId: prod.id_product,
              product: prod.name_product,
              currentStock: Number(prod.units),
              realStock: prod.units,
              adjustment: 0,
            }))
          );
        } else {
          setAdjustments([]);
        }
      });
  }, []);

  const handleRealStockChange = (productId, value) => {
    const numericValue = Number(value);
    const realStock =
      isNaN(numericValue) || numericValue < 0 ? 0 : numericValue;

    const currentDate = new Date();
    const newAdjustments = adjustments.map((item) => {
      if (item.productId === productId) {
        return {
          ...item,
          realStock,
          adjustment: realStock - item.currentStock,
          datediscard: `${currentDate.getDay}-${currentDate.getMonth}-${currentDate.getFullYear()}`,
        };
      }
      return item;
    });
    setAdjustments(newAdjustments);
  };

  const columns = [
    {
      header: lang === "es" ? "ID DEL PRODUCTO" : "PRODUCT ID",
      key: "productId",
    },
    { header: lang === "es" ? "PRODUCTO" : "PRODUCT", key: "product" },
    {
      header: lang === "es" ? "STOCK ACTUAL" : "CURRENT STOCK",
      key: "currentStock",
    },
    {
      header: lang === "es" ? "STOCK REAL" : "REAL STOCK",
      key: "realStock",
      render: (value, row) => {
        const isDisabled = !row.currentStock || Number(row.currentStock) <= 0 || saving;
        return (
          <input
            type="number"
            value={row.realStock}
            min={0}
            disabled={isDisabled}
            title={
              saving
                ? lang === "es"
                  ? "Guardando ajustes..."
                  : "Saving adjustments..."
                : isDisabled
                ? lang === "es"
                  ? "No se puede ajustar cuando el stock es 0"
                  : "Cannot adjust when stock is 0"
                : ""
            }
            onKeyDown={(e) => {
              if (
                e.key === "-" ||
                e.key === "e" ||
                e.key === "E" ||
                e.key === "+"
              ) {
                e.preventDefault();
              }
            }}
            style={{
              width: "60px",
              textAlign: "center",
              backgroundColor: isDisabled ? "#f0f0f0" : "white",
              color: "#000",
              cursor: isDisabled ? "not-allowed" : "text",
              opacity: isDisabled ? 0.6 : 1,
            }}
            onChange={(e) => {
              const inputValue = e.target.value;
              if (
                inputValue === "" ||
                (!isNaN(inputValue) && Number(inputValue) >= 0)
              ) {
                handleRealStockChange(
                  row.productId,
                  inputValue === "" ? 0 : Number(inputValue)
                );
              }
            }}
          />
        );
      },
    },
    {
      header: lang === "es" ? "AJUSTE" : "ADJUSTMENT",
      key: "adjustment",
      render: (value) => (
        <span
          style={{ color: value < 0 ? "red" : "inherit", fontWeight: "bold" }}
        >
          {value}
        </span>
      ),
    },
  ];

  const filteredAdjustments = adjustments.filter(item =>
    item.product?.toLowerCase().includes(productSearch.toLowerCase())
  );

  const exportColumns = [
    {
      header: lang === "es" ? "ID DEL PRODUCTO" : "PRODUCT ID",
      key: "productId",
    },
    { header: lang === "es" ? "PRODUCTO" : "PRODUCT", key: "product" },
    {
      header: lang === "es" ? "STOCK ACTUAL" : "CURRENT STOCK",
      key: "currentStock",
    },
    { header: lang === "es" ? "STOCK REAL" : "REAL STOCK", key: "realStock" },
    { header: lang === "es" ? "AJUSTE" : "ADJUSTMENT", key: "adjustment" },
  ];

  const handleSave = async () => {
    setSaving(true);

    try {
      // Actualiza los ajustes antes de enviar
      const updatedAdjustments = adjustments.map((item) => ({
        ...item,
        adjustment: item.realStock - item.currentStock,
      }));
      setAdjustments(updatedAdjustments);
      //console.log('Ajustes a guardar:', updatedAdjustments);

      ///***/// *//products/stockadjusmentset/${item.productId}`,

      // {
      //     "stockproductadjusment":[{"id_product":1,"stock_adjusment":2}]
      //
      // } valida positivo negativo
      // { quantity: (item.adjustment)*(-1), reasons: 'ajuste' }

      // Petición a discardproduct
      for (const item of updatedAdjustments) {
        await fetch(
          `${import.meta.env.VITE_API_BASE_URL}/products/stockadjusmentset`,
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              stockproductadjusment: [
                {
                  id_product: item.productId,
                  stock_adjusment: item.adjustment,
                },
              ],
            }),
          }
        );
      }

      alert(lang === "es" ? "Ajustes guardados correctamente" : "Adjustments saved successfully");
      redirect("/app/inventory");
      // Recarga la página para reflejar los cambios
      window.location.reload();
    } catch (error) {
      console.error('Error saving adjustments:', error);
      alert(lang === "es" ? "Error al guardar los ajustes" : "Error saving adjustments");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="report-page">
      <div className="page-header">
        <h2 className="page-title">{lang === "es" ? "Ajustes" : "Adjustments"}</h2>
      </div>

      <div className="filters-section">
        <input
          type="text"
          placeholder={lang === "es" ? "Search product..." : "Search product..."}
          value={productSearch}
          onChange={(e) => setProductSearch(e.target.value)}
          disabled={saving}
          className="filter-search"
          style={{
            backgroundColor: saving ? '#f5f5f5' : undefined,
            cursor: saving ? 'not-allowed' : undefined
          }}
        />
        <button
          className="save-button"
          onClick={handleSave}
          disabled={saving}
        >
          {saving
            ? lang === "es"
              ? "Guardando..."
              : "Saving..."
            : lang === "es"
            ? "Guardar"
            : "Save"
          }
        </button>
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '1rem', position: 'relative' }}>
          <ExcelExportButton
            data={filteredAdjustments}
            columns={exportColumns}
            filenamePrefix={
              lang === "es" ? "ajustes-inventario" : "inventory-adjustments"
            }
            sheetName={lang === "es" ? "Ajustes" : "Adjustments"}
          />
          {saving && (
            <div
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: 'rgba(255, 255, 255, 0.8)',
                cursor: 'not-allowed',
                zIndex: 1
              }}
            />
          )}
        </div>

      <div className="table-section">
        <Table columns={columns} data={filteredAdjustments} />
      </div>
    </div>
  );
}
