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

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

  const [employees, setEmployees] = useState([]);
  const [filteredEmployees, setFilteredEmployees] = useState([]);
  const [loading, setLoading] = useState(true);
  const [dateRange, setDateRange] = useState({ from: '', to: '' });
  const [areaFilter, setAreaFilter] = useState('All');
  const [statusFilter, setStatusFilter] = useState('All');
  const [positionFilter, setPositionFilter] = useState('All');
  const [nameSearch, setNameSearch] = useState('');
  const [nssSearch, setNssSearch] = useState('');

  const areas = ['Hotel', 'Restaurant', 'Maintenance'];
  const statuses = ['Active', 'Inactive'];

  const uniquePositions = [...new Set(employees.map(emp => emp.position_employee).filter(Boolean))].sort();

  const clearFilters = () => {
    setDateRange({ from: '', to: '' });
    setAreaFilter('All');
    setStatusFilter('All');
    setPositionFilter('All');
    setNameSearch('');
    setNssSearch('');
  };


 
  useEffect(() => {
  axios
    .get(`${import.meta.env.VITE_API_BASE_URL}/employees`)
    .then((res) => {
      const fixedData = res.data.data.map(emp => {
        // Only apply the "026" fix if the date is not in ISO format
        if (emp.end_contract && typeof emp.end_contract === 'string' && 
            !emp.end_contract.includes('T') && emp.end_contract.startsWith("026")) {
          emp.end_contract = "20" + emp.end_contract;
        }
        return emp;
      });

      const groupedByRfc = fixedData.reduce((acc, emp) => {
        const rfc = emp.employee_rfc;
        if (!acc[rfc]) {
          acc[rfc] = [];
        }
        acc[rfc].push(emp);
        return acc;
      }, {});

      const uniqueEmployees = Object.values(groupedByRfc).map(contracts => {
        return contracts.sort((a, b) => {
          const dateA = new Date(a.end_contract);
          const dateB = new Date(b.end_contract);
          if (isNaN(dateA.getTime()) && isNaN(dateB.getTime())) return 0;
          if (isNaN(dateA.getTime())) return 1;
          if (isNaN(dateB.getTime())) return -1;
          return dateB - dateA;
        })[0];
      });

      setEmployees(uniqueEmployees);
      setFilteredEmployees(uniqueEmployees);
    })
    .catch((err) => console.error("Error al cargar empleados:", err))
    .finally(() => setLoading(false));
}, []);



  const columns = [
    {
      header: lang === 'es' ? 'NOMBRE' : 'NAME',
      key: 'name_employee',
      render: (text, row) => (
        <Link
          to={`/app/payroll/employee/${row.nss_employe}`}
          style={{
            textDecoration: 'underline',
            color: '#5D1A2A',
            fontWeight: '500',
          }}
        >
          {row.name_employee}
        </Link>
      ),
    },
    { header: 'NSS', key: 'nss_employe' },
    { header: lang === 'es' ? 'POSICIÓN' : 'POSITION', key: 'position_employee' },
    { header: lang === 'es' ? 'ÁREA' : 'AREA', key: 'area_employee' },
    { header: lang === 'es' ? 'TELÉFONO' : 'PHONE', key: 'phone_employee' },
    {
  header: lang === 'es' ? 'FIN DE CONTRATO' : 'END OF CONTRACT',
  key: 'end_contract',
  render: (text, row) => {
    if (!row.end_contract || row.end_contract === '' || row.end_contract === null) {
      return '—';
    }
    const date = new Date(row.end_contract);
    return isNaN(date.getTime()) ? '—' : date.toLocaleDateString(lang === 'es' ? 'es-MX' : 'en-US');
  }
}
,
    { header: lang === 'es' ? 'PAGO DIARIO' : 'DAILY PAY', key: 'daily_pay' },
    { header: lang === 'es' ? 'UNIFORMES' : 'UNIFORMS', key: 'uniforms' },
    { header: lang === 'es' ? 'ESTATUS' : 'STATUS', key: 'status' },
  ];


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

    if (areaFilter !== 'All') {
      filtered = filtered.filter(emp => emp.area_employee === areaFilter);
    }

    if (statusFilter !== 'All') {
      filtered = filtered.filter(emp => emp.status === statusFilter);
    }

    if (positionFilter !== 'All') {
      filtered = filtered.filter(emp => emp.position_employee === positionFilter);
    }

    if (nameSearch) {
      filtered = filtered.filter(emp =>
        emp.name_employee?.toLowerCase().includes(nameSearch.toLowerCase())
      );
    }

    if (nssSearch) {
      filtered = filtered.filter(emp =>
        emp.nss_employe?.toString().includes(nssSearch)
      );
    }

    if (dateRange.from && dateRange.to) {
      filtered = filtered.filter((emp) => {
        const end = new Date(emp.end_contract);
        return end >= new Date(dateRange.from) && end <= new Date(dateRange.to);
      });
    }

    setFilteredEmployees(filtered);
  }, [dateRange, areaFilter, statusFilter, positionFilter, nameSearch, nssSearch, employees]);

  const exportColumns = [
    { header: lang === 'es' ? 'NOMBRE' : 'NAME', key: 'name_employee' },
    { header: 'NSS', key: 'nss_employe' },
    { header: lang === 'es' ? 'POSICIÓN' : 'POSITION', key: 'position_employee' },
    { header: lang === 'es' ? 'ÁREA' : 'AREA', key: 'area_employee' },
    { header: lang === 'es' ? 'TELÉFONO' : 'PHONE', key: 'phone_employee' },
    { 
      header: lang === 'es' ? 'FIN DE CONTRATO' : 'END OF CONTRACT', 
      key: 'end_contract' 
    },
    { header: lang === 'es' ? 'PAGO DIARIO' : 'DAILY PAY', key: 'daily_pay' },
    { header: lang === 'es' ? 'UNIFORMES' : 'UNIFORMS', key: 'uniforms' },
    { header: lang === 'es' ? 'ESTATUS' : 'STATUS', key: 'status' },
  ];

  const transformDataForExport = (data) => {
    return data.map(emp => ({
      ...emp,
      end_contract: (!emp.end_contract || emp.end_contract === '' || emp.end_contract === null)
        ? '—'
        : (() => {
            const date = new Date(emp.end_contract);
            return isNaN(date.getTime()) 
              ? '—' 
              : date.toLocaleDateString(lang === 'es' ? 'es-MX' : 'en-US');
          })()
    }));
  };

  return (
    <div className="payroll-employees-page">
      <div className="page-header">
        <h2 className="page-title">{lang === 'es' ? 'Empleados' : 'Employees'}</h2>
      </div>

      <div className="filters-section">
        <div className="filters-row">
          <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={areaFilter}
            onChange={(e) => setAreaFilter(e.target.value)}
            className="filter-select"
          >
            <option value="All">{lang === 'es' ? 'Todas las áreas' : 'All Areas'}</option>
            {areas.map((c) => (
              <option key={c} value={c}>{c}</option>
            ))}
          </select>

          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="filter-select"
          >
            <option value="All">{lang === 'es' ? 'Todos los estatus' : 'All Statuses'}</option>
            {statuses.map((s) => (
              <option key={s} value={s}>{s}</option>
            ))}
          </select>

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

        <div className="filters-row second-row">
          <input
            type="text"
            placeholder={lang === 'es' ? 'Buscar por nombre...' : 'Search by name...'}
            value={nameSearch}
            onChange={(e) => setNameSearch(e.target.value)}
            className="filter-search"
          />

          <input
            type="text"
            placeholder={lang === 'es' ? 'Buscar por NSS...' : 'Search by NSS...'}
            value={nssSearch}
            onChange={(e) => setNssSearch(e.target.value)}
            className="filter-search"
          />

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

      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '1rem' }}>
        <ExcelExportButton
          data={filteredEmployees}
          columns={exportColumns}
          filenamePrefix={lang === 'es' ? 'empleados-nomina' : 'employees-payroll'}
          sheetName={lang === 'es' ? 'Empleados' : 'Employees'}
          dataTransform={transformDataForExport}
        />
      </div>
  
      {loading ? (
        <p>{lang === 'es' ? 'Cargando empleados...' : 'Loading employees...'}</p>
      ) : (
        <div className="table-section">
        <Table columns={columns} data={filteredEmployees} />
        </div>
      )}
    </div>
  );
}
