import React, { useState, useEffect, useRef, useCallback } from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; import { Input } from '@/src/components/ui/Input'; import { Button } from '@/src/components/ui/Button'; import { Badge } from '@/src/components/ui/Badge'; import { Send, Bot, User, Sparkles, Loader2, X, MessageCircle, ScrollText, BookOpen, Scale, FileText, AlertTriangle, Droplets, MapPin, TrendingUp, Clock, Shield, Waves, Database, Building2, FileSearch, Search, ChevronRight, Star, ArrowRight, HelpCircle } from 'lucide-react'; import { cn } from '@/src/utils/cn'; import { getPopularGRs, mockGRs } from '@/src/data/mockGRs'; type DocumentType = 'GR' | 'Act' | 'Circular' | 'Manual' | 'SOP' | 'Report'; interface Document { id: string; title: string; type: DocumentType; date: string; department: string; relevance: number; summary?: string; } interface Insight { title: string; value: string; trend?: string; trendUp?: boolean; icon: React.ElementType; color: string; } type Message = { id: string; role: 'user' | 'assistant'; content: string; sources?: Document[]; insights?: Insight[]; timestamp?: Date; }; // Extended mock document database const mockDocuments: Document[] = [ { id: 'GR-2024-WRD-089', title: 'Flood Relief Compensation Guidelines 2024', type: 'GR', date: '2024-07-15', department: 'Relief & Rehabilitation', relevance: 95, summary: 'Compensation rates: ₹5,000/acre for crop loss, ₹95,000 for house damage' }, { id: 'GR-2024-WRD-056', title: 'Emergency Dam Safety Protocol', type: 'GR', date: '2024-06-20', department: 'Dam Safety', relevance: 92, summary: 'Mandatory 2-hour advance notification for downstream districts' }, { id: 'ACT-1976-012', title: 'Maharashtra Irrigation Act', type: 'Act', date: '1976-05-15', department: 'Legislative', relevance: 88, summary: 'Governs water distribution, irrigation rights, and canal maintenance' }, { id: 'CIRC-2024-WRD-023', title: 'Monsoon Preparedness Circular', type: 'Circular', date: '2024-05-01', department: 'Operations', relevance: 85, summary: 'Pre-monsoon checklist for all dam control rooms' }, { id: 'GR-2023-WRD-124', title: 'Dam Gate Operations SOP', type: 'SOP', date: '2023-08-10', department: 'Operations', relevance: 90, summary: 'Standard procedures for gate opening/closing with safety checks' }, { id: 'MANUAL-2024-001', title: 'Flood Management Field Manual', type: 'Manual', date: '2024-03-15', department: 'Training', relevance: 82, summary: 'Field guide for emergency response teams' }, { id: 'GR-2024-WRD-042', title: 'Water Resource Allocation Policy', type: 'GR', date: '2024-04-20', department: 'Planning', relevance: 78, summary: 'Priority: Drinking > Agriculture > Industrial use' }, { id: 'ACT-2005-WRD-003', title: 'MWRRA Act', type: 'Act', date: '2005-08-12', department: 'Legislative', relevance: 75, summary: 'Regulatory authority for water pricing and distribution' }, { id: 'CIRC-2024-WRD-015', title: 'Real-time Monitoring Guidelines', type: 'Circular', date: '2024-04-10', department: 'IT & Operations', relevance: 80, summary: 'IoT sensor deployment for live dam monitoring' }, { id: 'RPT-2024-001', title: 'Koyna Dam Safety Audit', type: 'Report', date: '2024-06-01', department: 'Dam Safety', relevance: 94, summary: 'Structural integrity: GOOD | Seismic risk: MODERATE' }, ]; // GR Helper Quick Actions const grQuickActions = [ { text: 'Find latest flood relief GR', icon: Search, color: 'blue' }, { text: 'Explain GR-2024-WRD-089', icon: FileText, color: 'indigo' }, { text: 'Compare compensation GRs', icon: Scale, color: 'purple' }, { text: 'Dam safety protocols', icon: Shield, color: 'red' }, ]; // Query suggestions with categories - Focused on rainfall regions and GR rules const queryCategories = [ { title: 'Rainfall & Weather', icon: Droplets, color: 'blue', queries: [ { text: 'Konkan region rainfall data', icon: Droplets }, { text: 'Vidarbha drought relief GR', icon: FileText }, ] }, { title: 'GR Rules & Acts', icon: Scale, color: 'purple', queries: [ { text: 'Water distribution priority rules', icon: Shield }, { text: 'Canal maintenance responsibility', icon: ScrollText }, ] }, { title: 'Relief & Compensation', icon: Waves, color: 'red', queries: [ { text: 'Flood affected area compensation', icon: FileText }, { text: 'Crop damage claim procedure', icon: BookOpen }, ] }, { title: 'Administrative', icon: Building2, color: 'emerald', queries: [ { text: 'Tahsildar water rights powers', icon: Scale }, { text: 'WUA formation guidelines', icon: MapPin }, ] }, ]; // Generate insights based on query const generateInsights = (query: string): Insight[] => { const q = query.toLowerCase(); if (q.includes('koyna')) { return [ { title: 'Current Level', value: '92.4%', trend: '+2.1%', trendUp: true, icon: Droplets, color: 'text-blue-600' }, { title: 'Storage', value: '2.8 TMC', trend: 'of 3.0 TMC', icon: Database, color: 'text-cyan-600' }, { title: 'Inflow', value: '45,000', trend: 'cusecs', icon: Waves, color: 'text-indigo-600' }, { title: 'Outflow', value: '32,000', trend: 'cusecs', icon: Waves, color: 'text-orange-600' }, ]; } if (q.includes('flood') && q.includes('compensation')) { return [ { title: 'Crop Loss', value: '₹5,000', trend: 'per acre', icon: FileText, color: 'text-emerald-600' }, { title: 'House Damage', value: '₹95,000', trend: 'full damage', icon: Building2, color: 'text-blue-600' }, { title: 'Processing Time', value: '30', trend: 'days', icon: Clock, color: 'text-orange-600' }, { title: 'Claims 2024', value: '12,450', trend: '+23%', trendUp: true, icon: TrendingUp, color: 'text-purple-600' }, ]; } if (q.includes('dam') && q.includes('gate')) { return [ { title: 'Active Releases', value: '12', trend: '+3 today', trendUp: true, icon: Waves, color: 'text-blue-600' }, { title: 'Critical Dams', value: '3', trend: 'High alert', icon: AlertTriangle, color: 'text-red-600' }, { title: 'Total Outflow', value: '1.2M', trend: 'cusecs', icon: Droplets, color: 'text-cyan-600' }, { title: 'Downstream Alert', value: '18', trend: 'districts', icon: Shield, color: 'text-orange-600' }, ]; } return [ { title: 'Total Dams', value: '287', trend: 'monitored', icon: Database, color: 'text-blue-600' }, { title: 'GRs 2024', value: '142', trend: 'indexed', icon: FileText, color: 'text-emerald-600' }, { title: 'Active Alerts', value: '7', trend: 'critical', icon: AlertTriangle, color: 'text-red-600' }, { title: 'Avg Storage', value: '68%', trend: '+5%', trendUp: true, icon: Droplets, color: 'text-cyan-600' }, ]; }; // Generate response based on query const generateResponse = (query: string): { content: string; docs: Document[] } => { const q = query.toLowerCase(); if (q.includes('koyna')) { return { content: `**Koyna Dam - Current Status (as of ${new Date().toLocaleTimeString('en-IN')})** • **Storage Level:** 92.4% (2.8 TMC of 3.0 TMC capacity) • **Inflow:** 45,000 cusecs | **Outflow:** 32,000 cusecs • **Status:** ⚠️ CRITICAL - Emergency discharge initiated • **Districts Alerted:** Satara, Sangli, Kolhapur collectors notified **Recent Actions:** - 4 radial gates opened at 50% capacity - Downstream evacuation advisory issued - Hourly monitoring activated Refer to **GR-2024-WRD-056** for emergency protocols.`, docs: mockDocuments.filter(d => d.id.includes('056') || d.id.includes('RPT-2024-001')) }; } if (q.includes('flood') && q.includes('compensation')) { return { content: `**Flood Relief Compensation - 2024 Guidelines (GR-2024-WRD-089)** **Eligibility Criteria:** • Residence in notified flood-affected area • Damage between July 1 - October 31, 2024 • Registration with local Tahsildar office **Compensation Rates:** • Crop Loss: ₹5,000 per acre (max 10 acres) • House Damage: ₹95,000 (full) / ₹50,000 (partial) • Livestock: ₹50,000 per animal (max 5) **Application Process:** 1. Submit Form WRD-FLOOD-01 to Tahsildar 2. Attach damage assessment report 3. Processing time: 30 days 4. Direct bank transfer Contact: District Relief Office for assistance.`, docs: mockDocuments.filter(d => d.id.includes('089') || d.id.includes('001')) }; } if (q.includes('gate') || q.includes('sop')) { return { content: `**Dam Gate Operations SOP (GR-2023-WRD-124)** **Pre-Opening Checklist:** ✓ Seismic sensors calibrated ✓ Downstream flow sensors active ✓ Alert systems tested ✓ Control room staffed (min 2 engineers) **Opening Procedure:** 1. **Notification** (T-2 hours): Alert downstream districts 2. **Gradual Opening**: 10% increments every 15 minutes 3. **Flow Monitoring**: Continuous discharge measurement 4. **Public Announcement**: Local media + sirens **Emergency Override:** Chief Engineer can authorize immediate release if dam level exceeds 95%. **Documentation:** All gate operations logged in DAMS system within 1 hour.`, docs: mockDocuments.filter(d => d.id.includes('124') || d.id.includes('056')) }; } if (q.includes('irrigation') || q.includes('act')) { return { content: `**Maharashtra Irrigation Act, 1976 - Key Provisions** **Section 33 - Water Rights:** • Priority order: Drinking water > Agriculture > Industry • Canal water distribution by WRD, not local bodies • Penalty for unauthorized diversion: Up to 3 years imprisonment **Section 45 - Maintenance:** • WRD responsible for major repairs (>₹1 lakh) • Water User Associations (WUAs) for minor maintenance • 5% water cess collected for maintenance fund **Recent Amendment (2024):** • IoT-based usage monitoring mandated • Real-time allocation adjustments during scarcity • Digital grievance portal: wrd.maharashtra.gov.in/grievance`, docs: mockDocuments.filter(d => d.type === 'Act') }; } const relevantDocs = mockDocuments .filter(d => q.includes(d.type.toLowerCase()) || d.title.toLowerCase().includes(q.split(' ')[0])) .slice(0, 3); return { content: `I found **${relevantDocs.length} relevant document(s)** for your query on "${query}". ${relevantDocs.map(d => `**${d.id}** - ${d.title}\n• ${d.summary || 'No summary available'}`).join('\n\n')} Would you like me to provide detailed information about any of these documents, or search for something more specific?`, docs: relevantDocs }; }; export function Chatbot() { const location = useLocation(); const navigate = useNavigate(); const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [isLoading, setIsLoading] = useState(false); const [isMobileOpen, setIsMobileOpen] = useState(false); const [showWelcome, setShowWelcome] = useState(true); const [showSidebar, setShowSidebar] = useState(true); const messagesEndRef = useRef(null); const inputRef = useRef(null); const popularGRs = getPopularGRs(); useEffect(() => { const searchParams = new URLSearchParams(location.search); const query = searchParams.get('q'); if (query) { handleSend(query); setShowWelcome(false); } }, [location]); useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]); // Generate unique ID to avoid React key duplicates const generateId = useCallback(() => { return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; }, []); const handleSend = async (text: string) => { if (!text.trim()) return; setShowWelcome(false); const userMsgId = generateId(); const userMsg: Message = { id: userMsgId, role: 'user', content: text, timestamp: new Date() }; setMessages(prev => [...prev, userMsg]); setInput(''); setIsLoading(true); await new Promise(r => setTimeout(r, 800)); const { content, docs } = generateResponse(text); const insights = generateInsights(text); const aiMsg: Message = { id: generateId(), role: 'assistant', content, sources: docs, insights, timestamp: new Date() }; setMessages(prev => [...prev, aiMsg]); setIsLoading(false); }; const getTypeIcon = (type: DocumentType) => { switch (type) { case 'GR': return ScrollText; case 'Act': return Scale; case 'Circular': return FileText; case 'Manual': return BookOpen; case 'SOP': return Shield; case 'Report': return FileSearch; } }; const formatTime = (date?: Date) => { if (!date) return ''; return date.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit' }); }; const WelcomeScreen = () => (
{/* Top Section - Title */}

