import { useState } from "react";
import { getMonthlyPayrollReport } from "../api/reportApi";

function ReportsPage() {
  const [month, setMonth] = useState("");
  const [rows, setRows] = useState([]);
  const [message, setMessage] = useState("");

  const loadReport = async () => {
    setMessage("");
    const monthValue = month.trim();
    if (monthValue && !/^\d{4}-(0[1-9]|1[0-2])$/.test(monthValue)) {
      setMessage("Month must use YYYY-MM format");
      return;
    }
    try {
      const response = await getMonthlyPayrollReport(monthValue);
      setRows(response.data);
      if (!response.data.length) {
        setMessage("No payroll found for this month");
      }
    } catch (error) {
      setMessage(error.response?.data?.message || "Failed to generate report");
    }
  };

  const formatNumber = (n) => {
    const num = Number(n);
    if (Number.isNaN(num)) return "—";
    return num.toLocaleString();
  };

  const calculateStats = () => {
    const totalGross = rows.reduce((acc, r) => acc + Number(r.grossSalary || 0), 0);
    const totalDeductions = rows.reduce((acc, r) => acc + Number(r.totalDeduction || 0), 0);
    const totalNet = rows.reduce((acc, r) => acc + Number(r.netSalary || 0), 0);
    const avgNet = rows.length > 0 ? Math.round(totalNet / rows.length) : 0;
    return { totalGross, totalDeductions, totalNet, avgNet };
  };

  const stats = calculateStats();

  return (
    <div className="space-y-4">
      <div className="ui-card p-5">
        <div className="rounded-xl bg-gradient-to-r from-orange-600 via-orange-600 to-red-700 p-4">
          <h1 className="text-2xl font-bold text-white">Payroll Reports</h1>
          <p className="mt-1 text-sm text-orange-50">Generate and view monthly payroll reports</p>
        </div>
      </div>

      <section className="ui-card p-5">
        <h2 className="mb-4 text-lg font-semibold text-blue-900">📊 Generate Report</h2>
        <div className="flex flex-wrap gap-3 items-end">
          <div className="flex-1 min-w-[200px]">
            <label className="block text-sm font-medium text-blue-900 mb-2">Select Month</label>
            <input
              type="month"
              className="ui-input w-full"
          value={month}
          onChange={(event) => setMonth(event.target.value)}
        />
          </div>
          <button
            type="button"
            onClick={loadReport}
            className="ui-btn ui-btn-primary h-10"
          >
            Generate Report
          </button>
      </div>

        {message && (
          <div className={`mt-3 rounded-lg p-3 text-sm ${
            message.includes('No payroll')
              ? 'bg-yellow-50 text-yellow-700 ring-1 ring-yellow-200'
              : 'bg-red-50 text-red-700 ring-1 ring-red-200'
          }`}>
            {message}
          </div>
        )}
      </section>

      {rows.length > 0 && (
        <div className="grid gap-4 md:grid-cols-4">
          <div className="ui-card p-4 bg-gradient-to-br from-blue-50 to-blue-100 ring-1 ring-blue-200">
            <div className="text-xs font-semibold text-blue-700">Total Gross</div>
            <div className="mt-2 text-2xl font-bold text-blue-900">{formatNumber(stats.totalGross)}</div>
            <div className="mt-1 text-xs text-blue-600">{rows.length} records</div>
          </div>
          <div className="ui-card p-4 bg-gradient-to-br from-red-50 to-red-100 ring-1 ring-red-200">
            <div className="text-xs font-semibold text-red-700">Total Deductions</div>
            <div className="mt-2 text-2xl font-bold text-red-900">{formatNumber(stats.totalDeductions)}</div>
          </div>
          <div className="ui-card p-4 bg-gradient-to-br from-green-50 to-green-100 ring-1 ring-green-200">
            <div className="text-xs font-semibold text-green-700">Total Net Salary</div>
            <div className="mt-2 text-2xl font-bold text-green-900">{formatNumber(stats.totalNet)}</div>
          </div>
          <div className="ui-card p-4 bg-gradient-to-br from-purple-50 to-purple-100 ring-1 ring-purple-200">
            <div className="text-xs font-semibold text-purple-700">Average Net Salary</div>
            <div className="mt-2 text-2xl font-bold text-purple-900">{formatNumber(stats.avgNet)}</div>
          </div>
        </div>
      )}

      {rows.length > 0 && (
        <section className="ui-card p-5">
          <h2 className="mb-4 text-lg font-semibold text-blue-900">📋 Report Details</h2>
          <div className="ui-table-wrap">
            <table className="ui-table">
              <thead>
                <tr>
              <th className="p-2 text-left">Month</th>
              <th className="p-2 text-left">First Name</th>
              <th className="p-2 text-left">Last Name</th>
              <th className="p-2 text-left">Position</th>
              <th className="p-2 text-left">Department</th>
                                <th className="p-2 text-right">Gross</th>
                                <th className="p-2 text-right">Deduction</th>
              <th className="p-2 text-right">Net Salary</th>
            </tr>
              </thead>
              <tbody>
                {rows.map((item) => (
                  <tr key={item.id}>
                <td className="p-2">{item.month}</td>
                <td className="p-2">{item.firstName}</td>
                <td className="p-2">{item.lastName}</td>
                <td className="p-2">{item.position}</td>
                <td className="p-2">{item.department}</td>
                    <td className="p-2 text-right font-medium text-blue-700">{formatNumber(item.grossSalary)}</td>
                    <td className="p-2 text-right font-medium text-red-700">{formatNumber(item.totalDeduction)}</td>
                    <td className="p-2 text-right font-bold text-green-700">{formatNumber(item.netSalary)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </section>
      )}

      {!rows.length && !message && (
        <div className="ui-card p-12 text-center">
          <div className="text-4xl mb-3">📅</div>
          <h3 className="text-lg font-semibold text-slate-700 mb-1">No Report Generated</h3>
          <p className="text-slate-600">Select a month above and click "Generate Report" to view payroll data</p>
        </div>
      )}
    </div>
  );
}

export default ReportsPage;
