"use client";
import { API, authFetch } from "@/lib/api";

import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { CheckCircle2, Clock, AlertTriangle, ArrowRight, Wallet } from "lucide-react";

const MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

export function RecentActivity() {
  const [payrolls, setPayrolls] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    authFetch(`${API}/dashboard/payroll`)
      .then(res => { if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json(); })
      .then(data => {
        const list = Array.isArray(data) ? data : (data?.payrolls ?? []);
        list.sort((a: any, b: any) => b.year !== a.year ? b.year - a.year : b.month - a.month);
        setPayrolls(list.slice(0, 8));
        setIsLoading(false);
      })
      .catch(err => {
        console.error(err);
        setIsLoading(false);
      });
  }, []);

  const fmtMoney = (n: number) =>
    `Rs ${Number(n).toLocaleString("en-PK", { maximumFractionDigits: 0 })}`;

  const statusInfo = (status: string) => {
    if (status === "PAID") return { icon: CheckCircle2, bg: "bg-green-100", color: "text-green-600", label: "Paid" };
    if (status === "PENDING") return { icon: Clock, bg: "bg-yellow-100", color: "text-yellow-600", label: "Pending" };
    return { icon: AlertTriangle, bg: "bg-red-100", color: "text-red-600", label: status };
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5, delay: 0.4 }}
      className="rounded-2xl bg-white p-6 shadow-sm border border-[#E2E8F0]"
    >
      <div className="mb-5 flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-gray-900">Payroll Alerts</h2>
          <p className="text-sm text-gray-500">Recent disbursements & pending runs</p>
        </div>
        <a href="/dashboard/payroll" className="text-sm font-medium text-brand-600 hover:text-brand-700 transition-colors flex items-center gap-1">
          View all <ArrowRight className="h-4 w-4" />
        </a>
      </div>

      {isLoading ? (
        <div className="space-y-3">
          {[...Array(4)].map((_, i) => (
            <div key={i} className="h-12 rounded-lg bg-gray-100 animate-pulse" />
          ))}
        </div>
      ) : payrolls.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-10 text-center">
          <Wallet className="h-8 w-8 text-gray-300 mb-2" />
          <p className="text-sm text-gray-400">No payroll records found</p>
        </div>
      ) : (
        <ul className="divide-y divide-gray-100">
          {payrolls.map((p, i) => {
            const { icon: Icon, bg, color, label } = statusInfo(p.status);
            return (
              <li key={p.id ?? i} className="flex items-center gap-3 py-3">
                <div className={`flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full ${bg}`}>
                  <Icon className={`h-4 w-4 ${color}`} />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-gray-900 truncate">
                    {MONTHS[(p.month ?? 1) - 1]} {p.year}
                  </p>
                  <p className="text-xs text-gray-400">{p.employeeCount ?? 0} employees · {fmtMoney(p.netSalary ?? 0)}</p>
                </div>
                <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${bg} ${color}`}>
                  {label}
                </span>
              </li>
            );
          })}
        </ul>
      )}
    </motion.div>
  );
}

