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

export default function EditExpense() {
    const { id } = useParams();
    const { lang } = useContext(langContext);
    const navigate = useNavigate();

    const [form, setForm] = useState({
      up_description: '',
      up_id_suppliers: '',
      up_request_date: '',
      up_payment_deadline: '',
      request_by: '',
      area: '',
      expense_cat: '',
      currency_id: '',
      needtoapprove: true,
      totalAmount: 0,
      subtotal: 0, //------
      products: []
    });

    const [loading, setLoading] = useState(true); // Start with loading: true
    const [success, setSuccess] = useState(false);
    const [error, setError] = useState('');
    // eslint-disable-next-line no-unused-vars
    const [savedExpense, setSavedExpense] = useState(null);

  // estados para datos de selects
  const [suppliers, setSuppliers] = useState([]);
  const [users, setUsers] = useState([]);
  const [areas, setAreas] = useState([]);
    const [categories, setCategories] = useState([]);
    const [currencies, setCurrencies] = useState([]);
    const [taxes, setTaxes] = useState([]);
    const [listproducts, setListProducts] = useState([]);

    const formatDate = (isoDate) => {
      if (!isoDate) return '';
      const d = new Date(isoDate);
      return d.toISOString().slice(0, 10);
    };

    useEffect(() => {
      async function fetchSelectData() {
        try {
          const res = await fetch(import.meta.env.VITE_API_BASE_URL + '/expenses/getinfo', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
          });
          if (!res.ok) throw new Error(`Error fetching info: ${res.status}`);
          const data = await res.json();
          // Supongo que data tiene algo como:
          // { suppliers: [...], users: [...], areas: [...], categories: [...], currencies: [...] }
          setSuppliers(data.suppliers || []);
          setUsers(data.users || []);
          setAreas(data.areas || []);
          setCategories(data.categories || []);
          setCurrencies(data.currencies || []);
          setTaxes(data.tax || []);
        } catch (err) {
          console.error('Error cargando metadata (getinfo):', err);
          setError('No se pudo cargar opciones de formulario.');
        }
      }
      // Helper para cargar opciones de selects
      const fetchOptions = (url, setter, mapFn) => {
        fetch(import.meta.env.VITE_API_BASE_URL + url)
        .then(res => res.json())
        .then(data => {
          const items = data.data || data.currency || data.categoryex || data.approve || data.request;
          if (items) {
            setter(items.map(mapFn));
          }
        })
        .catch(err => console.error(`Error fetching ${url}`, err));
      };

      const fetchExpense = async () => {
        try {
          const res = await fetch(import.meta.env.VITE_API_BASE_URL + `/expenses/getexpense/${id}`, {
            method: 'PUT',
          });

          if (!res.ok) {
            const textResponse = await res.text();
            throw new Error(`HTTP ${res.status}: ${textResponse}`);
          }

          const data = await res.json();

          if (!data.data || data.data.length === 0) {
            setError('Expense not found');
            return;
          }

          const base = data.data[0];

          let tax_id = null;

          if (base.iva > 0) {
            const tax_rate = parseFloat((base.iva / base.subtotal).toFixed(2));
            const taxMap = {
              0.16: 1,
              0.08: 2,
              0.00: 3
            };
            tax_id = taxMap[tax_rate] || null;
          }


          setForm({
            up_description: base.description_exp || '',
            up_id_suppliers: base.suppliers_id || '',
            up_request_date: formatDate(base.request_date),
            up_payment_deadline: formatDate(base.payment_deadline),
            request_by: base.request_by,
            area: base.id_area,
            expense_cat: base.category_exp,
            currency_id: base.currency,
            needtoapprove: base.needtoapprove !== undefined ? base.needtoapprove : true,
            subtotal: base.subtotal,
            up_tax: tax_id,
            iva: base.iva,
            ieps: base.ieps,
            total: base.total,
            products: base.products
          });

          setLoading(false);
        } catch (err) {
          console.error('Error fetching expense:', err);
          setError('Failed to load expense data');
          setLoading(false);
        }
      };
      /**/
      fetchExpense();
      fetchOptions('/products', setListProducts, c => ({ id: c.id_product, name: c.name_product }));
      fetchSelectData();
    }, [id]);

    const handleChange = (e) => {
      const { name, type, checked, value } = e.target;

      // Crear una copia del formulario
      const updatedForm = { ...form, [name]: type === 'checkbox' ? checked : value };

      // Inicializar valores por si están vacíos
      const subtotal = parseFloat(updatedForm.subtotal) || 0;
      const ieps = parseFloat(updatedForm.ieps) || 0;

      let ivaAmount = 0;

      // Si hay productos, recalcular desde ellos
      if (updatedForm.products.length > 0) {
        updatedForm.subtotal = updatedForm.products.reduce(
          (acc, p) => acc + (parseFloat(p.subtotal) || 0),
          0
        );

        ivaAmount = updatedForm.products.reduce(
          (acc, p) => acc + (parseFloat(p.iva) || 0),
          0
        );
      } else {
        // Si no hay productos, calcular IVA a partir del subtotal y tasa
        const taxRate = parseFloat(
          taxes.find(t => t.id === parseInt(updatedForm.up_tax))?.number || 0
        );
        ivaAmount = subtotal * taxRate;
      }

      updatedForm.iva = ivaAmount;

      // Calcular total final (subtotal + IVA + IEPS)
      updatedForm.total = subtotal + ivaAmount + ieps;

      // Actualizar estado
      setForm({
        ...updatedForm,
        iva: updatedForm.iva.toFixed(2),
        total: updatedForm.total.toFixed(2),
      });
    };


    const handleCategoryChange = (e) => {
      const { name, value } = e.target;
      const categoryValue = Number(value) || 0; // si el value es numérico
      setForm(prev => { // Clonamos el form actual
        const updatedForm = { ...prev, [name]: categoryValue };

        // Find the selected category to check its name
        const selectedCategory = categories.find(c => c.id === categoryValue);
        const isSuppliesCategory = selectedCategory && (
          selectedCategory.name === "Supplies" ||
          selectedCategory.name === "Laundry Supplies" ||
          selectedCategory.id === 1
        );

        if (isSuppliesCategory) {
          updatedForm.products = [
            {
              id_product: null,
              quantity: 1,
              unit_cost: 0,
              id_tax: null,
              total: 0
            }
          ];
          updatedForm.up_tax = "";
        } else { // Si cambia a otra categoría, vaciamos los productos
          updatedForm.products = [];
        } return updatedForm;
      });
    };

  const handleProductChange = (index, field, value) => {
    const updatedProducts = [...form.products]; // Convertir a entero si es un campo numérico esperado
    const ieps = parseFloat(form.ieps) || 0;
    const processedValue = ['unit_cost'].includes(field) ? parseFloat(value) : ['quantity', 'id_tax', 'id_product'].includes(field) ? parseInt(value) : value;
    updatedProducts[index][field] = processedValue;

    if (field === 'quantity' || field === 'unit_cost' || field === 'id_tax') {
      const qty = parseFloat(updatedProducts[index].quantity) || 0;
      const cost = parseFloat(updatedProducts[index].unit_cost) || 0;
      const taxValue = parseFloat(taxes.find(t => t.id === parseInt(updatedProducts[index].id_tax))?.number || 0);
      updatedProducts[index].subtotal = qty * cost;
      updatedProducts[index].iva = qty * cost * taxValue;
    }

    // Recalcular el amount (suma de todos los productos)
    const subtotalAmount = updatedProducts.reduce(
      (acc, p) => acc + (parseFloat(p.subtotal) || 0),
      0
    );

    // Recalcular el amount (suma de todos los productos)
    const ivaAmount = updatedProducts.reduce(
      (acc, p) => acc + (parseFloat(p.iva) || 0),
      0
    );

    setError(null);
    setSuccess(false);

    setForm(prev => ({
       ...prev,
      products: updatedProducts,
      subtotal: subtotalAmount.toFixed(2), // redondeado a 2 decimales
      iva: ivaAmount.toFixed(2), // redondeado a 2 decimales
      total: (subtotalAmount + ivaAmount + ieps).toFixed(2) // Calcular total final (subtotal + IVA + IEPS)
    }));
  };

  const handleAddProduct = () => {
    const ieps = parseFloat(form.ieps) || 0;

    // Primero, agregamos el nuevo producto
    const updatedProducts = [
      ...form.products,
      {
        id_product: null,
        quantity: 1,
        unit_cost: 0,
        id_tax: '',
        subtotal: 0,
        iva: 0
      }
    ];

    // Ahora sí, recalculamos después de agregarlo
    const subtotalAmount = updatedProducts.reduce(
      (acc, p) => acc + (parseFloat(p.subtotal) || 0),
      0
    );

    const ivaAmount = updatedProducts.reduce(
      (acc, p) => acc + (parseFloat(p.iva) || 0),
      0
    );

    setForm(prev => ({
      ...prev,
      products: updatedProducts,
      subtotal: subtotalAmount.toFixed(2),
      iva: ivaAmount.toFixed(2),
      total: (subtotalAmount + ivaAmount + ieps).toFixed(2)
    }));
  };

  const handleRemoveProduct = (index) => {
    setForm(prev => {
      const updated = [...prev.products];
      updated.splice(index, 1);

      // Recalcular el amount (suma de todos los productos)
      const subtotalAmount = updated.reduce(
        (acc, p) => acc + (parseFloat(p.subtotal) || 0),
        0
      );

      // Recalcular el amount (suma de todos los productos)
      const ivaAmount = updated.reduce(
        (acc, p) => acc + (parseFloat(p.iva) || 0),
        0
      );

      const ieps = parseFloat(prev.ieps) || 0;

      return {
        ...prev,
        products: updated,
        subtotal: subtotalAmount.toFixed(2), // redondeado a 2 decimales
        iva: ivaAmount.toFixed(2), // redondeado a 2 decimales
        total: (subtotalAmount + ivaAmount + ieps).toFixed(2) // Calcular total final (subtotal + IVA + IEPS)
      };
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setSuccess(false);
    setError('');

    try {
      const payload = {
        up_description: form.up_description,//
        suppliers_id: Number(form.up_id_suppliers), //
        up_req_date: form.up_request_date,//
        up_deadline: form.up_payment_deadline,//
        up_currency: Number(form.currency_id), //
        up_request_by: Number(form.request_by),//
        up_area: Number(form.area), //
        up_category: Number(form.expense_cat), //
        needtoapprove: form.needtoapprove,
        up_subtotal: Number(form.subtotal), //------
        up_iva: Number(form.iva), //------
        up_ieps: Number(form.ieps), //------
        up_total: Number(form.total), //
        products: form.products //
      };

      const res = await fetch(import.meta.env.VITE_API_BASE_URL + `/expenses/updateexpense/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      const text = await res.text();
      let data;
      try { data = JSON.parse(text); } catch { data = text; }

      if (!res.ok) {
        console.error('Error response:', res.status, data);
        throw new Error(`Server error ${res.status}: ${JSON.stringify(data)}`);
      }

      setSuccess(true);
      setSavedExpense(payload);

    } catch (err) {
      console.error('handleSubmit error:', err);
      setError(err.message || 'Unexpected error');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh'
      }}>
        <div>{lang === "en" ? "Loading expense data..." : "Cargando datos del gasto..."}</div>
      </div>
    );
  }

  return (
    <div className="new-expense-container">
      <div className="form-card">
        <div className="form-header">
          <div className="form-id">
            {lang === "en" ? "Edit expense (" : "Editar gasto ("}{id})
          </div>
          <button
            type="button"
            className="back-button"
            onClick={() => navigate("/app/report-expense")}
          >
            <span>←</span>
            {lang === "en" ? "Back" : "Volver"}
          </button>
        </div>

        <form onSubmit={handleSubmit}>
          <div className="form-grid">
            <div>
              <label>{lang === "en" ? "Description" : "Descripción"}</label>
              <input
                name="up_description"
                value={form.up_description}
                onChange={handleChange}
                required
              />
            </div>

            <div>
              <label>{lang === "en" ? "Supplier" : "Proveedor"}</label>
              <select
                name="up_id_suppliers"
                value={form.up_id_suppliers}
                onChange={handleChange}
                required
              >
                <option value="">{lang === "en" ? "Select supplier" : "Seleccionar proveedor"}</option>
                {suppliers
                  .sort((a, b) => {
                    const nameA = (a.name || '').toLowerCase();
                    const nameB = (b.name || '').toLowerCase();
                    return nameA.localeCompare(nameB);
                  })
                  .map(s => (
                    <option key={s.id} value={s.id}>{s.name}</option>
                  ))}
              </select>
            </div>

            <div>
              <label>{lang === "en" ? "Request by" : "Solicitado por"}</label>
              <select
                name="request_by"
                value={form.request_by}
                onChange={handleChange}
                required
              >
                <option value="">{lang === "en" ? "Select requester" : "Seleccionar solicitante"}</option>
                {users.map(u => (
                  <option key={u.id} value={u.id}>{u.name}</option>
                ))}
              </select>
            </div>

            <div>
              <label>{lang === "en" ? "Request date" : "Fecha de solicitud"}</label>
              <input
                type="date"
                name="up_request_date"
                value={form.up_request_date}
                onChange={handleChange}
                required
              />
            </div>

            <div>
              <label>{lang === "en" ? "Area" : "Área"}</label>
              <select
                name="area"
                value={form.area}
                onChange={handleChange}
                required
              >
                <option value="">{lang === "en" ? "Select area" : "Seleccionar área"}</option>
                {areas
                  .sort((a, b) => {
                    const nameA = (a.name || '').toLowerCase();
                    const nameB = (b.name || '').toLowerCase();
                    return nameA.localeCompare(nameB);
                  })
                  .map(a => (
                    <option key={a.id} value={a.id}>{a.name}</option>
                  ))}
              </select>
            </div>

            <div>
              <label>{lang === "en" ? "Category" : "Categoría"}</label>
              <select
                name="expense_cat"
                value={form.expense_cat}
                onChange={handleCategoryChange}
                required
              >
                <option value="">{lang === "en" ? "Select category" : "Seleccionar categoría"}</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(c => {
                    const displayName = lang === "en" ? (c.name || '') : (c.spanish_name || c.name || '');
                    console.log(`EditExpense - Category ${c.id}: lang=${lang}, name=${c.name}, spanish_name=${c.spanish_name}, display=${displayName}`);
                    return (
                      <option key={c.id} value={c.id}>
                        {displayName}
                      </option>
                    );
                  })}
              </select>
            </div>

            <div>
              <label>{lang === "en" ? "Payment deadline" : "Fecha límite de pago"}</label>
              <input
                type="date"
                name="up_payment_deadline"
                value={form.up_payment_deadline}
                onChange={handleChange}
                required
              />
            </div>

            <div>
              <label>{lang === "en" ? "Currency" : "Moneda"}</label>
              <select
                name="currency_id"
                value={form.currency_id}
                onChange={handleChange}
                required
              >
                <option value="">{lang === "en" ? "Select currency" : "Seleccionar moneda"}</option>
                {currencies.map(c => (
                  <option key={c.id} value={c.id}>{c.name}</option>
                ))}
              </select>
            </div>

            <div>
              <label>{"Subtotal"}</label>
              <input
                name="subtotal"
                value={form.subtotal}
                onChange={handleChange}
                type="number"
                required
                disabled={(() => {
                  const selectedCategory = categories.find(c => c.id === Number(form.expense_cat));
                  return selectedCategory && (
                    selectedCategory.name === "Supplies" ||
                    selectedCategory.name === "Laundry Supplies" ||
                    selectedCategory.id === 1
                  );
                })()}
              />
            </div>

            {(() => {
              const selectedCategory = categories.find(c => c.id === Number(form.expense_cat));
              const isSuppliesCategory = selectedCategory && (
                selectedCategory.name === "Supplies" ||
                selectedCategory.name === "Laundry Supplies" ||
                selectedCategory.id === 1
              );
              return !isSuppliesCategory;
            })() && (
            <div>
              <label>{lang === "en" ? "VAT rate:" : "Tasa de IVA:"}</label>
              <select name="up_tax"
                value={form.up_tax}
                onChange={handleChange}
                disabled={(() => {
                  const selectedCategory = categories.find(c => c.id === Number(form.expense_cat));
                  return selectedCategory && (
                    selectedCategory.name === "Supplies" ||
                    selectedCategory.name === "Laundry Supplies" ||
                    selectedCategory.id === 1
                  );
                })()}
              >
                  <option value="" disabled>{lang === "en" ? "Select Tax" : "Seleccione Impuesto"}</option>
                  {taxes.map(tax => (
                    <option key={tax.id} value={tax.id}>{tax.name}</option>
                  ))}
              </select>
            </div>
            )}

            <div>
              <label>{lang === "en" ? "VAT" : "IVA"}</label>
              <input
                name="iva"
                value={form.iva}
                onChange={handleChange}
                type="number"
                required
                disabled={(() => {
                  const selectedCategory = categories.find(c => c.id === Number(form.expense_cat));
                  return selectedCategory && (
                    selectedCategory.name === "Supplies" ||
                    selectedCategory.name === "Laundry Supplies" ||
                    selectedCategory.id === 1
                  );
                })()}
              />
            </div>

            <div>
              <label>{"IEPS"}</label>
              <input
                name="ieps"
                value={form.ieps}
                onChange={handleChange}
                type="number"
                required
              />
            </div>

            <div>
              <label>{"Total"}</label>
              <input
                name="total"
                value={form.total}
                onChange={handleChange}
                type="number"
                required
                disabled={(() => {
                  const selectedCategory = categories.find(c => c.id === Number(form.expense_cat));
                  return selectedCategory && (
                    selectedCategory.name === "Supplies" ||
                    selectedCategory.name === "Laundry Supplies" ||
                    selectedCategory.id === 1
                  );
                })()}
              />
            </div>

            {/* Need to Approve (Campo solicitado en la estructura) */}
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <label>{lang === "en" ? "Needs Approval:" : "Requiere aprobación:"}</label>
              <input
                type="checkbox"
                name="needtoapprove"
                checked={form.needtoapprove}
                onChange={handleChange}
                style={{ width: 'auto', marginLeft: '10px' }}
              />
            </div>
          </div>

          {/* Sección de Productos */}
          {(() => {
            const selectedCategory = categories.find(c => c.id === Number(form.expense_cat));
            const isSuppliesCategory = selectedCategory && (
              selectedCategory.name === "Supplies" ||
              selectedCategory.name === "Laundry Supplies" ||
              selectedCategory.id === 1
            );
            return isSuppliesCategory;
          })() && (
            <div className="add-products">
              <h3 style={{ marginTop: '20px' }}>
                {lang === "en" ? "Products" : "Productos"}
              </h3>

              <div style={{ border: '1px solid #ccc', padding: '10px', marginTop: '10px' }}>
                {form.products.map((product, index) => (
                    <div
                      key={index}
                      style={{
                        marginBottom: '10px',
                        borderBottom: '1px dotted #eee',
                        paddingBottom: '5px',
                        display: 'grid',
                        gridTemplateColumns: 'repeat(3, 1fr)',
                        gap: '10px',
                      }}
                    >
                      <div>
                        <label>{lang === "en" ? "Product ID:" : "ID Producto:"}</label>
                        <select name="product_id"
                          value={product.id_product || ""}
                          onChange={(e) => handleProductChange(index, 'id_product', e.target.value)}>
                            <option value="" disabled>{lang === "en" ? "Select Product ID" : "Seleccione ID Producto"}</option>
                            {[...listproducts].sort((a, b) => a.name.localeCompare(b.name)).map(lp => (
                              <option key={lp.id} value={lp.id}>{lp.name}</option>
                            ))}
                        </select>
                      </div>
                      <div>
                        <label>{lang === "en" ? "Quantity:" : "Cantidad:"}</label>
                        <input
                          type="number"
                          value={product.quantity}
                          onChange={(e) => handleProductChange(index, 'quantity', e.target.value)}
                          placeholder={lang === "en" ? "Quantity" : "Cantidad"}
                        />
                      </div>
                      <div>
                        <label>{lang === "en" ? "Unit Cost:" : "Precio Unitario:"}</label>
                        <input
                          type="number"
                          value={product.unit_cost}
                          onChange={(e) => handleProductChange(index, 'unit_cost', e.target.value)}
                          placeholder={lang === "en" ? "Unit Cost" : "Precio Unitario"}
                        />
                      </div>
                      <div>
                        <label>{lang === "en" ? "Tax:" : "Impuesto:"}</label>
                        <select name="product_id_tax"
                          value={product.id_tax}
                          onChange={(e) => handleProductChange(index, 'id_tax', e.target.value)}>
                            <option value="" disabled>{lang === "en" ? "Select Tax" : "Seleccione Impuesto"}</option>
                            {taxes.map(tax => (
                              <option key={tax.id} value={tax.id}>{tax.name}</option>
                            ))}
                        </select>
                      </div>

                      <div style={{ display: "flex", alignItems: "end", gap: "10px" }}>
                        <button
                          type="button"
                          onClick={() => handleRemoveProduct(index)}
                          className="save-button"
                          disabled={form.products.length <= 1}
                        >
                          {lang === "en" ? "Remove" : "Eliminar"}
                        </button>
                        {index === form.products.length - 1 && (
                          <button
                            type="button"
                            onClick={handleAddProduct}
                            className="save-button"
                          >
                            {lang === "en" ? "Add Product" : "Agregar producto"}
                          </button>
                        )}
                      </div>
                    </div>
                  ))}
              </div>
            </div>
          )}

          {/* Botón de Actualización que dispara la petición PUT */}
          <div style={{ marginTop: '30px', textAlign: 'center' }}>
            <button
              type="submit"
              style={{
                padding: '10px 20px',
                fontSize: '16px',
                backgroundColor: '#007bff',
                color: 'white',
                border: 'none',
                borderRadius: '5px',
                cursor: 'pointer',
              }}
            >
              {lang === "en" ? "Update Expense 💾" : "Actualizar gasto 💾"}
            </button>
          </div>

          {success && (
            <span style={{ color: 'green' }}>
              {lang === "en" ? "Expense saved successfully!" : "¡Gasto guardado con éxito!"}
            </span>
          )}
          {error && <span style={{ color: 'red' }}>{error}</span>}
        </form>
      </div>
    </div>
  );
}
