"use client";
import { API, authFetch } from "@/lib/api";

import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { FileBadge, Download } from "lucide-react";
import { downloadEobiPessiReportPDF } from "@/lib/pdf";

interface SocialRecord {
  id: string;
  month: number;
  year: number;
  employee?: { firstName?: string; lastName?: string; employeeId?: string };
  eobiEmployer: number | null;
  eobiEmployee: number | null;
  pessiEmployer: number | null;
  pessiEmployee: number | null;
}

export default function EobiPessiPage() {
  const [records, setRecords] = useState<SocialRecord[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    authFetch(`${API}/dash/social-security`)
      .then((r) => r.json())
      .then((data) => { if (Array.isArray(data)) setRecords(data); })
      .catch(() => {})
      .finally(() => setIsLoading(false));
  }, []);

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">
            Social Security (EOBI & PESSI)
          </h1>
          <p className="mt-1 text-sm text-gray-500">
            Automatically calculate contributions and generate required portal formats.
          </p>
        </div>
        
        <div className="flex items-center gap-3">
          <button
            onClick={() => downloadEobiPessiReportPDF(records)}
            disabled={records.length === 0}
            className="inline-flex items-center justify-center rounded-lg border border-transparent bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-brand-700 transition-colors gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Download className="h-4 w-4" /> Export Report Monthly
          </button>
        </div>
      </div>

      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4 }}
        className="rounded-2xl bg-white shadow-sm border border-[#E2E8F0] overflow-hidden p-8"
      >
        {isLoading ? (
          <div className="flex flex-col items-center justify-center p-12 text-center">
            <p className="text-sm text-gray-500">Loading records...</p>
          </div>
        ) : records.length === 0 ? (
          <div className="flex flex-col items-center justify-center p-12 text-center">
            <div className="flex h-16 w-16 items-center justify-center rounded-full bg-blue-50 mb-4">
              <FileBadge className="h-8 w-8 text-blue-600" />
            </div>
            <h3 className="text-lg font-medium text-gray-900">No Monthly Runs Detected</h3>
            <p className="mt-1 text-sm text-gray-500 max-w-sm">
              Run the core payroll pipeline first to calculate the EOBI / PESSI employer vs employee contribution sheets.
            </p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="py-3.5 pl-6 pr-3 text-left text-sm font-semibold text-gray-900">Employee</th>
                  <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Period</th>
                  <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">EOBI Emp.</th>
                  <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">EOBI Worker</th>
                  <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">PESSI Emp.</th>
                  <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">PESSI Worker</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 bg-white">
                {records.map((r) => {
                  const months = ["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
                  return (
                    <tr key={r.id} className="hover:bg-gray-50 transition-colors">
                      <td className="whitespace-nowrap py-4 pl-6 pr-3 text-sm font-medium text-gray-900">
                        {r.employee?.firstName} {r.employee?.lastName}
                        <div className="text-xs text-gray-400 font-mono">#{r.employee?.employeeId}</div>
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{months[r.month]} {r.year}</td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-900">Rs. {(r.eobiEmployer ?? 0).toLocaleString()}</td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-900">Rs. {(r.eobiEmployee ?? 0).toLocaleString()}</td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-900">Rs. {(r.pessiEmployer ?? 0).toLocaleString()}</td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-900">Rs. {(r.pessiEmployee ?? 0).toLocaleString()}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </motion.div>
    </div>
  );
}