GR Helper

AI Assistant for Government Resolutions & Acts

{/* GR Quick Actions */}

Quick Actions

{grQuickActions.map((action, idx) => { const Icon = action.icon; return ( ); })}
{/* Middle Section - Category Cards */}

Browse by Category

{queryCategories.map((cat, idx) => { const Icon = cat.icon; return ( ); })}
{/* Bottom Section - Quick Links */}
{['Konkan rainfall', 'Vidarbha GR', 'Water rights', 'Compensation'].map((s, i) => ( ))}
); const RecentGRsSidebar = () => ( ); const MessageBubble = ({ msg }: { msg: Message }) => (
{msg.role === 'user' ? : }
{msg.content.split('**').map((part, i) => i % 2 === 0 ? part : {part} )}
{msg.insights && msg.insights.length > 0 && (
{msg.insights.map((insight, idx) => { const Icon = insight.icon; return (
{insight.title}
{insight.value} {insight.trend && ( {insight.trend} )}
); })}
)} {msg.sources && msg.sources.length > 0 && (
{msg.sources.map((doc, idx) => { const TypeIcon = getTypeIcon(doc.type); return (
{doc.id} | {doc.title}
); })}
)} {formatTime(msg.timestamp)}
); return ( <> {/* Desktop */}
{/* Main Chat Area */}

GR Helper

AI Assistant for Government Resolutions

{showWelcome && messages.length === 0 ? ( ) : (
{messages.map((msg, i) => ( ))} {isLoading && (
Searching GR database...
)}
)}
{ e.preventDefault(); handleSend(input); }} className="flex gap-3">
setInput(e.target.value)} className="h-11 pl-4 pr-10 bg-slate-50 border-slate-200 text-sm focus:bg-white focus:border-blue-500 transition-all rounded-xl" disabled={isLoading} />
{/* Sidebar with Popular GRs */}
{/* Mobile */} <> {!isMobileOpen && ( )} {isMobileOpen && (

GR Helper

AI Assistant for Government GRs

{showWelcome && messages.length === 0 ? (
{/* Top */}

GR Helper

AI Assistant for Government GRs

{/* Quick Actions */}

Quick Actions

{grQuickActions.slice(0, 4).map((action, idx) => ( ))}
{/* Middle - Cards */}

Browse by Category

{queryCategories.map((cat, idx) => ( ))}
{/* Bottom - Quick Links */}
{['Konkan rainfall', 'Vidarbha GR', 'Water rights', 'Compensation'].map((s, i) => ( ))}
) : (
{messages.map((msg, i) => ( ))} {isLoading && (
Searching...
)}
)}
{ e.preventDefault(); handleSend(input); }} className="flex gap-2"> setInput(e.target.value)} className="flex-1 h-10 bg-slate-50 text-sm rounded-xl" disabled={isLoading} />
)} ); }