import React, { useEffect, useState } from 'react';
import Table from '../../components/Table/HotelTable';
import SummaryCard from '../../components/SummaryCard';
import '../../components/Filters/Filters.css';
import { useContext } from 'react';
import { langContext } from '../../context/LenguageContext';
import ConfirmationModal from '../../components/Modals/ConfirmationModal';
import axios from 'axios';
import { Link } from 'react-router-dom';
import ExcelExportButton from '../../components/ExcelExportButton';
import './Payments.css';
 
export default function Payments() {
  const { lang } = useContext(langContext);
  const [data, setData] = useState([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [selectedStatus, setSelectedStatus] = useState('');
  const [selectedStatusId, setSelectedStatusId] = useState(null);
  const [selectedId, setSelectedId] = useState(null);
  const [filters, setFilters] = useState({
    status: '',
    requestedBy: '',
    requestDateFrom: '',
    requestDateTo: '',
    approvedDateFrom: '',
    approvedDateTo: '',
    searchTerm: ''
  });
  const loadExpenses = () => {
    fetch(import.meta.env.VITE_API_BASE_URL + '/expenses/reportexpenses')
      .then(res => res.json())
      .then(resData => {
        const mapped = resData.data.map(item => {
          return {
            id: item.id_expense,
            description: item.expense_description,
            requestDate: item.request_date?.split('T')[0],
            approvedDate: item.approval_date?.split('T')[0],
            requestedBy: item.requested_by,
            totalpesos: Number(item.totalpesos),
            status: item.status_approval,
            paymentStatus: item.status_payment,
            supplier: item.supplier || 'Unknown',
            is_monthly : item.is_monthly
          };
        });
        setData(mapped.filter(c => c.is_monthly !== true && c.status === "Approved" && c.paymentStatus === "PENDING"));
      })
      .catch(() => {});
  };

  useEffect(() => {
    loadExpenses();
  }, []);

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

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

    const statusValue = selectedStatusId;

    axios.put(`${import.meta.env.VITE_API_BASE_URL}/status/paymentupdate/${selectedId}`, {
      status: statusValue
    })
      .then(() => {
        loadExpenses();

        setModalOpen(false);
        setSelectedId(null);
        setSelectedStatus(null);
      })
      .catch(() => {
        alert('❌ Error al actualizar el estado. Intenta nuevamente.');
      });
  };

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

  const filteredData = data.filter((item) => {
    if (filters.searchTerm && (!item.description || !item.description.toLowerCase().includes(filters.searchTerm.toLowerCase()))) return false;

    if (filters.status && item.status !== filters.status) return false;

    if (filters.requestedBy && item.requestedBy !== filters.requestedBy) return false;

    if (filters.requestDateFrom || filters.requestDateTo) {
      if (!item.requestDate) return false;

      const requestDate = new Date(item.requestDate);
      if (filters.requestDateFrom) {
        const from = new Date(filters.requestDateFrom);
        if (requestDate < from) return false;
      }
      if (filters.requestDateTo) {
        const to = new Date(filters.requestDateTo);
        if (requestDate > to) return false;
      }
    }

    if (filters.approvedDateFrom || filters.approvedDateTo) {
      if (!item.approvedDate) return false;

      const approvedDate = new Date(item.approvedDate);
      if (filters.approvedDateFrom) {
        const from = new Date(filters.approvedDateFrom);
        if (approvedDate < from) return false;
      }
      if (filters.approvedDateTo) {
        const to = new Date(filters.approvedDateTo);
        if (approvedDate > to) return false;
      }
    }

    return true;
  });

  const totalAmount = filteredData
    .reduce((acc, curr) => {
      return curr.totalpesos + acc;
    }, 0);

  const uniqueStatuses = [...new Set(data.map(item => item.status))].filter(Boolean);
  const uniqueRequestedBy = [...new Set(data.map(item => item.requestedBy))].filter(Boolean);

  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: 'requestDate' },
  { header: lang === "en" ? "APPROVED DATE" : "FECHA DE APROBACIÓN", key: 'approvedDate' },
  { header: lang === "en" ? "REQUESTED BY" : "SOLICITADO POR", key: 'requestedBy' },
  {
    header: lang === "en" ? "AMOUNT" : "IMPORTE",
    key: 'totalpesos',
    render: (value) => {
      const num = parseFloat(value || 0);
      return `$${num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
    }
  },
  {
    header: lang === "en" ? "APPROVAL STATUS" : "ESTADO DE APROBACIÓN",
    key: 'status',
    headerStyle: { textAlign: 'center' },
    render: (status) => (
      <div style={{ textAlign: 'center' }}>
        <button
          className={`status-button ${status.toLowerCase()}`}
          disabled
          style={{
            cursor: 'default',
            opacity: 1,
          }}
        >
          {status.toUpperCase()}
        </button>
      </div>
    ),
  },
  {
    header: lang === "en" ? "PAYMENT STATUS" : "ESTADO DE PAGO",
    key: 'id',
    headerStyle: { textAlign: 'center' },
    render: (id) => {
      return (
        <div style={{ display: 'flex', gap: '10px', justifyContent: 'center' }}>
          <button
            className="status-badge active"
            onClick={() => handleOpenModal(id, lang === "en" ? "PAID" : "PAGADO", 1)}
          >
            {lang === "en" ? "PAID" : "PAGAR"}
          </button>
          <button
            className="status-badge reject"
            onClick={() => handleOpenModal(id, lang === "en" ? "REJECTED" : "RECHAZADO", 3)}
          >
            {lang === "en" ? "REJECTED" : "RECHAZAR"}
          </button>
        </div>
      );
    },
  },
];

  const exportColumns = columns.slice(0, -1);


  return (
    <div className="report-page">
      <div className="page-header">
        <h2 className="page-title">
          {lang === "en" ? "Payment" : "Pagos"}
        </h2>
      </div>

      <div className="page-filters">
        <div className="filters-row">
          <input
            type="text"
            placeholder={lang === "en" ? "Search by description..." : "Buscar por descripción..."}
            value={filters.searchTerm}
            onChange={(e) => setFilters({ ...filters, searchTerm: e.target.value })}
            className="filter-search"
          />

          <select
            value={filters.status}
            onChange={(e) => setFilters({ ...filters, status: e.target.value })}
            className="filter-select"
          >
            <option value="">{lang === "en" ? "All Approval Statuses" : "Todos los estados de aprobación"}</option>
            {uniqueStatuses.map((status, index) => (
              <option key={index} value={status}>
                {status}
              </option>
            ))}
          </select>

          <select
            value={filters.requestedBy}
            onChange={(e) => setFilters({ ...filters, requestedBy: e.target.value })}
            className="filter-select"
          >
            <option value="">{lang === "en" ? "All Requesters" : "Todos los solicitantes"}</option>
            {uniqueRequestedBy.map((user, index) => (
              <option key={index} value={user}>
                {user}
              </option>
            ))}
          </select>
        </div>

        <div className="filters-row second-row">
          <div className="date-filter-group">
            <label className="date-filter-label">
              {lang === "en" ? "REQUEST DATE" : "FECHA DE SOLICITUD"}
            </label>
            <div className="date-inputs">
              <input
                type="date"
                value={filters.requestDateFrom}
                onChange={(e) => setFilters({ ...filters, requestDateFrom: e.target.value })}
                className="date-input"
              />
              <input
                type="date"
                value={filters.requestDateTo}
                onChange={(e) => setFilters({ ...filters, requestDateTo: e.target.value })}
                className="date-input"
              />
            </div>
          </div>

          <div className="date-filter-group">
            <label className="date-filter-label">
              {lang === "en" ? "APPROVED DATE" : "FECHA DE APROBACIÓN"}
            </label>
            <div className="date-inputs">
              <input
                type="date"
                value={filters.approvedDateFrom}
                onChange={(e) => setFilters({ ...filters, approvedDateFrom: e.target.value })}
                className="date-input"
              />
              <input
                type="date"
                value={filters.approvedDateTo}
                onChange={(e) => setFilters({ ...filters, approvedDateTo: e.target.value })}
                className="date-input"
              />
            </div>
          </div>

          <button
            onClick={() => setFilters({
              status: '',
              requestedBy: '',
              requestDateFrom: '',
              requestDateTo: '',
              approvedDateFrom: '',
              approvedDateTo: '',
              searchTerm: ''
            })}
            className="clear-filters-btn"
          >
            {lang === "en" ? "Clear Filters" : "Limpiar Filtros"}
          </button>
        </div>
      </div>

      <div className="summary-actions-section">
        <div className="summary-cards-wrapper">
          <SummaryCard
            title={lang === "en" ? "Total Spent" : "Total Gastado"}
            amount={totalAmount}
          />
        </div>
        <ExcelExportButton
          data={filteredData}
          columns={exportColumns}
          filenamePrefix={lang === 'es' ? 'pagos' : 'payments'}
          sheetName={lang === 'es' ? 'Pagos' : 'Payments'}
          className="export-button"
        />
      </div>

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

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