"use client"; import { useState } from "react"; import { ShieldAlert, AlertTriangle, AlertCircle, Info, Loader2, RefreshCcw, X } from "lucide-react"; import { runPayrollAnomalyAnalysis } from "@/lib/supabase/ai-actions"; import type { PayrollAnomalyResult, PayslipDataForAI } from "@/lib/gemini"; interface PayrollAnomalyAlertProps { payslips: { employee_id: string; employee_name: string; job_title: string | null; gross_pay: number; net_pay: number; hours_worked: number | null; hourly_rate: number | null; }[]; period: string; } const SEVERITY_CONFIG = { low: { icon: Info, color: "text-blue-600", bg: "bg-blue-50", border: "border-blue-200" }, medium: { icon: AlertCircle, color: "text-amber-600", bg: "bg-amber-50", border: "border-amber-200" }, high: { icon: AlertTriangle, color: "text-red-600", bg: "bg-red-50", border: "border-red-200" }, }; export function PayrollAnomalyAlert({ payslips, period }: PayrollAnomalyAlertProps) { const [analyzing, setAnalyzing] = useState(false); const [result, setResult] = useState(null); const [error, setError] = useState(null); const [dismissed, setDismissed] = useState(false); const handleAnalyze = async () => { setAnalyzing(true); setError(null); try { const payslipData: PayslipDataForAI[] = payslips.map((p) => ({ employee_name: p.employee_name, job_title: p.job_title, gross_pay: p.gross_pay, net_pay: p.net_pay, hours_worked: p.hours_worked, hourly_rate: p.hourly_rate, })); const response = await runPayrollAnomalyAnalysis(payslipData, period); if (!response.success) { if (response.blocked) { setError(`You've reached your free tier limit for AI queries (${response.current}/${response.limit}). Upgrade to Pro for unlimited access.`); } else { setError(response.error || "Analysis failed"); } return; } if (response.result) { setResult(response.result); setDismissed(false); } } catch (e: any) { setError(e.message || "Analysis failed"); } finally { setAnalyzing(false); } }; if (dismissed && result && !result.hasAnomalies) return null; return (
{/* Trigger button when no result */} {!result && !analyzing && ( )} {/* Loading state */} {analyzing && (
Analyzing payroll for anomalies...
)} {/* Error state */} {error && !analyzing && (

AI Check Failed

{error}

)} {/* Result */} {result && !analyzing && (
{result.hasAnomalies ? ( ) : ( )}

{result.hasAnomalies ? "Anomalies Detected" : "No Anomalies Found"}

{result.summary}

{result.hasAnomalies && result.anomalies.length > 0 && (
{result.anomalies.map((a, i) => { const config = SEVERITY_CONFIG[a.severity] || SEVERITY_CONFIG.low; const Icon = config.icon; return (
{a.employee} — {a.description}
); })}
)}
)}
); }