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

export default function PayrollContract(){
  const { lang } = useContext(langContext);
  
  const [contracts, setContracts] = useState([]);
  const [filteredContracts, setFilteredContracts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  const [areaFilter, setAreaFilter] = useState('All');
  const [statusFilter, setStatusFilter] = useState('All');
  const [dateRange, setDateRange] = useState({ from: '', to: '' });

  useEffect(() => {
    setLoading(true);
    fetch(import.meta.env.VITE_API_BASE_URL + "/contracts")
      .then((res) => {
        if (!res.ok) throw new Error('Failed to fetch contracts');
        return res.json();
      })
      .then((data) => {
        if (Array.isArray(data.data)) {
          setContracts(data.data);
          setFilteredContracts(data.data);
        } else {
          setContracts([]);
          setFilteredContracts([]);
        }
        setError(null);
      })
      .catch((err) => {
        console.error("Error fetching contracts:", err);
        setError(err.message);
        setContracts([]);
        setFilteredContracts([]);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

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

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

    if (statusFilter && statusFilter !== 'All') {
      filtered = filtered.filter(
        (contract) => contract.status_contract === statusFilter
      );
    }

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

    setFilteredContracts(filtered);
  }, [areaFilter, statusFilter, dateRange, contracts]);

  const uniqueAreas = [
    ...new Set(
      contracts.map((contract) => contract.area_employee).filter(Boolean)
    ),
  ].sort();
  
  const uniqueStatuses = [
    ...new Set(
      contracts.map((contract) => contract.status_contract).filter(Boolean)
    ),
  ].sort();

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

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

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

  const exportColumns = [
    { header: lang === "es" ? "ID" : "ID", key: "id_contract" },
    { 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" ? "INICIO DE CONTRATO" : "START OF CONTRACT", key: "contract_start" },
    { header: lang === "es" ? "FIN DE CONTRATO" : "END OF CONTRACT", key: "contract_end" },
    { header: lang === "es" ? "ESTADO" : "STATUS", key: "status_contract" },
  ];

  const dataTransform = (data) => {
    return data.map((row) => ({
      ...row,
      contract_start: formatDate(row.contract_start),
      contract_end: formatDate(row.contract_end),
    }));
  };

  return (
    <div className="payroll-contract-page">
      <div className="page-header">
        <h2 className="page-title">
          {lang === "en" ? "Contracts" : "Contratos"}
        </h2>
        </div>

      {loading && <p>{lang === "en" ? "Loading..." : "Cargando..."}</p>}
      {error && <p style={{ color: 'red' }}>{lang === "en" ? `Error: ${error}` : `Error: ${error}`}</p>}

      {!loading && !error && (
        <>
          <div className="filters-section">
            <div className="date-input-group">
              <label className="date-label">{lang === "en" ? "From:" : "Desde:"}</label>
              <input
                className="date-input"
                type="date"
                value={dateRange.from}
                onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
              />
            </div>

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

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

            <select
              className="filter-select"
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
            >
              <option value="All">{lang === "en" ? "All Status" : "Todos los Estados"}</option>
              {uniqueStatuses.map((status) => (
                <option key={status} value={status}>{status}</option>
              ))}
            </select>

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

      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '15px' }}>
        <ExcelExportButton
          data={filteredContracts}
          columns={exportColumns}
          filenamePrefix={lang === "es" ? "contratos-nomina" : "payroll-contracts"}
          sheetName={lang === "es" ? "Contratos de Nómina" : "Payroll Contracts"}
          dataTransform={dataTransform}
        />
      </div>

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