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

export default function NewProduct() {
  const { lang } = useContext(langContext);
  const navigate = useNavigate();
  const [productTypes, setProductTypes] = useState([]);
  const [categories, setCategories] = useState([]);
  const [suppliers, setSuppliers] = useState([]);
  const [form, setForm] = useState({
    new_name_product: '',
    new_sku_product: '',
    product_type: '',
    new_category: '',
    new_rfc_suppliers: '',
    unit: '',
    new_stock: '',
    newprice_product: '',
    new_tax: '',
    currency: '', // aquí se guardará el id_currency
    image_product: '',
  });
  const [currencies, setCurrencies] = useState([]);
  const [_imageFile, setImageFile] = useState(null);
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState('');
  const [units, setUnits] = useState([]);
  const [packageQuantity, setPackageQuantity] = useState('');
  const [piecesPerPackage, setPiecesPerPackage] = useState('');
  const [numberOfPairs, setNumberOfPairs] = useState('');
  const [numberOfDozens, setNumberOfDozens] = useState('');

  useEffect(() => {
    fetch(import.meta.env.VITE_API_BASE_URL + '/products/producttype')
      .then(res => res.json())
      .then(data => {
        setProductTypes(
          data.data.map(d => ({ 
            id: d.id_product_type, 
            name: d.name_product_type,
            spanish_name: d.spanish_name || d.name_product_type
          }))
        );
      });
    fetch(import.meta.env.VITE_API_BASE_URL + '/products/productcategory')
      .then(res => res.json())
      .then(data => {
        setCategories(
          data.data
            .filter(d => d.id_prod_category)
            .map(d => ({ 
              id: d.id_prod_category, 
              name: d.name_prod_category,
              spanish_name: d.spanish_name || d.name_prod_category
            }))
        );
      });
    fetch(import.meta.env.VITE_API_BASE_URL + '/products/suppliers')
      .then(res => res.json())
      .then(data => setSuppliers(data.data));
    fetch(import.meta.env.VITE_API_BASE_URL + '/settings/currency')
      .then(res => res.json())
      .then(data => {
        if (data.currency) {
          setCurrencies(data.currency.map(c => ({ id: c.id_currency, name: c.name_currency })));
        }
      });
    fetch(import.meta.env.VITE_API_BASE_URL + '/settings/units')
      .then(res => res.json())
      .then(data => {
        if (data.units) {
          setUnits(data.units.map(u => ({ 
            id: u.id_unit, 
            name: u.name_unit,
            spanish_name: u.spanish_name || u.name_unit
          })));
        }
      });
  }, []);


  const getSelectedUnitName = () => {
    if (!form.unit) return '';
    const selectedUnit = units.find(u => u.id === Number(form.unit));
    return selectedUnit ? selectedUnit.name.toLowerCase() : '';
  };

  const getUnitType = () => {
    const unitName = getSelectedUnitName();
    if (unitName.includes('package') || unitName.includes('paquete')) {
      return 'package';
    }
    if (unitName.includes('pair') || unitName.includes('par')) {
      return 'pair';
    }
    if (unitName.includes('dozen') || unitName.includes('docena')) {
      return 'dozen';
    }
    return null;
  };

  useEffect(() => {
    if (!form.unit) return;
    
    const selectedUnit = units.find(u => u.id === Number(form.unit));
    if (!selectedUnit) return;
    
    const unitName = selectedUnit.name.toLowerCase();
    let calculatedStock = '';
    
    if (unitName.includes('package') || unitName.includes('paquete')) {
      if (packageQuantity && piecesPerPackage) {
        calculatedStock = (Number(packageQuantity) * Number(piecesPerPackage)).toString();
      }
    } else if (unitName.includes('pair') || unitName.includes('par')) {
      if (numberOfPairs) {
        calculatedStock = (Number(numberOfPairs) * 2).toString();
      }
    } else if (unitName.includes('dozen') || unitName.includes('docena')) {
      if (numberOfDozens) {
        calculatedStock = (Number(numberOfDozens) * 12).toString();
      }
    }
    
    if (calculatedStock) {
      setForm(prev => ({ ...prev, new_stock: calculatedStock }));
    }
  }, [packageQuantity, piecesPerPackage, numberOfPairs, numberOfDozens, form.unit, units]);

  // Manejar cambios en el formulario
  const handleChange = e => {
    const { name, value } = e.target;
    
    if (name === 'unit') {
      const newUnitType = units.find(u => u.id === Number(value));
      const newUnitName = newUnitType ? newUnitType.name.toLowerCase() : '';
      
      const isPackage = newUnitName.includes('package') || newUnitName.includes('paquete');
      const isPair = newUnitName.includes('pair') || newUnitName.includes('par');
      const isDozen = newUnitName.includes('dozen') || newUnitName.includes('docena');
      
      if (!isPackage) {
        setPackageQuantity('');
        setPiecesPerPackage('');
      }
      if (!isPair) {
        setNumberOfPairs('');
      }
      if (!isDozen) {
        setNumberOfDozens('');
      }
      
      if (!isPackage && !isPair && !isDozen) {
        setForm(prev => ({ ...prev, [name]: value, new_stock: '' }));
      } else {
        setForm(prev => ({ ...prev, [name]: value }));
      }
    } else {
      setForm(prev => ({ ...prev, [name]: value }));
    }
  };

  // Manejar imagen

  // Redimensionar imagen antes de convertir a base64
  const handleImage = e => {
    const file = e.target.files[0];
    setImageFile(file);
    if (file) {
      const img = new window.Image();
      const reader = new FileReader();
      reader.onload = ev => {
        img.onload = () => {
          // Redimensionar a 800px de ancho máximo
          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);
          // Convertir a base64 (jpeg para mayor compresión)
          const dataUrl = canvas.toDataURL('image/jpeg', 0.8); // calidad 80%
          const base64 = dataUrl.split(',')[1];
          setForm(prev => ({ ...prev, image_product: base64 }));
        };
        img.src = ev.target.result;
      };
      reader.readAsDataURL(file);
    }
  };

  // Enviar formulario
  const handleSubmit = async e => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setSuccess(false);
    try {
      // Construir payload
      const payload = {
        ...form,
        product_type: form.product_type ? [Number(form.product_type)] : [],
        new_category: form.new_category ? Number(form.new_category) : undefined,
        new_rfc_suppliers: form.new_rfc_suppliers,
        new_sku_product: form.new_sku_product ? Number(form.new_sku_product) : undefined,
        unit: form.unit ? Number(form.unit) : undefined,
        new_stock: form.new_stock ? Number(form.new_stock) : undefined,
        newprice_product: form.newprice_product ? Number(form.newprice_product) : undefined,
        new_tax: form.new_tax ? Number(form.new_tax) : undefined,
        currency: form.currency ? Number(form.currency) : undefined, // id_currency como número
      };
      // Eliminar campos vacíos
      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/newproduct', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      if (!res.ok) throw new Error('Error al guardar el producto');
      setSuccess(true);
      setForm({
        new_name_product: '', new_sku_product: '', product_type: '', new_category: '', new_rfc_suppliers: '', unit: '', new_stock: '', newprice_product: '', new_tax: '', currency: '', image_product: ''
      });
      setImageFile(null);
      setPackageQuantity('');
      setPiecesPerPackage('');
      setNumberOfPairs('');
      setNumberOfDozens('');
    } 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" ? "Nuevo producto" : "New product"}</div>
          <button
            type="button"
            className="back-button"
            onClick={() => navigate('/app/products')}
          >
            ← {lang === "es" ? "Volver" : "Back"}
          </button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="form-grid">
            <div>
              <label>{lang === "es" ? "Nombre del producto" : "Product Name"}</label>
              <input name="new_name_product" value={form.new_name_product} onChange={handleChange} required />
            </div>
            <div>
              <label>{lang === "es" ? "SKU" : "SKU"}</label>
              <input name="new_sku_product" value={form.new_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 tipo" : "Select type"}</option>
                {productTypes
                  .sort((a, b) => {
                    const nameA = lang === "en" ? a.name : a.spanish_name;
                    const nameB = lang === "en" ? b.name : b.spanish_name;
                    return nameA.localeCompare(nameB);
                  })
                  .map(pt => (
                    <option key={pt.id} value={pt.id}>
                      {lang === "en" ? pt.name : pt.spanish_name}
                    </option>
                  ))}
              </select>
            </div>
            <div>
              <label>{lang === "es" ? "Categoría" : "Category"}</label>
              <select name="new_category" value={form.new_category} onChange={handleChange} required>
                <option value="">{lang === "es" ? "Selecciona categoría" : "Select category"}</option>
                {categories
                  .sort((a, b) => {
                    const nameA = lang === "en" ? a.name : a.spanish_name;
                    const nameB = lang === "en" ? b.name : b.spanish_name;
                    return nameA.localeCompare(nameB);
                  })
                  .map(cat => (
                    <option key={cat.id} value={cat.id}>
                      {lang === "en" ? cat.name : cat.spanish_name}
                    </option>
                  ))}
              </select>
            </div>
            <div>
              <label>{lang === "es" ? "Proveedor" : "Supplier"}</label>
              <select name="new_rfc_suppliers" value={form.new_rfc_suppliers} onChange={handleChange} required>
                <option value="">{lang === "es" ? "Selecciona proveedor" : "Select supplier"}</option>
                {suppliers.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 = lang === "en" ? a.name : a.spanish_name;
                    const nameB = lang === "en" ? b.name : b.spanish_name;
                    return nameA.localeCompare(nameB);
                  })
                  .map(unit => (
                    <option key={unit.id} value={unit.id}>
                      {lang === "en" ? unit.name : unit.spanish_name}
                    </option>
                  ))}
              </select>
            </div>
            {getUnitType() === 'package' && (
              <>
                <div>
                  <label>{lang === "es" ? "Cantidad de paquetes" : "Package Quantity"}</label>
                  <input
                    type="number"
                    value={packageQuantity}
                    onChange={(e) => setPackageQuantity(e.target.value)}
                    required
                    min="1"
                  />
                </div>
                <div>
                  <label>{lang === "es" ? "Piezas por paquete" : "Pieces per Package"}</label>
                  <input
                    type="number"
                    value={piecesPerPackage}
                    onChange={(e) => setPiecesPerPackage(e.target.value)}
                    required
                    min="1"
                  />
                </div>
              </>
            )}
            {getUnitType() === 'pair' && (
              <div>
                <label>{lang === "es" ? "Número de pares" : "Number of Pairs"}</label>
                <input
                  type="number"
                  value={numberOfPairs}
                  onChange={(e) => setNumberOfPairs(e.target.value)}
                  required
                  min="1"
                />
              </div>
            )}
            {getUnitType() === 'dozen' && (
              <div>
                <label>{lang === "es" ? "Número de docenas" : "Number of Dozens"}</label>
                <input
                  type="number"
                  value={numberOfDozens}
                  onChange={(e) => setNumberOfDozens(e.target.value)}
                  required
                  min="1"
                />
              </div>
            )}
            <div>
              <label>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="newprice_product" value={form.newprice_product} onChange={handleChange} type="number" step="0.01" required />
            </div>
            <div>
              <label>{lang === "es" ? "Impuesto" : "Tax"}</label>
              <select name="new_tax" value={form.new_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.map(cur => (
                  <option key={cur.id} value={cur.id}>{cur.name}</option>
                ))}
              </select>
            </div>
          </div>
          <div>
            <label>{lang === "es" ? "Imagen del producto" : "Product Image"}</label>
            <input type="file" accept="image/*" onChange={handleImage} />
          </div>
          <div className="save-button-wrapper">
            <button type="submit" className="save-button" disabled={loading}>{loading ? (lang === "es" ? 'Guardando...' : 'Saving...') : (lang === "es" ? 'Guardar producto' : 'Save Product')}</button>
          </div>
          {success && <span style={{ color: 'green' }}>{lang === "es" ? '¡Producto guardado!' : 'Product saved!'}</span>}
          {error && <span style={{ color: 'red' }}>{error}</span>}
        </form>
      </div>
    </div>
  );
}

