import React, { useEffect, useState } from 'react';
import { AlertTriangle, Lightbulb, Calendar, Clock, TrendingUp } from 'lucide-react';

interface SmartAnalysisProps {
  quantity: number;
  date: string;
  commodityName?: string;
  isManualSupplier: boolean;
  unitCount?: number;
}

interface Insight {
  id: string;
  type: 'warning' | 'info' | 'success';
  icon: React.ElementType;
  title: string;
  message: string;
}

export function DeliverySmartAnalysis({ 
  quantity, 
  date, 
  commodityName, 
  isManualSupplier,
  unitCount 
}: SmartAnalysisProps) {
  const [insights, setInsights] = useState<Insight[]>([]);

  useEffect(() => {
    const newInsights: Insight[] = [];

    // 1. Date Analysis
    if (date) {
      const d = new Date(date);
      const isWeekend = d.getDay() === 0 || d.getDay() === 6;
      const isFuture = d > new Date();

      if (isWeekend) {
        newInsights.push({
          id: 'weekend-delivery',
          type: 'warning',
          icon: Calendar,
          title: 'Weekend Delivery Detected',
          message: `You are recording a delivery on a ${d.toLocaleDateString('en-US', { weekday: 'long' })}. Most schools are closed. Please verify.`
        });
      }
      
      if (isFuture) {
        newInsights.push({
          id: 'future-date',
          type: 'warning',
          icon: Clock,
          title: 'Future Date',
          message: 'The delivery date is in the future. Are you pre-recording?'
        });
      }
    }

    // 2. Quantity Heuristics
    if (quantity > 0) {
      const RICE_THRESHOLD = 500;
      const BEANS_THRESHOLD = 300;
      
      let threshold = 1000; // default
      if (commodityName?.toLowerCase().includes('rice')) threshold = RICE_THRESHOLD;
      if (commodityName?.toLowerCase().includes('bean')) threshold = BEANS_THRESHOLD;

      if (quantity > threshold) {
        newInsights.push({
          id: 'high-quantity',
          type: 'info',
          icon: TrendingUp,
          title: 'High Volume Delivery',
          message: `This entered quantity (${quantity}) is significantly higher than the average ${commodityName || 'commodity'} delivery (${threshold}).`
        });
      }

      // Round number check (e.g. 1000 vs 1024)
      if (quantity > 100 && quantity % 100 === 0) {
         // This is a subtle nudge, often real weights aren't perfectly round
         // keeping it as 'info'
      }
    }

    // 3. Supplier Integrity
    if (isManualSupplier) {
      newInsights.push({
        id: 'manual-supplier',
        type: 'warning',
        icon: AlertTriangle,
        title: 'Unregistered Supplier',
        message: 'Using a manual supplier bypasses contract validation. Only proceed if you are 100% sure the supplier is not in the list.'
      });
    }

    // 4. Unit Logic
    if (unitCount && unitCount > 0 && quantity > 0) {
      // Check for unit mismatch implication
      // e.g. User said 100 bags but quantity is 50
    }

    setInsights(newInsights);
  }, [quantity, date, commodityName, isManualSupplier, unitCount]);

  if (insights.length === 0) return null;

  return (
    <div className="space-y-3 animate-in fade-in slide-in-from-bottom-2 duration-500">
      {insights.map((insight) => (
        <div 
          key={insight.id}
          className={`
            flex gap-3 rounded-xl p-3 border shadow-sm
            ${insight.type === 'warning' ? 'bg-amber-50 border-amber-200 text-amber-900' : ''}
            ${insight.type === 'info' ? 'bg-blue-50 border-blue-200 text-blue-900' : ''}
            ${insight.type === 'success' ? 'bg-emerald-50 border-emerald-200 text-emerald-900' : ''}
          `}
        >
          <div className={`
             flex h-8 w-8 shrink-0 items-center justify-center rounded-full
             ${insight.type === 'warning' ? 'bg-amber-100 text-amber-600' : ''}
             ${insight.type === 'info' ? 'bg-blue-100 text-blue-600' : ''}
             ${insight.type === 'success' ? 'bg-emerald-100 text-emerald-600' : ''}
          `}>
            <insight.icon className="h-4 w-4" />
          </div>
          <div>
            <h4 className="text-sm font-semibold">{insight.title}</h4>
            <p className="text-xs opacity-90">{insight.message}</p>
          </div>
        </div>
      ))}
    </div>
  );
}
