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

export default function ExpenseDetail() {
  const { id } = useParams();
  const { lang } = useContext(langContext);

  const [form, setForm] = useState({
    up_description: '',
    up_id_suppliers: '',
    up_request_by: '',
    up_area: '',
    up_category: '',
    up_req_date: '',
    up_deadline: '',
    up_currency: '',
    up_approbal_by:'',
    needtoapprove: true,
    amount: '',
    products: []
  });

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  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 formatDate = (isoDate) => {
    if (!isoDate) return '';
    const d = new Date(isoDate);
    return d.toISOString().slice(0, 10);
  };

  // Cargar listas de referencia (suppliers, users, areas, etc.)
  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();

        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.');
      }
    }

    fetchSelectData();
  }, []);

  // Cargar datos del gasto
  useEffect(() => {
    async function fetchExpense() {
      try {
        const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/expenses/getexpense/${id}`, {
          method: 'PUT',
        });
        const data = await res.json();

        if (!data.data || data.data.length === 0) {
          setError('No se encontraron datos del gasto.');
          setLoading(false);
          return;
        }

        const base = data.data[0];
        setForm({
          up_description: base.description_exp || '',
          up_id_suppliers: base.suppliers_id || '',
          up_request_by: base.request_by || '',
          up_area: base.id_area || '',
          up_category: base.category_exp || '',
          up_req_date: formatDate(base.request_date),
          up_deadline: formatDate(base.payment_deadline),
          up_currency: base.currency || '',
          up_approbal_by: base.approval_by || '',
          needtoapprove: base.needtoapprove !== undefined ? base.needtoapprove : true,
          amount: base.amount || '',
          products: base.products || []
        });
        setLoading(false);
      } catch (err) {
        console.error('Error cargando gasto:', err);
        setError('No se pudo cargar el gasto.');
        setLoading(false);
      }
    }

    fetchExpense();
  }, [id]);

  if (loading) return <div style={{ textAlign: 'center', padding: '20px' }}>Loading...</div>;
  if (error) return <div style={{ color: 'red', textAlign: 'center', padding: '20px' }}>{error}</div>;

  return (
    <div className="expense-detail">
      <h2>{lang === "en" ? "Detail" : "Información"} (ID: {id})</h2>

      <div className="expense-detail-grid">
        {/* Description */}
        <div>
          <label>{lang === "en" ? "Description" : "Descripción"}</label>
          <p>{form.up_description}</p>
        </div>

        {/* Supplier */}
        <div>
          <label>{lang === "en" ? "Supplier" : "Proveedor"}</label>
          <p>{suppliers.find(s => String(s.id) === String(form.up_id_suppliers))?.name || form.up_id_suppliers}</p>
        </div>

        {/* Request By */}
        <div>
          <label>{lang === "en" ? "Request by" : "Solicitado por"}</label>
          <p>{users.find(u => String(u.id) === String(form.up_request_by))?.name || form.up_request_by}</p>
        </div>

        {/* Area */}
        <div>
          <label>{lang === "en" ? "Area" : "Área"}</label>
          <p>{areas.find(a => String(a.id) === String(form.up_area))?.name || form.up_area}</p>
        </div>

        {/* Category */}
        <div>
          <label>{lang === "en" ? "Category" : "Categoría"}</label>
          <p>{categories.find(c => String(c.id) === String(form.up_category))?.name || form.up_category}</p>
        </div>

        {/* Request Date */}
        <div>
          <label>{lang === "en" ? "Request Date" : "Fecha de solicitud"}</label>
          <p>{form.up_req_date}</p>
        </div>

        {/* Payment Deadline */}
        <div>
          <label>{lang === "en" ? "Payment deadline" : "Fecha límite de pago"}</label>
          <p>{form.up_deadline}</p>
        </div>

        {/* Currency */}
        <div>
          <label>{lang === "en" ? "Currency" : "Moneda"}</label>
          <p>{currencies.find(c => String(c.id) === String(form.up_currency))?.name || form.up_currency}</p>
        </div>

        {/* Amount */}
        <div>
          <label>{lang === "en" ? "Amount" : "Importe"}</label>
          <p>{form.amount}</p>
        </div>

        {/* Needs Approval */}
        <div>
          <label>{lang === "en" ? "Needs Approval" : "Requiere aprobación"}</label>
          <p>{form.needtoapprove ? (lang === "en" ? 'Yes' : 'Sí') : (lang === "en" ? 'No' : 'No')}</p>
        </div>
      </div>

      <hr />

      {/* Products */}
      <h3>{lang === "en" ? "Products" : "Productos"}</h3>
      <div style={{ border: '1px solid #ccc', padding: '10px', marginTop: '10px' }}>
        {form.products.length > 0 ? (
          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" : "Producto"}</label>
                <p>{product.name || product.id_product}</p>
              </div>
              <div>
                <label>{lang === "en" ? "Quantity" : "Cantidad"}</label>
                <p>{product.quantity}</p>
              </div>
              <div>
                <label>{lang === "en" ? "Tax" : "Impuesto"}</label>
                <p>{taxes.find(t => String(t.id) === String(product.id_tax))?.name || product.id_tax}</p>
              </div>
            </div>
          ))
        ) : (
          <p>{lang === "en" ? "No products loaded." : "No hay productos cargados."}</p>
        )}
      </div>
    </div>
  );
}
