"use client"; import { useState, useRef, useEffect } from "react"; import { Search, Loader2, Sparkles, AlertCircle, ArrowRight, X } from "lucide-react"; import { runNaturalLanguageReport } from "@/lib/supabase/ai-actions"; import type { NLReportResult } from "@/lib/gemini"; interface NaturalLanguageReportsProps { className?: string; } interface HistoryEntry { id: string; query: string; result: NLReportResult; timestamp: Date; } export function NaturalLanguageReports({ className }: NaturalLanguageReportsProps) { const [query, setQuery] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [history, setHistory] = useState([]); const inputRef = useRef(null); const examples = [ "How many employees are on leave this month?", "What's our total outstanding invoice amount?", "Show me payroll trends for the last 3 months", "Who hasn't taken any leave this year?", ]; const handleSubmit = async (e?: React.FormEvent) => { e?.preventDefault(); if (!query.trim() || loading) return; setLoading(true); setError(null); try { const response = await runNaturalLanguageReport(query.trim()); 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 || "Query failed"); } return; } if (response.result) { setHistory((prev) => [ { id: Date.now().toString(), query: query.trim(), result: response.result!, timestamp: new Date(), }, ...prev, ]); } } catch (e: any) { setError(e.message || "Query failed"); } finally { setLoading(false); setQuery(""); } }; const handleExampleClick = (example: string) => { setQuery(example); inputRef.current?.focus(); }; const clearHistory = () => setHistory([]); return (
{/* Search input */}
setQuery(e.target.value)} placeholder="Ask about your business data..." className="w-full pl-12 pr-14 py-3.5 bg-white border border-gray-200 rounded-xl text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent shadow-sm" disabled={loading} />
{/* Example queries */} {history.length === 0 && !loading && (

Try asking

{examples.map((ex) => ( ))}
)} {/* Error */} {error && (

{error}

)} {/* History */} {history.length > 0 && (

Recent Queries

{history.map((entry) => (

“{entry.query}”

{entry.timestamp.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}

{entry.result.answer}

))}
)} {/* Loading inline */} {loading && (

Searching your data...

)}
); }