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

export default function PayrollEmployees(){
  const {lang} = useContext(langContext);
  const [attendanceData, setAttendanceData] = useState([]);
  const [filteredRooms, setFilteredRooms] = useState([]);
  const [nameFilter, setNameFilter] = useState('');
  const [idFilter, setIdFilter] = useState('');
  const [positionFilter, setPositionFilter] = useState('');
  const [dayFilter, setDayFilter] = useState('');
  const [startDateFilter, setStartDateFilter] = useState('');
  const [endDateFilter, setEndDateFilter] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(50);

  useEffect(() => {
    async function fetchAttendance() {
      try {
        setLoading(true);
        const response = await fetch(import.meta.env.VITE_API_BASE_URL + '/employees/getattendance');
        
        if (!response.ok) {
          throw new Error('Failed to fetch attendance data');
        }
        
        const result = await response.json();
        
        const dataArray = Array.isArray(result) ? result : (result.data || []);
        
        const mappedData = dataArray.map(item => ({
          name: item.aname_emp || '',
          lastname: item.alast_name || '',
          id: item.aid_attendance || '',
          position: item.arol || '',
          date: item.adate_atten ? formatApiDate(item.adate_atten) : '',
          day: item.alaboral_day || '',
          checkintime: item.atime_atten || '',
          checkouttime: item.atime_out || '--',
          observations: item.aobservations || '--',
        }));
        
        setAttendanceData(mappedData);
        setFilteredRooms(mappedData);
      } catch (err) {
        console.error('Error fetching attendance:', err);
        setError(err.message);
        setAttendanceData([]);
        setFilteredRooms([]);
      } finally {
        setLoading(false);
      }
    }
    
    fetchAttendance();
  }, []);

  const formatApiDate = (isoDate) => {
    const date = new Date(isoDate);
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    return `${day}/${month}/${year}`;
  };

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

    if (nameFilter) {
      filtered = filtered.filter(room => 
        room.name?.toLowerCase().includes(nameFilter.toLowerCase()) ||
        room.lastname?.toLowerCase().includes(nameFilter.toLowerCase())
      );
    }

    if (idFilter) {
      filtered = filtered.filter(room => 
        room.id?.toString().includes(idFilter)
      );
    }

    if (positionFilter) {
      filtered = filtered.filter(room => 
        room.position === positionFilter
      );
    }

    if (dayFilter) {
      filtered = filtered.filter(room => 
        room.day === dayFilter
      );
    }

    if (startDateFilter || endDateFilter) {
      filtered = filtered.filter(room => {
        const roomDateParts = room.date?.split('/');
        if (!roomDateParts || roomDateParts.length !== 3) return false;
        
        const roomDate = new Date(roomDateParts[2], roomDateParts[1] - 1, roomDateParts[0]);
        
        const startDate = startDateFilter ? new Date(startDateFilter) : null;
        const endDate = endDateFilter ? new Date(endDateFilter) : null;
        
        if (startDate && endDate) {
          return roomDate >= startDate && roomDate <= endDate;
        } else if (startDate) {
          return roomDate >= startDate;
        } else if (endDate) {
          return roomDate <= endDate;
        }
        
        return true;
      });
    }

    setFilteredRooms(filtered);
    setCurrentPage(1);
  }, [nameFilter, idFilter, positionFilter, dayFilter, startDateFilter, endDateFilter, attendanceData]);

  const totalItems = filteredRooms.length;
  const totalPages = Math.ceil(totalItems / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentPageData = filteredRooms.slice(startIndex, endIndex);

  const goToPage = (page) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
    }
  };

  const goToFirstPage = () => setCurrentPage(1);
  const goToLastPage = () => setCurrentPage(totalPages);
  const goToPreviousPage = () => goToPage(currentPage - 1);
  const goToNextPage = () => goToPage(currentPage + 1);

  const getPageNumbers = () => {
    const pages = [];
    const maxPagesToShow = 5;
    
    if (totalPages <= maxPagesToShow) {
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      if (currentPage <= 3) {
        pages.push(1, 2, 3, 4, '...', totalPages);
      } else if (currentPage >= totalPages - 2) {
        pages.push(1, '...', totalPages - 3, totalPages - 2, totalPages - 1, totalPages);
      } else {
        pages.push(1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages);
      }
    }
    
    return pages;
  };

  const columns = [
    { header: lang === 'es' ? 'ID' : 'ID', key: 'id'},
  { header: lang === 'es' ? 'NOMBRE' : 'NAME', key: 'name'},
  { header: lang === 'es' ? 'APELLIDO' : 'LAST NAME', key: 'lastname'},
  { header: lang === 'es' ? 'POSICIÓN' : 'POSITION', key: 'position' },
  { header: lang === 'es' ? 'FECHA' : 'DATE', key: 'date' },
  { header: lang === 'es' ? 'DÍA' : 'DAY', key: 'day' },
  { header: lang === 'es' ? 'HORA DE ENTRADA' : 'CHECK-IN TIME', key: 'checkintime' },
];

  const uniquePositions = [...new Set(attendanceData.map(room => room.position).filter(Boolean))].sort();
  const uniqueDays = [...new Set(attendanceData.map(room => room.day).filter(Boolean))].sort();

  const clearFilters = () => {
    setNameFilter('');
    setIdFilter('');
    setPositionFilter('');
    setDayFilter('');
    setStartDateFilter('');
    setEndDateFilter('');
  };

  const exportColumns = [
    { header: lang === "es" ? "NOMBRE" : "NAME", key: 'name' },
    { header: lang === "es" ? "APELLIDO" : "LAST NAME", key: 'lastname' },
    { header: lang === "es" ? "ID" : "ID", key: 'id' },
    { header: lang === "es" ? "POSICIÓN" : "POSITION", key: 'position' },
    { header: lang === "es" ? "FECHA" : "DATE", key: 'date' },
    { header: lang === "es" ? "DÍA" : "DAY", key: 'day' },
    { header: lang === "es" ? "HORA DE ENTRADA" : "CHECK-IN TIME", key: 'checkintime' },
    { header: lang === "es" ? "HORA DE SALIDA" : "CHECK-OUT TIME", key: 'checkouttime' },
  ];

  return (
    <div className="payroll-attendance-page">
      <div className="page-header">
        <h2 className="page-title">{lang === 'es' ? 'Asistencia' : 'Attendance'}</h2>
      </div>

      {loading && (
        <div style={{ textAlign: 'center', padding: '20px', color: '#666' }}>
          {lang === 'es' ? 'Cargando datos de asistencia...' : 'Loading attendance data...'}
        </div>
      )}

      {error && (
        <div style={{ textAlign: 'center', padding: '20px', color: '#e74c3c', backgroundColor: '#fadbd8', borderRadius: '8px', marginBottom: '20px' }}>
          {lang === 'es' ? 'Error al cargar los datos: ' : 'Error loading data: '}{error}
        </div>
      )}

      {!loading && !error && (
        <>
          <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={startDateFilter}
                  onChange={(e) => setStartDateFilter(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={endDateFilter}
                  onChange={(e) => setEndDateFilter(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={dayFilter}
                onChange={(e) => setDayFilter(e.target.value)}
                className="filter-select"
              >
                <option value="">{lang === "es" ? "Todos los días" : "All Days"}</option>
                {uniqueDays.map((day, index) => (
                  <option key={index} value={day}>
                    {day}
                  </option>
                ))}
              </select>
            </div>

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

              <input
                type="text"
                placeholder={lang === 'es' ? 'Buscar por ID...' : 'Search by ID...'}
                value={idFilter}
                onChange={(e) => setIdFilter(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={filteredRooms}
          columns={exportColumns}
          filenamePrefix={lang === "es" ? "asistencia-nomina" : "attendance-payroll"}
          sheetName={lang === "es" ? "Asistencia" : "Attendance"}
        />
      </div>

          <div className="table-section">
      <Table columns={columns} data={currentPageData} />
          </div>
      
      {totalPages > 1 && (
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center', 
          marginTop: '20px',
          padding: '15px',
          backgroundColor: 'white',
          borderRadius: '8px',
          boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
            <label style={{ color: '#333', fontWeight: 'bold' }}>
              {lang === 'es' ? 'Mostrar:' : 'Show:'}
            </label>
            <select 
              value={itemsPerPage} 
              onChange={(e) => {
                setItemsPerPage(Number(e.target.value));
                setCurrentPage(1);
              }}
              style={{
                padding: '5px 10px',
                borderRadius: '4px',
                border: '1px solid #ccc',
                backgroundColor: 'white',
                cursor: 'pointer'
              }}
            >
              <option value={25}>25</option>
              <option value={50}>50</option>
              <option value={100}>100</option>
              <option value={200}>200</option>
            </select>
            <span style={{ color: '#666' }}>
              {lang === 'es' 
                ? `Mostrando ${startIndex + 1} a ${Math.min(endIndex, totalItems)} de ${totalItems} registros`
                : `Showing ${startIndex + 1} to ${Math.min(endIndex, totalItems)} of ${totalItems} records`
              }
            </span>
          </div>

          <div style={{ display: 'flex', gap: '5px', alignItems: 'center' }}>
            <button
              onClick={goToFirstPage}
              disabled={currentPage === 1}
              style={{
                padding: '8px 12px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                backgroundColor: currentPage === 1 ? '#f0f0f0' : 'white',
                cursor: currentPage === 1 ? 'not-allowed' : 'pointer',
                color: '#333',
                fontWeight: 'bold'
              }}
            >
              {'<<'}
            </button>
            
            <button
              onClick={goToPreviousPage}
              disabled={currentPage === 1}
              style={{
                padding: '8px 12px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                backgroundColor: currentPage === 1 ? '#f0f0f0' : 'white',
                cursor: currentPage === 1 ? 'not-allowed' : 'pointer',
                color: '#333',
                fontWeight: 'bold'
              }}
            >
              {'<'}
            </button>

            {getPageNumbers().map((page, index) => (
              page === '...' ? (
                <span key={`ellipsis-${index}`} style={{ padding: '8px', color: '#666' }}>...</span>
              ) : (
                <button
                  key={page}
                  onClick={() => goToPage(page)}
                  style={{
                    padding: '8px 12px',
                    border: '1px solid #ccc',
                    borderRadius: '4px',
                    backgroundColor: currentPage === page ? '#007bff' : 'white',
                    color: currentPage === page ? 'white' : '#333',
                    cursor: 'pointer',
                    fontWeight: currentPage === page ? 'bold' : 'normal',
                    minWidth: '40px'
                  }}
                >
                  {page}
                </button>
              )
            ))}

            <button
              onClick={goToNextPage}
              disabled={currentPage === totalPages}
              style={{
                padding: '8px 12px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                backgroundColor: currentPage === totalPages ? '#f0f0f0' : 'white',
                cursor: currentPage === totalPages ? 'not-allowed' : 'pointer',
                color: '#333',
                fontWeight: 'bold'
              }}
            >
              {'>'}
            </button>

            <button
              onClick={goToLastPage}
              disabled={currentPage === totalPages}
              style={{
                padding: '8px 12px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                backgroundColor: currentPage === totalPages ? '#f0f0f0' : 'white',
                cursor: currentPage === totalPages ? 'not-allowed' : 'pointer',
                color: '#333',
                fontWeight: 'bold'
              }}
            >
              {'>>'}
            </button>
          </div>
        </div>
      )}
        </>
      )}
    </div>
  );
}
