import React, { useEffect, useState, useContext } from "react";
import Table from "../../components/Table/HotelTable";
import { langContext } from "../../context/LenguageContext";
import "../../components/Filters/Filters.css";
import "./MonthlyReport.css";

export default function MonthlyReport() {
  const { lang } = useContext(langContext);

  const getCurrentMonthRange = () => {
    const now = new Date();
    const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
    const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
    return {
      start: firstDay.toISOString().split("T")[0],
      end: lastDay.toISOString().split("T")[0],
    };
  };

  const currentMonth = getCurrentMonthRange();

  const [payments, setPayments] = useState([]);
  const [descriptionSearch, setDescriptionSearch] = useState("");
  const [areaFilter, setAreaFilter] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [paymentStatusFilter, setPaymentStatusFilter] = useState("");
  const [supplierFilter, setSupplierFilter] = useState("");
  const [dateRange, setDateRange] = useState({
    from: currentMonth.start,
    to: currentMonth.end,
  });

  const filteredData = payments.filter((item) => {
    const matchesDescription = item.description
      .toLowerCase()
      .includes(descriptionSearch.toLowerCase());
    const matchesArea = !areaFilter || item.area === areaFilter;
    const matchesStatus = !statusFilter || item.status === statusFilter;
    const matchesPaymentStatus =
      !paymentStatusFilter || item.paymentStatus === paymentStatusFilter;
    const matchesSupplier = !supplierFilter || item.supplier === supplierFilter;

    let matchesDateRange = true;
    if (dateRange.from || dateRange.to) {
      if (!item.date) {
        matchesDateRange = false;
      } else {
        const itemDate = new Date(item.date);
        if (dateRange.from) {
          const fromDate = new Date(dateRange.from);
          if (itemDate < fromDate) matchesDateRange = false;
        }
        if (dateRange.to) {
          const toDate = new Date(dateRange.to);
          if (itemDate > toDate) matchesDateRange = false;
        }
      }
    }

    return (
      matchesDescription &&
      matchesArea &&
      matchesStatus &&
      matchesPaymentStatus &&
      matchesSupplier &&
      matchesDateRange
    );
  });

  const uniqueAreas = [
    ...new Set(payments.map((item) => item.area).filter(Boolean)),
  ].sort();
  const uniqueStatuses = [
    ...new Set(payments.map((item) => item.status).filter(Boolean)),
  ].sort();
  const uniquePaymentStatuses = [
    ...new Set(payments.map((item) => item.paymentStatus).filter(Boolean)),
  ].sort();
  const uniqueSuppliers = [
    ...new Set(payments.map((item) => item.supplier).filter(Boolean)),
  ].sort();

  const clearFilters = () => {
    setDescriptionSearch("");
    setAreaFilter("");
    setStatusFilter("");
    setPaymentStatusFilter("");
    setSupplierFilter("");
    const currentMonth = getCurrentMonthRange();
    setDateRange({ from: currentMonth.start, to: currentMonth.end });
  };

  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:", error);
    }
  };

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

      async function fetchMonthlyPaymentsData() {
        await fetch(
          import.meta.env.VITE_API_BASE_URL + "/expenses/monthlypayments"
        )
          .then((response) => response.json())
          .then((data) => {
            const adaptedData = data.data.map((item) => ({
              id: item.id_expense,
              description: item.expense_description,
              date: new Date(item.payment_deadline).toISOString().split("T")[0],
              area: item.area.toUpperCase(),
              recurrence: item.recurrence_name,
              supplier: item.supplier,
              status: capitalizeFirstLetter(item.status),
              amount: `$${parseFloat(item.total || 0).toLocaleString()}`,
              paymentStatus: item.status_payment.toUpperCase(),
              more: {
                id: item.id_expense,
                description: item.expense_description,
                status: item.status_payment,
              },
            }));

            const groupedData = adaptedData.sort((a, b) => {
              const descCompare = a.description.localeCompare(b.description);
              if (descCompare !== 0) return descCompare;

              const areaCompare = a.area.localeCompare(b.area);
              if (areaCompare !== 0) return areaCompare;

              return 0;
            });

            setPayments(groupedData);
          })
          .catch((error) => {
            console.error("Error fetching latest expenses:", error);
          });
      }

      fetchMonthlyPaymentsData();
    };

    loadData();
  }, []);

  const columns = [
    {
      header: lang === "en" ? "EXPENSE DESCRIPTION" : "DESCRIPCIÓN DEL GASTO",
      key: "description",
    },
    {
      header: lang === "en" ? "PAYMENT DEADLINE" : "FECHA LÍMITE DE PAGO",
      key: "date",
    },
    { header: lang === "en" ? "AREA" : "ÁREA", key: "area" },
    { header: lang === "en" ? "RECURRENCE" : "RECURRENCIA", key: "recurrence" },
    { header: lang === "en" ? "SUPPLIER" : "PROVEEDOR", key: "supplier" },
    { header: lang === "en" ? "STATUS" : "ESTADO", key: "status" },
    { header: lang === "en" ? "AMOUNT" : "IMPORTE", key: "amount" },
    {
      header: lang === "en" ? "PAYMENT STATUS" : "ESTADO DE PAGO",
      key: "paymentStatus",
      headerStyle: { textAlign: "center" },
      render: (status) => (
        <div style={{ textAlign: "center" }}>
          <button className={`status-button ${status.toLowerCase()}`}>
            {status}
          </button>
        </div>
      ),
    },
  ];

  function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
  }

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

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

          <div className="date-input-group">
            <label className="date-label">
              {lang === "es" ? "Desde:" : "From:"}
            </label>
            <input
              type="date"
              value={dateRange.from}
              onChange={(e) =>
                setDateRange({ ...dateRange, from: e.target.value })
              }
              className="date-input"
            />
          </div>

          <div className="date-input-group">
            <label className="date-label">
              {lang === "es" ? "Hasta:" : "To:"}
            </label>
            <input
              type="date"
              value={dateRange.to}
              onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
              className="date-input"
            />
          </div>
        </div>

        <div className="filters-row second-row">
          <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>

          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="filter-select"
          >
            <option value="">
              {lang === "en" ? "All Statuses" : "Todos los Estados"}
            </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={supplierFilter}
            onChange={(e) => setSupplierFilter(e.target.value)}
            className="filter-select"
          >
            <option value="">
              {lang === "en" ? "All Suppliers" : "Todos los Proveedores"}
            </option>
            {uniqueSuppliers.map((supplier, index) => (
              <option key={index} value={supplier}>
                {supplier}
              </option>
            ))}
          </select>

          <button onClick={clearFilters} className="clear-filters-btn">
            {lang === "en" ? "Clear Filters" : "Limpiar Filtros"}
          </button>
        </div>
      </div>

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