import React, { useEffect, useState } from "react";
import { getReports } from "../api/reportApi";
import Layout from "../components/Layout";

const ReportsPage = ({ user, setUser }) => {
  const now = new Date();
  const [month, setMonth] = useState(now.getMonth() + 1);
  const [year, setYear] = useState(now.getFullYear());
  const [report, setReport] = useState({
    totalEmployees: 0,
    totalPayrollAmount: 0,
    totalAllowances: 0,
    totalDeductions: 0,
    payrollRecords: []
  });

  const monthNames = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

  useEffect(() => {
    const loadReport = async () => {
      const data = await getReports(month, year);
      setReport(data);
    };

    loadReport();
  }, [month, year]);

  return (
    <Layout title="Reports" user={user} setUser={setUser}>
      <div className="no-print mb-5 flex flex-col gap-3 rounded-md border border-primary p-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex gap-3">
          <select value={month} onChange={(event) => setMonth(parseInt(event.target.value))} className="rounded-md border border-primary bg-secondary p-3 outline-none">
            {monthNames.slice(1).map((name, idx) => (
              <option key={idx + 1} value={idx + 1}>{name}</option>
            ))}
          </select>
          <input type="number" min="2020" max="2030" value={year} onChange={(event) => setYear(parseInt(event.target.value))} className="w-24 rounded-md border border-primary bg-secondary p-3 outline-none" />
        </div>
        <button onClick={() => window.print()} className="rounded-md bg-primary px-5 py-3 font-semibold text-secondary">
          Print Report
        </button>
      </div>

      <h3 className="mb-4 text-xl font-bold">{monthNames[month]} {year} Payroll Report</h3>

      <section className="mb-6 grid gap-4 md:grid-cols-4">
        <div className="rounded-md border border-primary p-4">
          <p className="text-sm font-semibold">Total Employees</p>
          <p className="mt-2 text-2xl font-bold">{report.totalEmployees}</p>
        </div>
        <div className="rounded-md border border-primary p-4">
          <p className="text-sm font-semibold">Payroll Records</p>
          <p className="mt-2 text-2xl font-bold">{report.recordCount}</p>
        </div>
        <div className="rounded-md border border-primary p-4">
          <p className="text-sm font-semibold">Total Allowances</p>
          <p className="mt-2 text-2xl font-bold">{report.totalAllowances.toLocaleString()} FRW</p>
        </div>
        <div className="rounded-md border border-primary p-4">
          <p className="text-sm font-semibold">Total Deductions</p>
          <p className="mt-2 text-2xl font-bold">{report.totalDeductions.toLocaleString()} FRW</p>
        </div>
      </section>

      <section className="mb-6 grid gap-4 md:grid-cols-2">
        <div className="rounded-md border border-primary p-4">
          <p className="text-sm font-semibold">Total Payroll Amount</p>
          <p className="mt-2 text-3xl font-bold">{report.totalPayrollAmount.toLocaleString()} FRW</p>
        </div>
      </section>

      <section>
        <h3 className="mb-3 text-lg font-bold">Payroll Records</h3>
        <div className="overflow-x-auto">
          <table className="w-full min-w-[800px] border border-primary text-left text-sm">
            <thead className="bg-primary text-secondary">
              <tr>
                <th className="p-3">Employee Code</th>
                <th className="p-3">Name</th>
                <th className="p-3">Department</th>
                <th className="p-3">Basic Pay</th>
                <th className="p-3">Allowances</th>
                <th className="p-3">Deductions</th>
                <th className="p-3">Net Pay</th>
              </tr>
            </thead>
            <tbody>
              {report.payrollRecords.length === 0 ? (
                <tr className="border-t border-primary">
                  <td colSpan="7" className="p-3 text-center">No payroll records for this period</td>
                </tr>
              ) : (
                report.payrollRecords.map((record) => (
                  <tr key={record._id} className="border-t border-primary">
                    <td className="p-3">{record.employee?.employeeCode}</td>
                    <td className="p-3">{record.employee?.firstName} {record.employee?.lastName}</td>
                    <td className="p-3">{record.employee?.department}</td>
                    <td className="p-3">{Number(record.basicPay).toLocaleString()} FRW</td>
                    <td className="p-3">{Number(record.allowances).toLocaleString()} FRW</td>
                    <td className="p-3">{Number(record.deductions).toLocaleString()} FRW</td>
                    <td className="p-3 font-bold">{Number(record.netPay).toLocaleString()} FRW</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </section>
    </Layout>
  );
};

export default ReportsPage;
