import React, { useEffect, useState } from "react";
import { getEmployees } from "../api/employeeApi";
import { getPayrolls } from "../api/payrollApi";
import Layout from "../components/Layout";

const DashboardPage = ({ user, setUser }) => {
  const [summary, setSummary] = useState({
    employees: 0,
    payrollRecords: 0,
    totalPayrollAmount: 0,
    departments: 0
  });

  useEffect(() => {
    const loadSummary = async () => {
      const [employees, payrolls] = await Promise.all([
        getEmployees(),
        getPayrolls()
      ]);

      const departments = new Set(employees.map((emp) => emp.department)).size;
      const totalPayrollAmount = payrolls.reduce((sum, p) => sum + p.netPay, 0);

      setSummary({
        employees: employees.length,
        payrollRecords: payrolls.length,
        totalPayrollAmount,
        departments
      });
    };

    loadSummary();
  }, []);

  const cards = [
    { label: "Employees", value: summary.employees },
    { label: "Departments", value: summary.departments },
    { label: "Payroll Records", value: summary.payrollRecords },
    { label: "Total Payroll", value: `${summary.totalPayrollAmount.toLocaleString()} FRW` }
  ];

  return (
    <Layout title="Dashboard" user={user} setUser={setUser}>
      <section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {cards.map((card) => (
          <div key={card.label} className="rounded-md border border-primary p-5">
            <p className="text-sm font-semibold">{card.label}</p>
            <p className="mt-3 text-3xl font-bold">{card.value}</p>
          </div>
        ))}
      </section>

      <section className="mt-6 rounded-md border border-primary p-5">
        <h3 className="mb-2 text-lg font-bold">Employee Payroll Management System</h3>
        <p className="text-sm leading-6">
          This system manages employee records, processes monthly payroll and generates payroll reports
          for the organisation.
        </p>
      </section>
    </Layout>
  );
};

export default DashboardPage;
