import React, { useEffect, useState, useCallback } from "react";
import "./NewProduct.css";
import { useContext } from "react";
import { langContext } from "../../context/LenguageContext";
import DiscardConfirmModal from "../../components/Modals/DiscardConfirmModal";

export default function DiscardProduct() {
  const { lang } = useContext(langContext);
  const [products, setProducts] = useState([]);
  console.log("PRODUCTS", products);
  const [form, setForm] = useState({
    productId: "",
    reasons: "",
    quantity: "",
  });
  const [loading, setLoading] = useState(false);
  const [initialLoading, setInitialLoading] = useState(true);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState("");
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);

  const loadProducts = useCallback(async () => {
    try {
      setError("");
      const response = await fetch(
        import.meta.env.VITE_API_BASE_URL + "/products"
      );
      if (!response.ok) {
        throw new Error(
          lang === "es"
            ? "Error al cargar los productos"
            : "Error loading products"
        );
      }
      const data = await response.json();
      setProducts(Array.isArray(data.data) ? data.data : []);
    } catch (err) {
      console.error("Error fetching products:", err);
      setError(
        err.message ||
          (lang === "es"
            ? "Error al cargar los productos"
            : "Error loading products")
      );
    }
  }, [lang]);

  useEffect(() => {
    async function loadInitialProducts() {
      try {
        setInitialLoading(true);
        await loadProducts();
      } finally {
        setInitialLoading(false);
      }
    }
    loadInitialProducts();
  }, [loadProducts]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setForm((prev) => {
      const updated = { ...prev, [name]: value };
      if (name === "productId") {
        const product = products.find((p) => p.id_product === parseInt(value));
        setSelectedProduct(product || null);
      }
      return updated;
    });
  };

  const validateForm = () => {
    if (!form.productId) {
      setError(
        lang === "es"
          ? "Por favor selecciona un producto"
          : "Please select a product"
      );
      return false;
    }
    const quantity = parseInt(form.quantity);
    if (!quantity || quantity < 1) {
      setError(
        lang === "es"
          ? "La cantidad debe ser mayor a 0"
          : "Quantity must be greater than 0"
      );
      return false;
    }
    if (selectedProduct && quantity > (parseInt(selectedProduct.units) || 0)) {
      setError(
        lang === "es"
          ? `La cantidad no puede ser mayor al stock disponible (${selectedProduct.units})`
          : `Quantity cannot exceed available stock (${selectedProduct.units})`
      );
      return false;
    }
    if (!form.reasons || form.reasons.trim() === "") {
      setError(
        lang === "es" ? "Por favor ingresa una razón" : "Please enter a reason"
      );
      return false;
    }
    return true;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");
    setSuccess(false);

    if (!validateForm()) {
      return;
    }

    setShowConfirmModal(true);
  };

  const handleConfirmDiscard = async () => {
    setShowConfirmModal(false);
    setLoading(true);
    const currentDate = new Date();
    try {
      const day = currentDate.getDate();
      const month = currentDate.getMonth() + 1;
      const year = currentDate.getFullYear();
      const formattedDate = `${day}-${month}-${year}`;

      const payload = {
        quantity: parseInt(form.quantity),
        reasons: form.reasons.trim(),
        datediscard: formattedDate,
      };

      const res = await fetch(
        `${import.meta.env.VITE_API_BASE_URL}/products/discardproduct/${form.productId}`,
        {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        }
      );

      if (!res.ok) {
        const errorData = await res.json().catch(() => ({}));
        throw new Error(
          errorData.message ||
            (lang === "es"
              ? "Error al descartar el producto"
              : "Error discarding product")
        );
      }

      await loadProducts();

      setSuccess(true);
      setForm({ productId: "", reasons: "", quantity: "" });
      setSelectedProduct(null);

      setTimeout(() => {
        setSuccess(false);
      }, 2000);
    } catch (err) {
      setError(
        err.message ||
          (lang === "es"
            ? "Error al descartar el producto"
            : "Error discarding product")
      );
    } finally {
      setLoading(false);
    }
  };

  const handleCancelDiscard = () => {
    setShowConfirmModal(false);
  };

  const confirmMessage =
    lang === "es"
      ? `¿Estás seguro de descartar ${form.quantity} unidad(es) de ${selectedProduct?.name_product || "este producto"}?`
      : `Are you sure you want to discard ${form.quantity} unit(s) of ${selectedProduct?.name_product || "this product"}?`;

  return (
    <div className="new-expense-container">
      <div className="form-card">
        <div className="form-id">
          {lang === "es" ? "Descartar producto" : "Discard product"}
        </div>

        {initialLoading ? (
          <p>
            {lang === "es" ? "Cargando productos..." : "Loading products..."}
          </p>
        ) : (
          <form onSubmit={handleSubmit}>
            <div className="form-grid">
              <div>
                <label>{lang === "es" ? "Producto" : "Product"}</label>
                <select
                  name="productId"
                  value={form.productId}
                  onChange={handleChange}
                  required
                  disabled={loading}
                >
                  <option value="">
                    {lang === "es" ? "Selecciona producto" : "Select product"}
                  </option>
                  {products
                    .filter((prod) => (parseInt(prod.units) || 0) >= 1)
                    .map((prod) => (
                      <option key={prod.id_product} value={prod.id_product}>
                        {prod.name_product}{" "}
                        {prod.units !== undefined
                          ? `(${lang === "es" ? "Stock" : "Stock"}: ${prod.units})`
                          : ""}
                      </option>
                    ))}
                </select>
              </div>
              <div>
                <label>{lang === "es" ? "Razón" : "Reason"}</label>
                <input
                  name="reasons"
                  value={form.reasons}
                  onChange={handleChange}
                  required
                  disabled={loading}
                  placeholder={
                    lang === "es"
                      ? "Ingresa la razón del descarte"
                      : "Enter discard reason"
                  }
                />
              </div>
              <div>
                <label>{lang === "es" ? "Cantidad" : "Quantity"}</label>
                <input
                  name="quantity"
                  value={form.quantity}
                  onChange={handleChange}
                  type="number"
                  min={1}
                  max={selectedProduct ? selectedProduct.units : undefined}
                  required
                  disabled={loading}
                  placeholder={
                    lang === "es"
                      ? "Cantidad a descartar"
                      : "Quantity to discard"
                  }
                />
                {selectedProduct && (
                  <small
                    style={{
                      color: "#666",
                      fontSize: "0.85em",
                      marginTop: "4px",
                    }}
                  >
                    {lang === "es" ? "Stock disponible" : "Available stock"}:{" "}
                    {selectedProduct.units || 0}
                  </small>
                )}
              </div>
            </div>
            <div className="save-button-wrapper">
              <button
                type="submit"
                className="save-button"
                disabled={loading || initialLoading}
              >
                {loading
                  ? lang === "es"
                    ? "Descartando..."
                    : "Discarding..."
                  : lang === "es"
                    ? "Descartar producto"
                    : "Discard product"}
              </button>
            </div>
            {success && (
              <div className="feedback-message success">
                {lang === "es"
                  ? "¡Producto descartado con éxito!"
                  : "Product discarded successfully!"}
              </div>
            )}
            {error && <div className="feedback-message error">{error}</div>}
          </form>
        )}
      </div>

      <DiscardConfirmModal
        isOpen={showConfirmModal}
        message={confirmMessage}
        onConfirm={handleConfirmDiscard}
        onCancel={handleCancelDiscard}
      />
    </div>
  );
}
