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

const Reports = () => {
  const [data, setData] = useState([]);
  const [month, setMonth] = useState('');

  useEffect(() => {
    // Koresha port yawe ya backend (5000)
    axios.get('http://localhost:5000/api/reports')
      .then(res => setData(res.data))
      .catch(err => console.error("Report Error:", err));
  }, []);

  const filteredData = useMemo(() => {
    return month ? data.filter(r => r.month === month) : data;
  }, [data, month]);

  const totals = useMemo(() => {
    return filteredData.reduce((acc, curr) => ({
      gross: acc.gross + (parseFloat(curr.GlossSalary) || 0),
      net: acc.net + (parseFloat(curr.NetSalary) || 0)
    }), { gross: 0, net: 0 });
  }, [filteredData]);

  return (
    <div className="p-8 bg-white min-h-screen">
      {/* HEADER SECTION */}
      <div className="border-b-2 border-blue-900 pb-6 mb-6 flex justify-between items-center print:hidden">
        <div>
          <h1 className="text-3xl font-extrabold text-blue-900 uppercase">Official Payroll Report</h1>
          <p className="text-gray-500">Consolidated Employee & Department Ledger</p>
        </div>
        <div className="flex gap-3">
          <input type="month" className="border p-2 rounded" onChange={(e) => setMonth(e.target.value)} />
          <button onClick={() => window.print()} className="bg-blue-900 text-white px-6 py-2 rounded font-bold hover:bg-blue-800">Print Report</button>
        </div>
      </div>

      {/* STATS SUMMARY */}
      <div className="grid grid-cols-2 gap-6 mb-8">
        <div className="bg-blue-50 p-6 rounded-lg border border-blue-200">
          <p className="text-blue-600 font-semibold">Total Gross Salary</p>
          <h2 className="text-3xl font-bold">${totals.gross.toFixed(2)}</h2>
        </div>
        <div className="bg-green-50 p-6 rounded-lg border border-green-200">
          <p className="text-green-600 font-semibold">Total Net Salary</p>
          <h2 className="text-3xl font-bold">${totals.net.toFixed(2)}</h2>
        </div>
      </div>

      {/* TABLE */}
      <table className="w-full border-collapse">
        <thead className="bg-gray-800 text-white">
          <tr>
            <th className="p-4 border">Employee Name</th>
            <th className="p-4 border">Department</th>
            <th className="p-4 border text-right">Gross</th>
            <th className="p-4 border text-right">Deduction</th>
            <th className="p-4 border text-right">Net Salary</th>
            <th className="p-4 border">Month</th>
          </tr>
        </thead>
        <tbody>
          {filteredData.length > 0 ? filteredData.map((r, i) => (
            <tr key={i} className="border-b hover:bg-gray-50 transition">
              <td className="p-4 border font-medium">{r.FirstName} {r.LastName}</td>
              <td className="p-4 border">{r.DepartementName || "N/A"}</td>
              <td className="p-4 border text-right">${r.GlossSalary || "0.00"}</td>
              <td className="p-4 border text-right text-red-600">-${r.TotalDeduction || "0.00"}</td>
              <td className="p-4 border text-right font-bold text-blue-900">${r.NetSalary || "0.00"}</td>
              <td className="p-4 border">{r.month || "N/A"}</td>
            </tr>
          )) : (
            <tr><td colSpan="6" className="p-6 text-center text-gray-500">No data available for this criteria.</td></tr>
          )}
        </tbody>
      </table>
    </div>
  );
};
export default Reports;