import React, { useEffect, useState } from 'react';
import Table from '../../components/Table/HotelTable';
import SummaryCard from '../../components/SummaryCard';
import './ReportExpense.css';
import { Link } from 'react-router-dom';
import { useContext } from 'react';
import { langContext } from '../../context/LenguageContext';
import ExcelExportButton from '../../components/ExcelExportButton';

export default function ReportExpense() {
  const { lang } = useContext(langContext);
  const [data, setData] = useState([]);

  const refreshMonthlyData = async () => {
    try {
      await fetch(`${import.meta.env.VITE_API_BASE_URL}/payment/refreshmonthly`, {
        method: 'GET'
      });
    } catch (error) {
      console.error('Error refreshing monthly data from Expenses section:', error);
    }
  };
  const [approvedDateRange, setApprovedDateRange] = useState({ from: '', to: '' });
  const [requestDateRange, setRequestDateRange] = useState({ from: '', to: '' });
  const [statusFilter, setStatusFilter] = useState('');
  const [paymentStatusFilter, setPaymentStatusFilter] = useState('');
  const [requestedByFilter, setRequestedByFilter] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('');
  const [areaFilter, setAreaFilter] = useState('');
  const [descriptionSearch, setDescriptionSearch] = useState('');

  const clearFilters = () => {
    setDescriptionSearch('');
    setStatusFilter('');
    setPaymentStatusFilter('');
    setRequestedByFilter('');
    setCategoryFilter('');
    setAreaFilter('');
    setRequestDateRange({ from: '', to: '' });
    setApprovedDateRange({ from: '', to: '' });
  };

  useEffect(() => {
    const loadData = async () => {
      await refreshMonthlyData();

      fetch(import.meta.env.VITE_API_BASE_URL + '/expenses/reportexpenses')
      .then(res => res.json())
      .then(resData => {
        const mapped = resData.data.map(item => ({
          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',
          category: item.category,
          area: item.area,
          is_monthly: item.is_monthly
        }));
        const filteredData = mapped.filter(c => c.is_monthly !== true);
        setData(filteredData);
        
      })
      .catch(err => console.error('Error loading expense report:', err));
    };

    loadData();
  }, []);

  const uniqueStatuses = [...new Set(data.map(item => item.status).filter(Boolean))].sort();
  const uniquePaymentStatuses = [...new Set(data.map(item => item.paymentStatus).filter(Boolean))].sort();
  const uniqueRequestedBy = [...new Set(data.map(item => item.requestedBy).filter(Boolean))].sort();
  const uniqueCategories = [...new Set(data.map(item => item.category).filter(Boolean))].sort();
  const uniqueAreas = [...new Set(data.map(item => item.area).filter(Boolean))].sort();

  const filteredData = data.filter((item) => {
    if (requestDateRange.from || requestDateRange.to) {
      if (!item.requestDate) return false;

      const request = new Date(item.requestDate);
      if (requestDateRange.from) {
        const from = new Date(requestDateRange.from);
        if (request < from) return false;
      }
      if (requestDateRange.to) {
        const to = new Date(requestDateRange.to);
        if (request > to) return false;
      }
    }

    if (approvedDateRange.from || approvedDateRange.to) {
      if (!item.approvedDate) return false;

      const approved = new Date(item.approvedDate);
      if (approvedDateRange.from) {
        const from = new Date(approvedDateRange.from);
        if (approved < from) return false;
      }
      if (approvedDateRange.to) {
        const to = new Date(approvedDateRange.to);
        if (approved > to) return false;
      }
    }

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

    if (paymentStatusFilter && item.paymentStatus !== paymentStatusFilter) return false;

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

    if (categoryFilter && item.category !== categoryFilter) return false;

    if (areaFilter && item.area !== areaFilter) return false;

    if (descriptionSearch && !item.description?.toLowerCase().includes(descriptionSearch.toLowerCase())) {
      return false;
    }

    return true;
  });

  const totalAmount = filteredData
    .filter(item => item.status === "Approved" && item.paymentStatus === "PAID")
    .reduce((acc, curr) => {
      return curr.totalpesos + acc;
    }, 0);

  const formatDate = (dateStr) => {
    if (!dateStr) return '';
    const [year, month, day] = dateStr.split('-');
    return `${month}/${day}/${year}`;
  };

  const columns = [
  {
    header: lang === "en" ? "EXPENSE DESCRIPTION" : "DESCRIPCIÓN DEL GASTO",
    key: 'description',
    render: (text, row) => {
      const targetUrl = row.is_monthly ? `/app/expenses/${row.id}` : `/app/expenses/edit/${row.id}`;
      return (
        <Link to={targetUrl} style={{ color: 'blue', textDecoration: 'underline' }}>
          {text}
        </Link>
      );
    },
  },
  { 
    header: lang === "en" ? "REQUEST DATE" : "FECHA DE SOLICITUD", 
    key: 'requestDate',
    render: (value) => formatDate(value)
  },
  { 
    header: lang === "en" ? "APPROVED DATE" : "FECHA DE APROBACIÓN", 
    key: 'approvedDate',
    render: (value) => formatDate(value)
  },
  { header: lang === "en" ? "REQUESTED BY" : "SOLICITADO POR", key: 'requestedBy' },
  { header: lang === "en" ? "CATEGORY" : "CATEGORÍA", key: 'category' },
  { header: lang === "en" ? "AREA" : "ÁREA", key: 'area' },
  {
    header: lang === "en" ? "AMOUNT MXN" : "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: 'paymentStatus',
    headerStyle: { textAlign: 'center' },
    render: (status) => {
      const statusClass = status.toLowerCase();
      return (
        <div style={{ display: 'flex', gap: '10px', justifyContent: 'center' }}>
          <button
            className={`status-button ${statusClass}`}
            disabled
            style={{
              cursor: 'default',
              opacity: 1,
            }}
          >
            {status.toUpperCase()}
          </button>
        </div>
      );
    },
  },
];

  const exportColumns = [
    { header: lang === "en" ? "EXPENSE DESCRIPTION" : "DESCRIPCIÓN DEL GASTO", key: 'description' },
    { 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" ? "CATEGORY" : "CATEGORÍA", key: 'category' },
    { header: lang === "en" ? "AREA" : "ÁREA", key: 'area' },
    { header: lang === "en" ? "AMOUNT MXN" : "IMPORTE", key: 'totalpesos' },
    { header: lang === "en" ? "APPROVAL STATUS" : "ESTADO DE APROBACIÓN", key: 'status' },
    { header: lang === "en" ? "PAYMENT STATUS" : "ESTADO DE PAGO", key: 'paymentStatus' },
  ];


  const pendingPaymentsCount = filteredData.filter(
    (item) => item.paymentStatus?.toLowerCase() === 'pending'
  ).length;

  const rejectedExpensesCount = filteredData.filter(
    (item) => item.status === "Rejected" && item.paymentStatus === "REJECTED"
  ).length;

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

      <div className="filters-section">
        <div className="filters-row">
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(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={paymentStatusFilter}
            onChange={(e) => setPaymentStatusFilter(e.target.value)}
            className="filter-select"
          >
            <option value="">{lang === "en" ? "All Payment Statuses" : "Todos los estados de pago"}</option>
            {uniquePaymentStatuses.map((status, index) => (
              <option key={index} value={status}>
                {status}
              </option>
            ))}
          </select>

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

          <select
            value={categoryFilter}
            onChange={(e) => setCategoryFilter(e.target.value)}
            className="filter-select"
          >
            <option value="">{lang === "en" ? "All Categories" : "Todas las categorías"}</option>
            {uniqueCategories.map((category, index) => (
              <option key={index} value={category}>
                {category}
              </option>
            ))}
          </select>

          <select
            value={areaFilter}
            onChange={(e) => setAreaFilter(e.target.value)}
            className="filter-select"
          >
            <option value="">{lang === "en" ? "All Areas" : "Todas las áreas"}</option>
            {uniqueAreas.map((area, index) => (
              <option key={index} value={area}>
                {area}
              </option>
            ))}
          </select>
        </div>

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

          <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={requestDateRange.from}
                onChange={(e) => setRequestDateRange({ ...requestDateRange, from: e.target.value })}
                className="date-input"
              />
              <input
                type="date"
                value={requestDateRange.to}
                onChange={(e) => setRequestDateRange({ ...requestDateRange, to: 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={approvedDateRange.from}
                onChange={(e) => setApprovedDateRange({ ...approvedDateRange, from: e.target.value })}
                className="date-input"
              />
              <input
                type="date"
                value={approvedDateRange.to}
                onChange={(e) => setApprovedDateRange({ ...approvedDateRange, to: e.target.value })}
                className="date-input"
              />
            </div>
          </div>

          <button
            onClick={clearFilters}
            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={parseFloat(totalAmount || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          />
          <div className="info-card">
            <h3 className="card-title">
              {lang === "en" ? "Pending Approved Payments" : "Pagos aprobados pendientes"}
            </h3>
            <div className="card-value">{pendingPaymentsCount}</div>
          </div>
          <div className="info-card">
            <h3 className="card-title">
              {lang === "en" ? "Rejected Expenses" : "Gastos rechazados"}
            </h3>
            <div className="card-value">{rejectedExpensesCount}</div>
          </div>
        </div>
        <ExcelExportButton
          data={filteredData}
          columns={exportColumns}
          filenamePrefix={lang === "en" ? "expense-report" : "reporte-gastos"}
          sheetName={lang === "en" ? "Expense Report" : "Reporte de Gastos"}
          className="export-button"
        />
      </div>

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

  );
}
