'use client';

import { useSmart } from './smart-context';
import { useEffect, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { Lightbulb, ArrowRight, X } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useQueryClient } from '@tanstack/react-query';
import api from '@/lib/api-client';

export function SmartAssistant() {
  const { suggestions } = useSmart();
  const router = useRouter();
  const pathname = usePathname();
  const queryClient = useQueryClient();
  const [isVisible, setIsVisible] = useState(false);

  // Predictive Prefetching Logic
  useEffect(() => {
    if (suggestions?.next_steps && suggestions.next_steps.length > 0) {
      setIsVisible(true);
      
      // Prefetch data for suggested routes to make navigation instant
      suggestions.next_steps.forEach(path => {
        if (path.includes('my-deliveries')) {
          queryClient.prefetchQuery({
            queryKey: ['my-deliveries'],
            queryFn: () => api.get('/deliveries').then(res => res.data)
          });
        } else if (path.includes('suppliers')) {
          queryClient.prefetchQuery({
            queryKey: ['suppliers'],
            queryFn: () => api.get('/suppliers').then(res => res.data)
          });
        }
      });

      // Auto-hide after 10 seconds to not be annoying
      const timer = setTimeout(() => setIsVisible(false), 10000);
      return () => clearTimeout(timer);
    }
  }, [suggestions, queryClient]);

  if (!isVisible || !suggestions?.next_steps?.length) return null;

  return (
    <div className={cn(
      'fixed right-4 z-[60] max-w-[calc(100vw-2rem)] animate-in slide-in-from-bottom-5 fade-in duration-300 sm:right-6',
      pathname.startsWith('/field-staff') ? 'bottom-28' : 'bottom-6'
    )}>
      <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-lg rounded-lg p-4 max-w-sm">
        <div className="flex items-start justify-between mb-2">
          <div className="flex items-center gap-2 text-amber-500 font-medium text-sm">
            <Lightbulb className="h-4 w-4" />
            <span>Smart Suggestion</span>
          </div>
          <button 
            onClick={() => setIsVisible(false)}
            className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200"
          >
            <X className="h-4 w-4" />
          </button>
        </div>
        
        <p className="text-sm text-slate-600 dark:text-slate-300 mb-3">
          Usually, you go here next:
        </p>

        <div className="space-y-2">
          {suggestions.next_steps.map((path) => (
            <button
              key={path}
              onClick={() => router.push(path)}
              className="w-full flex items-center justify-between p-2 text-sm bg-slate-50 dark:bg-slate-800 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-md transition-colors text-left group"
            >
              <span className="truncate font-medium text-slate-700 dark:text-slate-200">
                {path.split('/').pop()?.replace(/-/g, ' ').replace(/\b\w/g, l => l.toUpperCase()) || path}
              </span>
              <ArrowRight className="h-3 w-3 text-slate-400 group-hover:text-primary transition-colors" />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}
