import React, { useEffect, useState } from 'react';
import './NewMonthlyPayment.css';
// import '../Inventory/NewProduct.css ';
import { useContext } from 'react';
import { langContext } from '../../context/LenguageContext';


//**////** */ */  REVISAR POR QUE NO AGREGA UN NEWMONTLYEXPENSE
export default function NewMonthlyPayment() {
  const { lang } = useContext(langContext);
  const [suppliers, setSuppliers] = useState([]);
  const [recurrences, setRecurrences] = useState([]);
  const [currencies, setCurrencies] = useState([]);
  const [categories, setCategories] = useState([]);
  const [areas, setAreas] = useState([]);
  const [taxes, setTaxes] = useState([]);
  const [form, setForm] = useState({
    descriptionex: '',
    recurrence_id: "",
    payment_type: "",
    currency_id: "",
    suppliers_id: '',
    area: '',
    expense_category: '',
    day_expense: '',
    tax_id: '',
    new_subtotal: ''
  });

  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (form.payment_type === "2") {
      setForm(prev => ({
        ...prev,
        new_subtotal: '',
        tax_id: ''
      }));
    }
  }, [form.payment_type]);
  
  useEffect(() => {
    fetch(import.meta.env.VITE_API_BASE_URL + '/expenses/getinfo')
      .then(res => res.json())
      .then(data => {
        setSuppliers(data.suppliers);
        setCurrencies(data.currencies);
        setAreas(data.areas);
        setCategories(data.categories);
        setTaxes(data.tax);
      })
      .catch(err => console.error('Error fetching suppliers', err));
    fetch(import.meta.env.VITE_API_BASE_URL + '/settings/recurrence')
      .then(res => res.json())
      .then(data => setRecurrences(data.currency));
    
  }, []);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setForm(prev => ({ ...prev, [name]: value }));
  };

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

    try {
      const isVariable = Number(form.payment_type) === 2;
      
      const payload = {
        ...form,
        recurrence_id: Number(form.recurrence_id),
        payment_type: Number(form.payment_type),
        currency_id: Number(form.currency_id),
        area: Number(form.area),
        expense_category: Number(form.expense_category),
        day_expense: Number(form.day_expense),
        tax_id: isVariable ? null : form.tax_id,
        new_subtotal: isVariable ? null : form.new_subtotal
      };

      const res = await fetch(import.meta.env.VITE_API_BASE_URL + '/payment/newexpmonthly', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      if (!res.ok) throw new Error('Error al guardar el gasto mensual');

      setSuccess(true);
      setForm({
        descriptionex: '',
        recurrence_id: '',
        payment_type: '',
        currency_id: '',
        suppliers_id: '',
        area: '',
        expense_category: '',
        day_expense: '',
        amount_expense: '',
        tax_id: '',
        new_subtotal: ''
      });
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="new-expense-container">
      <div className="form-card">
        <div className="form-id">
          {lang === "en" ? "New monthly payment" : "Nuevo pago mensual"}
        </div>

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

            <div>
              <label>{lang === "en" ? "Recurrence" : "Recurrencia"}</label>
              <select name="recurrence_id" value={form.recurrence_id} onChange={handleChange}>
                <option value="">{lang === "en" ? "Select a recurrence" : "Selecciona un período"}</option>
                {
                  [...recurrences].sort((a, b) => a.name_recurrence.localeCompare(b.name_recurrence)).map(r => (
                    <option key={r.id_recurrence} value={r.id_recurrence}>
                      {r.name_recurrence}
                    </option>
                  ))
                }
              </select>
            </div>

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

            <div>
              <label>{lang === "en" ? "Payment type" : "Tipo de pago"}</label>
              <select name="payment_type" value={form.payment_type} onChange={handleChange} required>
                <option value="">{lang === "en" ? "Select payment type" : "Selecciona tipo de pago"}</option>
                <option value={1}>{lang === "en" ? "Fixed" : "Fijo"}</option>
                <option value={2}>{lang === "en" ? "Variable" : "Variable"}</option>
              </select>
            </div>

            {form.payment_type !== "2" && (
              <div>
                <label>{lang === "en" ? "Amount" : "Importe"}</label>
                <input
                  name="new_subtotal"
                  value={form.new_subtotal}
                  onChange={handleChange}
                  type="number"
                  required={form.payment_type === "1"}
                />
              </div>
            )}

            <div>
              <label>{lang === "en" ? "Supplier" : "Proveedor"}</label>
              <select
                name="suppliers_id"
                value={form.suppliers_id}
                onChange={handleChange}
                required
              >
                <option value="">
                  {lang === "en" ? "Select supplier" : "Seleccionar proveedor"}
                </option>
                {suppliers.map(s => (
                  <option key={s.id} value={s.id}>
                    {s.name}
                  </option>
                ))}
              </select>
            </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) => a.name.localeCompare(b.name)).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_category"
                value={form.expense_category}
                onChange={handleChange}
                required
              >
                <option value="">
                  {lang === "en" ? "Select category" : "Seleccionar categoría"}
                </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>

            {form.payment_type !== "2" && (
              <div>
                <label>{lang === "en" ? "Tax" : "Impuesto"}</label>
                <select
                  name="tax_id"
                  value={form.tax_id}
                  onChange={handleChange}
                  required={form.payment_type === "1"}
                >
                  <option value="">
                    {lang === "en" ? "Select tax" : "Seleccionar impuesto"}
                  </option>
                  {
                    taxes.map(t => (
                      <option key={t.id} value={t.id}>{t.name}</option>
                    ))
                  }
                </select>
              </div>
            )}

            <div>
              <label>{lang === "en" ? "Payment deadline" : "Fecha límite de pago"}</label>
              <input
                name="day_expense"
                value={form.day_expense}
                onChange={handleChange}
                type="number"
                min="1"
                max="31"
                required
              />
            </div>

          </div>

          <div className="save-button-wrapper">
            <button type="submit" className="save-button" disabled={loading}>
              {loading
                ? lang === "en" ? "Saving..." : "Guardando..."
                : lang === "en" ? "Save" : "Guardar"}
            </button>
          </div>

          {success && (
            <span style={{ color: 'green' }}>
              {lang === "en"
                ? "Monthly payment saved!"
                : "¡Pago mensual guardado!"}
            </span>
          )}

          {error && <span style={{ color: 'red' }}>{error}</span>}
        </form>
      </div>
    </div>

  );
}