import { useEffect, useMemo, useState } from 'react';
import axios from 'axios';

function Reports() {
  const [employees, setEmployees] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [salaries, setSalaries] = useState([]);

  const headers = { Authorization: `Bearer ${localStorage.getItem('token')}` };

  useEffect(() => {
    Promise.all([
      axios.get('http://localhost:5001/api/employees/list', { headers }),
      axios.get('http://localhost:5001/api/departments/list', { headers }),
      axios.get('http://localhost:5001/api/salaries/list', { headers }),
    ])
      .then(([empRes, deptRes, salRes]) => {
        setEmployees(empRes.data);
        setDepartments(deptRes.data);
        setSalaries(salRes.data);
      })
      .catch((err) => console.error(err));
  }, []);

  const today = new Date();
  const oneWeekAgo = new Date();
  oneWeekAgo.setDate(today.getDate() - 7);

  const salaryTotals = useMemo(() => {
    const monthly = {};
    const daily = { total: 0, count: 0 };
    const weekly = { total: 0, count: 0 };
    const departmentTotals = {};

    salaries.forEach((salary) => {
      const salaryDate = new Date(salary.createdAt || salary.updatedAt || today);
      const monthKey = salary.monthOfPayment || '';
      const netValue = Number(salary.netSalary) || 0;
      const deptName = salary.employee?.department?.departmentName || 'Unknown';

      departmentTotals[deptName] = (departmentTotals[deptName] || 0) + netValue;
      monthly[monthKey] = (monthly[monthKey] || 0) + netValue;

      if (salaryDate.toDateString() === today.toDateString()) {
        daily.total += netValue;
        daily.count += 1;
      }
      if (salaryDate >= oneWeekAgo) {
        weekly.total += netValue;
        weekly.count += 1;
      }
    });

    return { daily, weekly, monthly, departmentTotals };
  }, [salaries, today, oneWeekAgo]);

  return (
    <div>
      <h1 className="mb-6 text-2xl font-bold">Reports</h1>

      <div className="mb-6 grid gap-4 sm:grid-cols-3">
        <div className="box">
          <p className="text-sm text-gray-600">Employees</p>
          <p className="text-2xl font-bold">{employees.length}</p>
        </div>
        <div className="box">
          <p className="text-sm text-gray-600">Departments</p>
          <p className="text-2xl font-bold">{departments.length}</p>
        </div>
        <div className="box">
          <p className="text-sm text-gray-600">Salary Records</p>
          <p className="text-2xl font-bold">{salaries.length}</p>
        </div>
      </div>

      <div className="mb-6 grid gap-4 sm:grid-cols-3">
        <div className="box">
          <h2 className="mb-2 font-semibold">Today</h2>
          <p>{salaryTotals.daily.count} payments</p>
          <p className="text-sm text-gray-600">Total: {salaryTotals.daily.total}</p>
        </div>
        <div className="box">
          <h2 className="mb-2 font-semibold">Last 7 days</h2>
          <p>{salaryTotals.weekly.count} payments</p>
          <p className="text-sm text-gray-600">Total: {salaryTotals.weekly.total}</p>
        </div>
        <div className="box">
          <h2 className="mb-2 font-semibold">By Department</h2>
          {Object.keys(salaryTotals.departmentTotals).length === 0 ? (
            <p className="text-gray-600">No data</p>
          ) : (
            Object.entries(salaryTotals.departmentTotals).map(([dept, total]) => (
              <p key={dept} className="text-sm">{dept}: {total}</p>
            ))
          )}
        </div>
      </div>

      <div className="box">
        <h2 className="mb-3 font-semibold">Monthly Totals</h2>
        {Object.keys(salaryTotals.monthly).length === 0 ? (
          <p className="text-gray-600">No monthly data yet.</p>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>Month</th>
                <th>Total</th>
              </tr>
            </thead>
            <tbody>
              {Object.entries(salaryTotals.monthly).map(([month, total]) => (
                <tr key={month}>
                  <td>{month || 'Unknown'}</td>
                  <td>{total}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

export default Reports;
