import React, { useState, useEffect, useRef, useContext } from "react";
import { useNavigate, useParams, useLocation } from "react-router-dom";
import { langContext } from "../../context/LenguageContext";
import "./NewIncome.css";

export default function NewIncome() {
  const navigate = useNavigate();
  const { id } = useParams();
  const location = useLocation();
  const { lang } = useContext(langContext);
  const isEditMode = Boolean(id);
  
  const [form, setForm] = useState({
    account_id: "",
    date: "",
    amount: "",
    invoice: "",
    categories: [],
  });

  const [loading, setLoading] = useState(false);
  const [loadingData, setLoadingData] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const [accounts, setAccounts] = useState([]);
  const [categoryOptions, setCategoryOptions] = useState([]);
  const [invoiceOptions, setInvoiceOptions] = useState([]);
  const [invoiceSearchTerm, setInvoiceSearchTerm] = useState("");
  const [showInvoiceDropdown, setShowInvoiceDropdown] = useState(false);
  const [filteredInvoices, setFilteredInvoices] = useState([]);
  const [isAmountDisabled, setIsAmountDisabled] = useState(false);
  
  const invoiceInputRef = useRef(null);
  const invoiceDropdownRef = useRef(null);

  const taxOptions = [
    { value: 0, label: "0%" },
    { value: 8, label: "8%" },
    { value: 16, label: "16%" },
  ];

  useEffect(() => {
    async function fetchAccounts() {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/incomeshrx/accountincome`);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const result = await response.json();
        const data = Array.isArray(result) ? result : (result.data || []);
        setAccounts(data);
      } catch (err) {
        console.error('Error fetching accounts:', err);
        setAccounts([]);
      }
    }
    fetchAccounts();
  }, []);

  useEffect(() => {
    async function fetchCategories() {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/incomeshrx/categoryincome`);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const result = await response.json();
        const data = Array.isArray(result) ? result : (result.data || []);
        setCategoryOptions(data);
      } catch (err) {
        console.error('Error fetching categories:', err);
        setCategoryOptions([]);
      }
    }
    fetchCategories();
  }, []);

  useEffect(() => {
    async function fetchInvoices() {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/incomeshrx/invoiceIncome`);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const result = await response.json();
        const data = Array.isArray(result) ? result : (result.data || []);
        setInvoiceOptions(data);
      } catch (err) {
        console.error('Error fetching invoices:', err);
        setInvoiceOptions([]);
      }
    }
    fetchInvoices();
  }, []);

  useEffect(() => {
    if (invoiceSearchTerm.trim() === "") {
      setFilteredInvoices(invoiceOptions);
    } else {
      const filtered = invoiceOptions.filter((invoice) =>
        invoice.name_inv_income.toLowerCase().includes(invoiceSearchTerm.toLowerCase())
      );
      setFilteredInvoices(filtered);
    }
  }, [invoiceSearchTerm, invoiceOptions]);

  useEffect(() => {
    function handleClickOutside(event) {
      if (
        invoiceInputRef.current &&
        !invoiceInputRef.current.contains(event.target) &&
        invoiceDropdownRef.current &&
        !invoiceDropdownRef.current.contains(event.target)
      ) {
        setShowInvoiceDropdown(false);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  useEffect(() => {
    if (!isEditMode) {
      setForm({
        account_id: "",
        date: "",
        amount: "",
        invoice: "",
        categories: [{
          categoryType: "",
          amount: "",
          selectedTax: null,
          total: "0.00",
        }],
      });
      setInvoiceSearchTerm("");
      setSuccess(false);
      setError("");
    }
  }, [isEditMode]);

  const calculateSelectedTax = (amount, tax) => {
    if (!amount || amount === 0) return null;
    
    const taxPercentage = Math.round((tax / amount) * 100);
    const availableTaxes = [16, 8, 0];
    
    for (const taxValue of availableTaxes) {
      if (taxPercentage === taxValue) {
        return taxValue;
      }
    }

    return null;
  };

  useEffect(() => {
    if (!isEditMode || !id) return;

    const navigationData = location.state?.incomeData;

    if (navigationData) {
      try {
        setLoadingData(true);
        setError("");
        

        const formattedDate = navigationData.date
          ? new Date(navigationData.date).toISOString().slice(0, 10)
            : "";
          
        const mappedCategories = navigationData.categories?.map((cat) => {
            const catAmount = parseFloat(cat.amount) || 0;
            const catTax = parseFloat(cat.tax) || 0;
            const selectedTax = calculateSelectedTax(catAmount, catTax);
            
            return {
              categoryType: String(cat.id_category || cat.id_cat_income || ""),
              amount: String(cat.amount || ""),
              selectedTax: selectedTax,
              total: String(cat.total || "0.00"),
            };
          }) || [{
            categoryType: "",
            amount: "",
            selectedTax: null,
            total: "0.00",
          }];

        const invoiceString = navigationData.invoices;
        let matchedInvoice = null;
        let isAmountDisabled = false;

        if (invoiceString && invoiceOptions.length > 0) {
          matchedInvoice = invoiceOptions.find(
            (inv) => String(inv.id_inv_income) === invoiceString ||
                    inv.name_inv_income === invoiceString
            );

          if (matchedInvoice) {
            isAmountDisabled = true;
            setInvoiceSearchTerm(matchedInvoice.name_inv_income);
          } else {
            isAmountDisabled = false;
            setInvoiceSearchTerm(invoiceString);
          }
        }

        setIsAmountDisabled(isAmountDisabled);

        const selectedAccount = accounts.find(
          (acc) => acc.name_acc_income === navigationData.account
        );
        const accountId = selectedAccount ? String(selectedAccount.id_acc_income) : "";

        setForm({
          account_id: accountId,
          date: formattedDate,
          amount: String(navigationData.amount || ""),
          invoice: invoiceString || "",
          categories: mappedCategories,
        });

      } catch (err) {
        console.error("Error processing navigation data:", err);
        setError(lang === "en" ? "Failed to load income data for editing." : "Error al cargar datos del ingreso para editar.");
      } finally {
        setLoadingData(false);
      }
    } else {
      console.warn("No navigation data found, this shouldn't happen");
      setError(lang === "en" ? "No data available for editing." : "No hay datos disponibles para editar.");
      setLoadingData(false);
    }
  }, [isEditMode, id, invoiceOptions, accounts, location.state, lang]);

  const isAccountCash = () => {
    if (!form.account_id) return false;
    const selectedAccount = accounts.find(
      (acc) => String(acc.id_acc_income) === String(form.account_id)
    );
    return selectedAccount?.name_acc_income === "CASH";
  };

  const getCurrentAccountName = () => {
    if (!form.account_id) return "";
    const selectedAccount = accounts.find(
      (acc) => String(acc.id_acc_income) === String(form.account_id)
    );
    return selectedAccount?.name_acc_income || "";
  };

  const getFilteredAccounts = () => {
    if (isEditMode) {
      const currentAccountName = getCurrentAccountName();
      if (currentAccountName === "STRIPE") {
        return accounts;
      }
      return accounts.filter((account) => account.name_acc_income !== "STRIPE");
    } else {
      return accounts.filter((account) => account.name_acc_income !== "STRIPE");
    }
  };

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

  const handleInvoiceInputChange = (e) => {
    const value = e.target.value;
    setInvoiceSearchTerm(value);
    setShowInvoiceDropdown(true);
    
    const matchedInvoice = invoiceOptions.find(
      (inv) => String(inv.id_inv_income) === value ||
              inv.name_inv_income === value
    );

    if (matchedInvoice) {
      setForm((prev) => ({
        ...prev,
        invoice: String(matchedInvoice.name_inv_income)
      }));
    } else {
      setForm((prev) => ({
        ...prev,
        invoice: value,
        ...(isEditMode ? {} : { amount: "" })
      }));
    }
    
    if (error) setError("");
  };

  const handleInvoiceSelect = (invoice) => {
    setForm((prev) => ({
      ...prev,
      invoice: String(invoice.name_inv_income)
    }));
    setInvoiceSearchTerm(invoice.name_inv_income);
    setShowInvoiceDropdown(false);
    if (error) setError("");
  };

  const handleInvoiceFocus = () => {
    setShowInvoiceDropdown(true);
  };

  const handleCategoryChange = (index, field, value) => {
    const updatedCategories = [...form.categories];
    updatedCategories[index][field] = value;

    if (field === "amount" || field === "selectedTax") {
      const amount = parseFloat(updatedCategories[index].amount) || 0;
      const selectedTax = updatedCategories[index].selectedTax;
      const taxPercentage = selectedTax ? selectedTax / 100 : 0;
      const taxAmount = amount * taxPercentage;
      const total = amount + taxAmount;

      updatedCategories[index].total = total.toFixed(2);
    }

    if (!isEditMode) {
      const newTotalIncome = updatedCategories.reduce((total, category) => {
        return total + (parseFloat(category.total) || 0);
      }, 0);

      setForm((prev) => ({
        ...prev,
        categories: updatedCategories,
        amount: newTotalIncome.toFixed(2),
      }));
    } else {
      setForm((prev) => ({
        ...prev,
        categories: updatedCategories,
      }));
    }

    if (error) setError("");
  };

  const handleAddCategory = () => {
    const newCategory = {
      categoryType: "",
      amount: "",
      selectedTax: null,
      total: "0.00",
    };

    setForm((prev) => {
      const updatedCategories = [...prev.categories, newCategory];

      if (!isEditMode) {
        const newTotalIncome = updatedCategories.reduce((total, category) => {
          return total + (parseFloat(category.total) || 0);
        }, 0);

        return {
          ...prev,
          categories: updatedCategories,
          amount: newTotalIncome.toFixed(2),
        };
      } else {
        return {
          ...prev,
          categories: updatedCategories,
        };
      }
    });
  };

  const handleRemoveCategory = (index) => {
    if (form.categories.length > 1) {
      setForm((prev) => {
        const updatedCategories = prev.categories.filter((_, i) => i !== index);

        if (!isEditMode) {
          const newTotalIncome = updatedCategories.reduce((total, category) => {
            return total + (parseFloat(category.total) || 0);
          }, 0);

          return {
            ...prev,
            categories: updatedCategories,
            amount: newTotalIncome.toFixed(2),
          };
        } else {
          return {
            ...prev,
            categories: updatedCategories,
          };
        }
      });
    }
  };

  const calculateTotalIncome = () => {
    return form.categories
      .reduce((total, category) => {
        return total + (parseFloat(category.total) || 0);
      }, 0)
      .toFixed(2);
  };

  const isUpdateButtonEnabled = () => {
    if (!isEditMode) return true;

    const totalIncome = parseFloat(calculateTotalIncome());
    const amountValue = parseFloat(form.amount) || 0;
    const difference = Math.abs(totalIncome - amountValue);

    return difference <= 2;
  };

  useEffect(() => {
    if (form.categories.length === 0) {
      setForm((prev) => ({
        ...prev,
        categories: [
          {
            categoryType: "",
            amount: "",
            selectedTax: null,
            total: "0.00",
          },
        ],
        amount: "0.00",
      }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const validateForm = () => {
    if (!form.account_id) {
      setError(lang === 'en' ? "Account is required" : "La cuenta es requerida");
      return false;
    }
    if (!form.date) {
      setError(lang === 'en' ? "Date is required" : "La fecha es requerida");
      return false;
    }
    if (!isAccountCash() && (!form.amount || parseFloat(form.amount) <= 0)) {
      setError(lang === 'en' ? "Amount must be a positive number" : "El monto debe ser un número positivo");
      return false;
    }
    if (!isAccountCash() && !form.invoice) {
      setError(lang === 'en' ? "Invoice is required" : "La factura es requerida");
      return false;
    }

    if (form.categories.length === 0) {
      setError(lang === 'en' ? "At least one category is required" : "Se requiere al menos una categoría");
      return false;
    }

    for (let i = 0; i < form.categories.length; i++) {
      const category = form.categories[i];
      if (!category.categoryType) {
        setError(lang === 'en'
          ? `Category ${i + 1}: Category type is required`
          : `Categoría ${i + 1}: El tipo de categoría es requerido`);
        return false;
      }
      if (!category.amount || parseFloat(category.amount) <= 0) {
        setError(lang === 'en'
          ? `Category ${i + 1}: Amount must be a positive number`
          : `Categoría ${i + 1}: El monto debe ser un número positivo`);
        return false;
      }
    }

    if (!isAccountCash() && isEditMode) {
      const totalIncome = parseFloat(calculateTotalIncome());
      const amountValue = parseFloat(form.amount) || 0;
      const difference = Math.abs(totalIncome - amountValue);

      if (difference > 2) {
        setError(lang === 'en'
          ? "The total income is not the same as the Amount input value"
          : "El ingreso total no es igual al valor del campo Monto");
        return false;
      }
    }

    return true;
  };

  const formatDateForAPI = (dateStr) => {
    if (!dateStr) return "";
    return dateStr;
  };

  const formatDateForUpdate = (dateStr) => {
    if (!dateStr) return "";
    return dateStr;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    setLoading(true);
    setError("");

    try {
      const formattedCategories = form.categories.map((cat) => {
        const amount = parseFloat(cat.amount) || 0;
        const selectedTax = cat.selectedTax || 0;
        const taxPercentage = selectedTax / 100;
        const taxAmount = amount * taxPercentage;
        const total = amount + taxAmount;

        return {
          id_category: parseInt(cat.categoryType) || 0,
          amount: amount,
          tax: parseFloat(taxAmount.toFixed(2)),
          total: parseFloat(total.toFixed(2)),
        };
      });

      let response;

      if (isEditMode) {

        const payload = {
          account_id: parseInt(form.account_id),
          amount: parseFloat(form.amount),
          up_date: formatDateForUpdate(form.date),
          up_invoice: form.invoice && form.invoice.trim() ? form.invoice : null,
          categories: formattedCategories,
        };



        response = await fetch(
          `${import.meta.env.VITE_API_BASE_URL}/incomeshrx/updateincome/${id}`,
          {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
          }
        );
      } else {

        const payload = {
          account_id: parseInt(form.account_id),
          amount: parseFloat(form.amount),
          new_date: formatDateForAPI(form.date),
          newinvoice: form.invoice && form.invoice.trim() ? form.invoice : null,
          categories: formattedCategories,
        };


        response = await fetch(
          `${import.meta.env.VITE_API_BASE_URL}/incomeshrx/newincome`,
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
          }
        );
      }

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
      }

      setSuccess(true);
      
      if (!isEditMode) {
        setForm({
          account_id: "",
          date: "",
          amount: "",
          invoice: "",
          categories: [],
        });
        setInvoiceSearchTerm("");
      }
    } catch (err) {
      console.error("Error submitting income:", err);
      setError(err.message || (lang === "en" ? "Failed to submit income. Please try again." : "Error al enviar el ingreso. Por favor inténtelo de nuevo."));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="new-income-container">
      <div className="form-card">
        <div className="form-header">
          <h1>{isEditMode ? (lang === "en" ? "Edit Income" : "Editar Ingreso") : (lang === "en" ? "New Income" : "Nuevo Ingreso")}</h1>
          <button
            type="button"
            className="back-button"
            onClick={() => navigate("/app/new-income-report")}
          >
            <span>←</span>
            {lang === "en" ? "Back" : "Volver"}
          </button>
        </div>

        {success && (
          <div className="success-message">
            {isEditMode
              ? (lang === "en" ? "Income updated successfully!" : "¡Ingreso actualizado exitosamente!")
              : (lang === "en" ? "Income submitted successfully!" : "¡Ingreso enviado exitosamente!")}
          </div>
        )}

        {error && <div className="error-message">{error}</div>}

        {loadingData ? (
          <div style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            padding: '40px',
            color: '#666'
          }}>
            <div style={{
              width: '40px',
              height: '40px',
              border: '4px solid #f3f3f3',
              borderTop: '4px solid #5D1A2A',
              borderRadius: '50%',
              animation: 'spin 1s linear infinite'
            }} />
            <style>{`
              @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
              }
            `}</style>
            <span style={{ marginLeft: '12px' }}>{lang === "en" ? "Loading income data..." : "Cargando datos del ingreso..."}</span>
          </div>
        ) : (
        <form onSubmit={handleSubmit}>
          <div className="form-grid">
            <div className="form-group">
              <label htmlFor="account_id">{lang === "en" ? "Account *" : "Cuenta *"}</label>
              <select
                id="account_id"
                name="account_id"
                value={form.account_id}
                onChange={handleChange}
                required
                disabled={isEditMode}
                style={isEditMode ? { backgroundColor: '#f5f5f5', cursor: 'not-allowed' } : {}}
              >
                <option value="">{lang === "en" ? "Select Account" : "Seleccionar Cuenta"}</option>
                {getFilteredAccounts().map((account) => (
                  <option key={account.id_acc_income} value={account.id_acc_income}>
                    {account.name_acc_income}
                  </option>
                ))}
              </select>
            </div>

            <div className="form-group">
              <label htmlFor="date">{lang === "en" ? "Date *" : "Fecha *"}</label>
              <input
                type="date"
                id="date"
                name="date"
                value={form.date}
                onChange={handleChange}
                disabled={isEditMode}
                required
              />
            </div>

            <div className="form-group">
              <label htmlFor="amount">
                {lang === "en" ? "Amount" : "Monto"}{!isAccountCash() && '*'}
              </label>
              <input
                type="number"
                id="amount"
                name="amount"
                value={form.amount}
                onChange={handleChange}
                placeholder="0.00"
                step="0.01"
                min="0"
                required={!isAccountCash()}
                disabled={true}
                style={isEditMode && isAmountDisabled ? { backgroundColor: '#f5f5f5', cursor: 'not-allowed' } : {}}
              />
            </div>

            <div className="form-group" style={{ position: 'relative' }}>
              <label htmlFor="invoice">
                {lang === "en" ? "Invoice" : "Factura"}{!isAccountCash() && '*'}
              </label>
              <input
                ref={invoiceInputRef}
                type="text"
                id="invoice"
                name="invoice"
                value={invoiceSearchTerm}
                onChange={handleInvoiceInputChange}
                onFocus={handleInvoiceFocus}
                placeholder={lang === "en" ? "Type to search invoice..." : "Escriba para buscar factura..."}
                required={!isAccountCash()}
                autoComplete="off"
              />
              
              {showInvoiceDropdown && (
                <div
                  ref={invoiceDropdownRef}
                  style={{
                    position: 'absolute',
                    top: '100%',
                    left: 0,
                    right: 0,
                    maxHeight: '200px',
                    overflowY: 'auto',
                    backgroundColor: 'white',
                    border: '1px solid #ccc',
                    borderRadius: '4px',
                    marginTop: '4px',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                    zIndex: 1000
                  }}
                >
                  {filteredInvoices.length > 0 ? (
                    filteredInvoices.map((invoice) => (
                      <div
                        key={invoice.id_inv_income}
                        onClick={() => handleInvoiceSelect(invoice)}
                        style={{
                          padding: '10px 12px',
                          cursor: 'pointer',
                          borderBottom: '1px solid #f0f0f0',
                          transition: 'background-color 0.2s'
                        }}
                        onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#f5f5f5'}
                        onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'white'}
                      >
                        {invoice.name_inv_income}
                      </div>
                    ))
                  ) : (
                    <div style={{ padding: '10px 12px', color: '#999', textAlign: 'center' }}>
                      {lang === "en" ? "No invoices found" : "No se encontraron facturas"}
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>

          <div className="income-categories">
            <h3 style={{ marginTop: "20px" }}>{lang === "en" ? "Income Categories" : "Categorías de Ingreso"}</h3>

            <div className="categories-container">
              {form.categories.map((category, index) => (
                <div key={index} className="category-item">
                  <div>
                    <label>{lang === "en" ? "Category Type:" : "Tipo de Categoría:"}</label>
                    <select
                      value={category.categoryType || ""}
                      onChange={(e) =>
                        handleCategoryChange(
                          index,
                          "categoryType",
                          e.target.value
                        )
                      }
                    >
                      <option value="" disabled>
                        {lang === "en" ? "Select Category Type" : "Seleccionar Tipo de Categoría"}
                      </option>
                      {categoryOptions
                        .sort((a, b) => {
                          const nameA = (a.name_category || a.name_cat_income || a.name || '').toLowerCase();
                          const nameB = (b.name_category || b.name_cat_income || b.name || '').toLowerCase();
                          return nameA.localeCompare(nameB);
                        })
                        .map((cat) => (
                          <option
                            key={cat.id_category || cat.id_cat_income || cat.id}
                            value={cat.id_category || cat.id_cat_income || cat.id}
                          >
                            {cat.name_category || cat.name_cat_income || cat.name}
                          </option>
                        ))}
                    </select>
                  </div>

                  <div>
                    <label>{lang === "en" ? "Amount:" : "Monto:"}</label>
                    <input
                      type="number"
                      value={category.amount || ""}
                      onChange={(e) =>
                        handleCategoryChange(index, "amount", e.target.value)
                      }
                      placeholder="0.00"
                      step="0.01"
                      min="0"
                    />
                  </div>

                  <div>
                    <label>{lang === "en" ? "Taxes:" : "Impuestos:"}</label>
                    <div className="taxes-container">
                      {taxOptions.map((tax) => (
                        <label key={tax.value}>
                          <input
                            type="radio"
                            name={`tax-${index}`}
                            checked={category.selectedTax === tax.value}
                            onChange={() => {
                              handleCategoryChange(
                                index,
                                "selectedTax",
                                tax.value
                              );
                            }}
                            style={{
                              width: '14px',
                              height: '14px',
                              cursor: 'pointer'
                            }}
                          />
                          {tax.label}
                        </label>
                      ))}
                    </div>
                  </div>

                  <div>
                    <label>{lang === "en" ? "Total:" : "Total:"}</label>
                    <input
                      type="text"
                      value={category.total || "0.00"}
                      readOnly
                    />
                  </div>

                  <div style={{ display: "flex", alignItems: "end" }}>
                    <button
                      type="button"
                      onClick={() => handleRemoveCategory(index)}
                      className="save-button"
                      disabled={form.categories.length <= 1}
                    >
                      {lang === "en" ? "Remove Category" : "Eliminar Categoría"}
                    </button>
                  </div>
                </div>
              ))}

              <button
                type="button"
                onClick={handleAddCategory}
                className="save-button"
              >
                {lang === "en" ? "Add Category" : "Agregar Categoría"}
              </button>
            </div>

            <div className="total-income-summary">
              <strong>{lang === "en" ? "Total Income:" : "Ingreso Total:"} ${calculateTotalIncome()}</strong>
            </div>
          </div>

          <div className="save-button-wrapper">
            <button
              type="submit"
              className={`save-button ${isEditMode && !isUpdateButtonEnabled() ? 'disabled-validation' : ''}`}
              disabled={loading || (isEditMode && !isUpdateButtonEnabled())}
            >
              {loading
                ? (isEditMode ? (lang === "en" ? "Updating..." : "Actualizando...") : (lang === "en" ? "Submitting..." : "Enviando..."))
                : (isEditMode ? (lang === "en" ? "Update Income" : "Actualizar Ingreso") : (lang === "en" ? "Save Income" : "Guardar Ingreso"))}
            </button>
          </div>
        </form>
        )}
      </div>
    </div>
  );
}
