import React, { useEffect, useState, useContext } from "react";
import "../../components/Filters/Filters.css";
import "./Payroll.css";
import Table from "../../components/Table/HotelTable copy";
import { Link } from "react-router-dom";
import { langContext } from "../../context/LenguageContext";
import ExcelExportButton from "../../components/ExcelExportButton";
// import axios from 'axios';

export default function Payroll() {
  const { lang } = useContext(langContext);
  const [income, setIncome] = useState({ data: [] });
  const [dateRange, setDateRange] = useState({ from: "", to: "" });
  const [positionFilter, setPositionFilter] = useState("");
  const [areaFilter, setAreaFilter] = useState("");
  const [searchName, setSearchName] = useState("");
  // eslint-disable-next-line no-unused-vars
  const [activeEmployees, setActiveEmployees] = useState({ data: 0 });
  const [filteredContracts, setFilteredContracts] = useState([]);

  useEffect(() => {
    fetch(import.meta.env.VITE_API_BASE_URL + "/contracts/disabledcontract")
      .then((res) => {
        if (!res.ok) {
          throw new Error(`HTTP error! status: ${res.status}`);
        }
        return res.json();
      })
      .catch((err) => {
        console.warn('Failed to fetch disabled contracts:', err.message);
      });

    // Obtener el número de empleados activos desde la API
    fetch(import.meta.env.VITE_API_BASE_URL + "/employees/activeEmployees")
      .then((res) => res.json())
      .then((data) => {
        setActiveEmployees(data);
      })
      .catch(() => setActiveEmployees({ data: 0 }));
    // Obtener los contratos desde la API
    fetch(import.meta.env.VITE_API_BASE_URL + "/contracts")
      .then((res) => res.json())
      .then((data) => {
        // Si la respuesta tiene la propiedad data como array
        if (Array.isArray(data.data)) {
          setIncome(data);
          setFilteredContracts(data.data);
        } else {
          setIncome({ data: [] });
          setFilteredContracts([]);
        }
      })
      .catch(() => {
        setIncome({ data: [] });
        setFilteredContracts([]);
      });
  }, []);

  useEffect(() => {
    let filtered = [...income.data];

    filtered = filtered.filter((contract) =>
      contract.status_contract === 'Active' ||
      contract.status_contract === 'Activo' ||
      contract.status_contract === true
    );

    if (dateRange.from && dateRange.to) {
      filtered = filtered.filter((contract) => {
        const endDate = contract.contract_end?.slice(0, 10);

        if (!endDate) return false;

        // Compare date strings directly to avoid timezone issues
        return endDate >= dateRange.from && endDate <= dateRange.to;
      });
    }

    if (positionFilter) {
      filtered = filtered.filter(
        (contract) => contract.position_employee === positionFilter
      );
    }

    if (areaFilter) {
      filtered = filtered.filter(
        (contract) => contract.area_employee === areaFilter
      );
    }

    if (searchName) {
      filtered = filtered.filter((contract) =>
        contract.name_employee?.toLowerCase().includes(searchName.toLowerCase())
      );
    }

    setFilteredContracts(filtered);
  }, [dateRange, positionFilter, areaFilter, searchName, income]);

  const uniquePositions = [
    ...new Set(
      income.data.map((contract) => contract.position_employee).filter(Boolean)
    ),
  ].sort();
  const uniqueAreas = [
    ...new Set(
      income.data.map((contract) => contract.area_employee).filter(Boolean)
    ),
  ].sort();

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

    const dateOnly = dateStr.slice(0, 10);
    const [year, month, day] = dateOnly.split("-");
    return `${day}/${month}/${year}`;
  };

  const clearFilters = () => {
    setDateRange({ from: "", to: "" });
    setPositionFilter("");
    setAreaFilter("");
    setSearchName("");
  };

  const exportColumns = [
    { header: lang === "es" ? "NOMBRE" : "NAME", key: "name_employee" },
    {
      header: lang === "es" ? "POSICIÓN" : "POSITION",
      key: "position_employee",
    },
    { header: lang === "es" ? "ÁREA" : "AREA", key: "area_employee" },
    {
      header: lang === "es" ? "FIN DE CONTRATO" : "END OF CONTRACT",
      key: "contract_end",
    },
    { header: lang === "es" ? "ESTADO" : "STATUS", key: "status_contract" },
  ];

  const transformDataForExport = (data) => {
    return data.map((contract) => ({
      ...contract,
      contract_end: formatDate(contract.contract_end),
    }));
  };

  const columns = [
    {
      header: lang === "es" ? "NOMBRE" : "NAME",
      key: "name_employee",
      render: (value, row) => (
        <Link
          to={`/app/payroll/${row.id_contract}`}
          style={{
            textDecoration: "underline",
            color: "#5D1A2A",
            fontWeight: "500",
          }}
        >
          {value}
        </Link>
      ),
    },
    {
      header: lang === "es" ? "POSICIÓN" : "POSITION",
      key: "position_employee",
    },
    { header: lang === "es" ? "ÁREA" : "AREA", key: "area_employee" },
    {
      header: lang === "es" ? "FIN DE CONTRATO" : "END OF CONTRACT",
      key: "contract_end",
      render: (value) => formatDate(value),
    },
    { header: lang === "es" ? "ESTADO" : "STATUS", key: "status_contract" },
  ];

  return (
    <div className="payroll-page">
      <div className="page-header">
        <h2 className="page-title">{lang === "es" ? "Informe" : "Report"}</h2>
      </div>

      <div className="filters-section">
        <input
          type="text"
          placeholder={lang === "es" ? "Buscar por nombre" : "Search by name"}
          value={searchName}
          onChange={(e) => setSearchName(e.target.value)}
          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>

        <select
          value={positionFilter}
          onChange={(e) => setPositionFilter(e.target.value)}
          className="filter-select"
        >
          <option value="">
            {lang === "es" ? "Todas las posiciones" : "All Positions"}
          </option>
          {uniquePositions.map((position, index) => (
            <option key={index} value={position}>
              {position}
            </option>
          ))}
        </select>

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

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

      <div
        className="summary-container"
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
        }}
      >
        <div style={{ display: "flex", gap: "80px" }}>
          <div className="summary-card">
            <strong>
              {lang === "es"
                ? "Contratos por vencer"
                : "Contracts due to expire"}
            </strong>
            <div>{filteredContracts.length}</div>
          </div>
          {/*}
          <div className="summary-card">
            <strong>Active employees</strong>
            <div>{Array.isArray(activeEmployees.data) ? activeEmployees.data.filter(e => e.status === 'Active').length : 0}</div>
          </div>
          */}
        </div>
        <ExcelExportButton
          data={filteredContracts}
          columns={exportColumns}
          filenamePrefix={lang === "es" ? "informe-nomina" : "payroll-report"}
          sheetName={lang === "es" ? "Contratos" : "Contracts"}
          dataTransform={transformDataForExport}
        />
      </div>

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