import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useContext } from 'react';
import { langContext } from '../../context/LenguageContext';
import './AlterProduct.css';

const IMAGE_BASE_URL = import.meta.env.VITE_API_BASE_URL + '/products';

export default function NewProduct() {
  const { lang } = useContext(langContext);
  const { id } = useParams();
  const navigate = useNavigate();
  const [productTypes, setProductTypes] = useState([]);
  const [categories, setCategories] = useState([]);
  const [suppliers, setSuppliers] = useState([]);
  const [currencies, setCurrencies] = useState([]);
  const [units, setUnits] = useState([]);
  const [imagePreview, setImagePreview] = useState(null);
  const [form, setForm] = useState({
    up_name_product: '',
    up_sku_product: '',
    product_type: 1,
    id_category: 0,
    supplier_rfc: '',
    unit: '',
    new_stock: '',
    up_price_product: '',
    up_id_tax: '',
    img_product: '',
    currency: '',
  });

  // Estados para la retroalimentación al usuario
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState('');

  // Efecto para cargar los datos de los selects y del producto a editar
  useEffect(() => {
    // Si no hay un ID en la URL, no se hace nada.
    if (!id) return;

    const fetchInitialData = async () => {
      setLoading(true); // Mostrar indicador de carga mientras se obtienen los datos
      setError('');
      try {
        // Realizar todas las peticiones de red en paralelo para mayor eficiencia
        const [
          productTypesRes,
          categoriesRes,
          suppliersRes,
          currenciesRes,
          unitsRes,
          productRes
        ] = await Promise.all([
          fetch(import.meta.env.VITE_API_BASE_URL + '/products/producttype', { method: 'GET' }),
          fetch(import.meta.env.VITE_API_BASE_URL + '/products/productcategory', { method: 'GET' }),
          fetch(import.meta.env.VITE_API_BASE_URL + '/products/suppliers', { method: 'GET' }),
          fetch(import.meta.env.VITE_API_BASE_URL + '/settings/currency', { method: 'GET' }),
          fetch(import.meta.env.VITE_API_BASE_URL + '/settings/units', { method: 'GET' }),
          fetch(`${import.meta.env.VITE_API_BASE_URL}/products/product/${id}`, { method: 'PUT' })
        ]);
        // Manejar errores si alguna de las respuestas de la API falla
        if (!productTypesRes.ok || !categoriesRes.ok || !suppliersRes.ok || !currenciesRes.ok || !unitsRes.ok || !productRes.ok) {
          throw new Error('Error al cargar los datos necesarios para el formulario.');
        }

        // Convertir todas las respuestas a formato JSON
        const productTypesData = await productTypesRes.json();
        const categoriesData = await categoriesRes.json();
        const suppliersData = await suppliersRes.json();
        const currenciesData = await currenciesRes.json();
        const unitsData = await unitsRes.json();
        const productData = await productRes.json();

        // Poblar los estados para las opciones de los selects
        setProductTypes(
          productTypesData.data.map(d => ({
            id: d.id_product_type,
            name: d.name_product_type,
            spanish_name: d.spanish_name
          }))
        );
        setCategories(
          categoriesData.data
            .filter(d => d.id_prod_category)
            .map(d => ({
              id: d.id_prod_category,
              name: d.name_prod_category,
              spanish_name: d.spanish_name
            }))
        );
        setSuppliers(suppliersData.data);
        if (currenciesData.currency) {
          setCurrencies(currenciesData.currency.map(c => ({ id: c.id_currency, name: c.name_currency })));
        }
        if (unitsData.units) {
          setUnits(unitsData.units.map(u => ({ id: u.id_unit, name: u.name_unit })));
        }

        // Poblar el estado del formulario con los datos del producto existente
        if (productData && productData.data && productData.data.length > 0) {
          const prod = productData.data[0];
          setForm({
            up_name_product: prod.name_product || '',
            up_sku_product: prod.sku_product || '',
            product_type: prod.product_type || [], // Se espera que sea un array de IDs
            id_category: prod.id_category_pro || '',
            supplier_rfc: prod.supplier_product || '',
            unit: prod.id_unit || '',
            new_stock: prod.stock || '',
            up_price_product: prod.price_product || '',
            up_id_tax: prod.id_tax || '',
            img_product: prod.image_product || '',
            currency: prod.id_curreny || '',
          });

          if (prod.image_product) {
            if (prod.image_product.startsWith('/')) {
              setImagePreview(`data:image/jpeg;base64,${prod.image_product}`);
            } else if (prod.image_product.length > 200) {
              setImagePreview(`data:image/jpeg;base64,${prod.image_product}`);
            } else {
              setImagePreview(`${IMAGE_BASE_URL}/${prod.image_product}`);
            }
          }
        } else {
            throw new Error(`No se encontró un producto con el ID ${id}.`);
        }

      } catch (err) {
        console.error("Error al cargar datos iniciales:", err);
        setError(err.message);
      } finally {
        setLoading(false); // Ocultar el indicador de carga
      }
    };

    fetchInitialData();
  }, [id]); // El efecto se volverá a ejecutar si el `id` del producto cambia

  // Manejar cambios en los campos del formulario
  const handleChange = e => {
    const { name, value } = e.target;
    // Manejo especial para el select múltiple de 'product_type'
    if (name === 'product_type') {
      const options = e.target.options;
      const selected = [];
      for (let i = 0; i < options.length; i++) {
        if (options[i].selected) selected.push(Number(options[i].value));
      }
      setForm(prev => ({ ...prev, product_type: selected }));
    } else {
      setForm(prev => ({ ...prev, [name]: value }));
    }
  };

  // Redimensionar y convertir la imagen a base64
  const handleImage = e => {
    const file = e.target.files[0];
    if (file) {
      const img = new window.Image();
      const reader = new FileReader();
      reader.onload = ev => {
        img.onload = () => {
          const MAX_WIDTH = 800;
          const scale = Math.min(1, MAX_WIDTH / img.width);
          const width = img.width * scale;
          const height = img.height * scale;
          const canvas = document.createElement('canvas');
          canvas.width = width;
          canvas.height = height;
          const ctx = canvas.getContext('2d');
          ctx.drawImage(img, 0, 0, width, height);
          const dataUrl = canvas.toDataURL('image/jpeg', 0.8);
          const base64 = dataUrl.split(',')[1];
          setForm(prev => ({ ...prev, img_product: base64 }));
          setImagePreview(dataUrl);
        };
        img.src = ev.target.result;
      };
      reader.readAsDataURL(file);
    }
  };

  // Enviar el formulario para actualizar el producto
  const handleSubmit = async e => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setSuccess(false);
    try {
      const payload = {
        up_name_product: form.up_name_product,
        up_sku_product: form.up_sku_product,
        product_type: form.product_type,
        id_category: form.id_category ? Number(form.id_category) : undefined,
        supplier_rfc: form.supplier_rfc,
        unit: form.unit ? Number(form.unit) : undefined,
        new_stock: form.new_stock ? Number(form.new_stock) : undefined,
        up_price_product: form.up_price_product ? Number(form.up_price_product) : undefined,
        up_id_tax: form.up_id_tax ? Number(form.up_id_tax) : undefined,
        img_product: form.img_product,
        currency: form.currency ? Number(form.currency) : undefined,
      };
      
      // Limpiar campos vacíos o indefinidos antes de enviar
      Object.keys(payload).forEach(k => (payload[k] === '' || payload[k] === undefined) && delete payload[k]);
      
      const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/products/update_product/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      if (!res.ok) throw new Error('Error al actualizar el producto');
      setSuccess(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="new-expense-container">
        <div className="form-card">
          <div className="form-header">
            <div className="form-id">{lang === "es" ? "Editar Producto" : "Edit Product"}</div>
            <button 
              type="button" 
              className="back-button"
              onClick={() => navigate('/app/products')}
            >
              <span>←</span>
              {lang === "es" ? "Volver" : "Back"}
            </button>
          </div>
          <form onSubmit={handleSubmit}>
            {loading && !success && <p>{lang === "es" ? "Cargando datos del producto..." : "Loading product data..."}</p>}

            <div className="form-grid">
              <div>
                <label>{lang === "es" ? "Nombre del producto" : "Product Name"}</label>
                <input name="up_name_product" value={form.up_name_product} onChange={handleChange} required />
              </div>
              <div>
                <label>{lang === "es" ? "SKU" : "SKU"}</label>
                <input name="up_sku_product" value={form.up_sku_product} onChange={handleChange} type="number" required />
              </div>
              <div>
                <label>{lang === "es" ? "Tipo de producto" : "Product Type"}</label>
                <select name="product_type" value={form.product_type} onChange={handleChange}  required>
                  <option value="">{lang === "es" ? "Selecciona categoría" : "Select category"}</option>
                  {productTypes
                    .sort((a, b) => {
                      const nameA = (lang === "en" ? (a.name || '') : (a.spanish_name || a.name || '')).toLowerCase();
                      const nameB = (lang === "en" ? (b.name || '') : (b.spanish_name || b.name || '')).toLowerCase();
                      return nameA.localeCompare(nameB);
                    })
                    .map(pt => {
                      const displayName = lang === "en" ? (pt.name || '') : (pt.spanish_name || pt.name || '');
                      console.log(`AlterProduct - Product Type ${pt.id}: lang=${lang}, name=${pt.name}, spanish_name=${pt.spanish_name}, display=${displayName}`);
                      return (
                        <option key={pt.id} value={pt.id}>
                          {displayName}
                        </option>
                      );
                    })}
                </select>
              </div>
              <div>
                <label>{lang === "es" ? "Categoría" : "Category"}</label>
                <select name="id_category" value={form.id_category} onChange={handleChange} required>
                  <option selected="Hotel accesories">{lang === "es" ? "Selecciona categoría" : "Select category"}</option>
                  {categories
                    .sort((a, b) => {
                      const nameA = (lang === "en" ? (a.name || '') : (a.spanish_name || a.name || '')).toLowerCase();
                      const nameB = (lang === "en" ? (b.name || '') : (b.spanish_name || b.name || '')).toLowerCase();
                      return nameA.localeCompare(nameB);
                    })
                    .map(cat => {
                      const displayName = lang === "en" ? (cat.name || '') : (cat.spanish_name || cat.name || '');
                      console.log(`AlterProduct - Category ${cat.id}: lang=${lang}, name=${cat.name}, spanish_name=${cat.spanish_name}, display=${displayName}`);
                      return (
                        <option key={cat.id} value={cat.id}>
                          {displayName}
                        </option>
                      );
                    })}
                </select>
              </div>
              <div>
                <label>{lang === "es" ? "Proveedor" : "Supplier"}</label>
                <select name="supplier_rfc" value={form.supplier_rfc} onChange={handleChange} required>
                  <option value="">{lang === "es" ? "Selecciona proveedor" : "Select supplier"}</option>
                  {suppliers
                    .sort((a, b) => {
                      const nameA = (a.name_suppliers || '').toLowerCase();
                      const nameB = (b.name_suppliers || '').toLowerCase();
                      return nameA.localeCompare(nameB);
                    })
                    .map(sup => (
                      <option key={sup.rfc_suppliers} value={sup.rfc_suppliers}>{sup.name_suppliers}</option>
                    ))}
                </select>
              </div>
              <div>
                <label>{lang === "es" ? "Unidad" : "Unit"}</label>
                <select name="unit" value={form.unit} onChange={handleChange} required>
                  <option value="">{lang === "es" ? "Selecciona unidad" : "Select unit"}</option>
                  {units
                    .sort((a, b) => {
                      const nameA = (a.name || '').toLowerCase();
                      const nameB = (b.name || '').toLowerCase();
                      return nameA.localeCompare(nameB);
                    })
                    .map(unit => (
                      <option key={unit.id} value={unit.id}>{unit.name}</option>
                    ))}
                </select>
              </div>
              <div>
                <label>{lang === "es" ? "Stock" : "Stock"}</label>
                <input name="new_stock" value={form.new_stock} onChange={handleChange} type="number" required />
              </div>
              <div>
                <label>{lang === "es" ? "Precio" : "Price"}</label>
                <input name="up_price_product" value={form.up_price_product} onChange={handleChange} type="number" step="0.01" required />
              </div>
              <div>
                <label>{lang === "es" ? "Impuesto" : "Tax"}</label>
                <select name="up_id_tax" value={form.up_id_tax} onChange={handleChange} required>
                  <option value="">{lang === "es" ? "Selecciona impuesto" : "Select tax"}</option>
                  <option value="1">16%</option>
                  <option value="2">8%</option>
                  <option value="3">0%</option>
                </select>
              </div>
              <div>
                <label>{lang === "es" ? "Moneda" : "Currency"}</label>
                <select name="currency" value={form.currency} onChange={handleChange} required>
                  <option value="">{lang === "es" ? "Selecciona moneda" : "Select currency"}</option>
                  {currencies
                    .sort((a, b) => {
                      const nameA = (a.name || '').toLowerCase();
                      const nameB = (b.name || '').toLowerCase();
                      return nameA.localeCompare(nameB);
                    })
                    .map(cur => (
                      <option key={cur.id} value={cur.id}>{cur.name}</option>
                    ))}
                </select>
              </div>
            </div>
            <div className="image-upload-section">
              <label>{lang === "es" ? "Imagen del producto" : "Product image"}</label>
              {imagePreview && (
                <div className="image-preview">
                  <img src={imagePreview} alt="Product preview" style={{ maxWidth: '200px', maxHeight: '200px', marginBottom: '10px' }} />
                </div>
              )}
              <input type="file" accept="image/*" onChange={handleImage} />
            </div>
            <div className="save-button-wrapper">
              <button type="submit" className="save-button" disabled={loading}>{loading ? 'Actualizando...' : 'Actualizar producto'}</button>
            </div>
            {success && <div className="feedback-message success">{lang === "es" ? "¡Producto actualizado con éxito!" : "Product updated successfully!"}</div>}
            {error && <div className="feedback-message error">{error}</div>}
          </form>
        </div>
      </div>
  );
}
