import React, { useState, useEffect } from 'react';
import Table from '../components/Table/HotelTable';
import ConfirmationModal from '../components/Modals/ConfirmationModal';
import { Link } from 'react-router-dom';
import axios from 'axios';
import '../components/Filters/Filters.css';
import './PendingApproval.css';
import { useContext } from 'react';
import { langContext } from '../context/LenguageContext';

export default function PendingApproval() {
  const { lang } = useContext(langContext);
  const [data, setData] = useState([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [selectedStatus, setSelectedStatus] = useState(null);
  const [selectedId, setSelectedId] = useState(null);
  const [selectedStatusId, setSelectedStatusId] = useState(null);

  //Cargar datos reales al montar el componente
  useEffect(() => {
    axios.get(import.meta.env.VITE_API_BASE_URL + '/expenses/pendingapproval')
      .then((res) => {
        //Mapeamos los datos para adaptarlos a las columnas
        const formattedData = res.data.data.map(item => ({
          id: item.id_expense,
          description: item.expense_description,
          date: new Date(item.request_date).toISOString().split('T')[0], // yyyy-mm-dd
          requestedBy: item.requested_by,
          area: item.area,
          amount: `$${parseFloat(item.amount).toLocaleString()}`,
        }));

        setData(formattedData);
      })
      .catch((err) => {
        console.error("Error al obtener gastos pendientes:", err);
      });
  }, []);

  const handleOpenModal = (id, statusType, statusId) => {
    setSelectedId(id);
    setSelectedStatus(statusType);
    setSelectedStatusId(statusId);
    setModalOpen(true);
  };

  const handleConfirm = () => {
    if (!selectedId || !selectedStatus) return;

    const statusValue = selectedStatusId;

    axios.put(`${import.meta.env.VITE_API_BASE_URL}/status/approveupdate/${selectedId}`, {
      status: statusValue
    })
      .then((res) => {
        console.log(res.data.message || 'Estado actualizado correctamente');

        // Quitar el gasto aprobado/rechazado de la lista actual
        setData(prevData => prevData.filter(item => item.id !== selectedId));

        // Cerrar el modal y limpiar selección
        setModalOpen(false);
        setSelectedId(null);
        setSelectedStatus(null);
      })
      .catch((err) => {
        console.error(`Error al actualizar el estado del gasto ${selectedId}:`, err);
        alert('❌ Error al actualizar el estado. Intenta nuevamente.');
      });
  };

  const handleCancel = () => {
    setModalOpen(false);
  };

  const columns = [
    {
      header: lang === "en" ? "EXPENSE DESCRIPTION" : "DESCRIPCIÓN DEL GASTO",
      key: 'description',
      render: (text, row) => (
        <Link to={`/app/expenses/${row.id}`} style={{ color: 'blue', textDecoration: 'underline' }}>
          {text}
        </Link>
      ),
    },
    { header: lang === "en" ? "REQUEST DATE" : "FECHA DE SOLICITUD", key: 'date' },
    { header: lang === "en" ? "REQUESTED BY" : "SOLICITADO POR", key: 'requestedBy' },
    { header: lang === "en" ? "AREA" : "ÁREA", key: 'area' },
    { header: lang === "en" ? "AMOUNT" : "IMPORTE", key: 'amount' },
    {
      header: lang === "en" ? "STATUS" : "ESTADO",
      key: 'id',
      headerStyle: { textAlign: 'center' },
      render: (id) => (
        <div style={{ display: 'flex', gap: '10px', justifyContent: 'center' }}>
          <button
            className="status-badge active"
            onClick={() => handleOpenModal(id, lang === "en" ? "APPROVED" : "APROBADO", 1)}
          >
            {lang === "en" ? "APPROVE" : "APROBAR"}
          </button>
          <button
            className="status-badge reject"
            onClick={() => handleOpenModal(id, lang === "en" ? "REJECTED" : "RECHAZADO", 2)}
          >
            {lang === "en" ? "REJECT" : "RECHAZAR"}
          </button>
        </div>
      ),
    },
  ];

  return (
    <div className="pending-approval-page">
      <div className="page-header">
        <h2 className="page-title">
          {lang === "en" ? "Pending Approval" : "Aprobación Pendiente"}
        </h2>
      </div>

      <div className="table-section">
        <Table columns={columns} data={data} />
      </div>

      <ConfirmationModal
        isOpen={modalOpen}
        statusType={selectedStatus}
        onConfirm={handleConfirm}
        onCancel={handleCancel}
      />
    </div>
  );
}