import React, { useState, useEffect } from 'react';
import { supabase } from '@/lib/supabase';
import { Sparkles, Loader2, MapPin, TrendingUp, Lightbulb, Truck } from 'lucide-react';
import { useFleetData } from '@/contexts/FleetDataContext';

interface Rec { recommendedLoad?: string; reason?: string; estProfitPerMile?: string; deadheadNote?: string; tips?: string[]; raw?: string; }

const AIAssistant: React.FC = () => {
  const { loads, drivers } = useFleetData();
  const [driver, setDriver] = useState('');
  const [location, setLocation] = useState('');
  const [truckType, setTruckType] = useState('Dry Van');
  const [loading, setLoading] = useState(false);
  const [rec, setRec] = useState<Rec | null>(null);

  useEffect(() => {
    if (drivers.length && !driver) { setDriver(drivers[0].name); setLocation(drivers[0].location); }
  }, [drivers, driver]);

  const available = loads.filter((l) => l.status === 'Available');

  const computeFallback = (): Rec => {
    if (available.length === 0) return { raw: 'No available loads to recommend right now. Create a load first.' };
    const best = [...available].sort((a, b) => b.rate / (b.miles + b.deadhead) - a.rate / (a.miles + a.deadhead))[0];
    const ppm = best.rate / (best.miles + best.deadhead);
    return {
      recommendedLoad: best.loadNumber,
      reason: `Highest profit lane (${best.pickup} → ${best.delivery}) with only ${best.deadhead} deadhead miles for ${driver}.`,
      estProfitPerMile: `$${ppm.toFixed(2)}`, deadheadNote: `${best.deadhead} mi from ${location}`,
      tips: [`Confirm HOS — ~${best.miles} loaded miles.`, `Pre-book fuel near ${best.delivery.split(',')[0]}.`],
    };
  };

  const run = async () => {
    setLoading(true); setRec(null);
    const fallback = computeFallback();
    try {
      const { data, error } = await supabase.functions.invoke('ai-dispatch', {
        body: { driver, location, truckType, availableLoads: available.map((l) => ({ loadNumber: l.loadNumber, pickup: l.pickup, delivery: l.delivery, rate: l.rate, miles: l.miles, deadhead: l.deadhead, commodity: l.commodity })) },
      });
      if (error) throw error;
      const r: Rec = (data && data.result) || {};
      setRec({ recommendedLoad: r.recommendedLoad || fallback.recommendedLoad, reason: r.reason || fallback.reason, estProfitPerMile: r.estProfitPerMile || fallback.estProfitPerMile, deadheadNote: r.deadheadNote || fallback.deadheadNote, tips: r.tips && r.tips.length ? r.tips : fallback.tips });
    } catch { setRec(fallback); } finally { setLoading(false); }
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <div className="bg-white rounded-xl border border-slate-200 p-6">
        <div className="flex items-center gap-2 mb-1">
          <div className="w-9 h-9 rounded-lg bg-gradient-to-br from-[#0B3D91] to-[#00C853] flex items-center justify-center"><Sparkles className="w-5 h-5 text-white" /></div>
          <div><h2 className="font-semibold text-slate-900">AI Dispatch Assistant</h2><p className="text-xs text-slate-500">Smart load recommendations</p></div>
        </div>
        <div className="space-y-4 mt-5">
          <div>
            <label className="text-xs font-medium text-slate-600">Driver</label>
            <select value={driver} onChange={(e) => { const d = drivers.find((x) => x.name === e.target.value); setDriver(e.target.value); if (d) setLocation(d.location); }}
              className="w-full mt-1 text-sm rounded-lg border border-slate-200 px-3 py-2.5 outline-none focus:border-[#0B3D91]">
              {drivers.map((d) => <option key={d.id} value={d.name}>{d.name} ({d.status})</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs font-medium text-slate-600">Current Location</label>
            <input value={location} onChange={(e) => setLocation(e.target.value)} className="w-full mt-1 text-sm rounded-lg border border-slate-200 px-3 py-2.5 outline-none focus:border-[#0B3D91]" />
          </div>
          <div>
            <label className="text-xs font-medium text-slate-600">Equipment</label>
            <select value={truckType} onChange={(e) => setTruckType(e.target.value)} className="w-full mt-1 text-sm rounded-lg border border-slate-200 px-3 py-2.5 outline-none focus:border-[#0B3D91]">
              <option>Dry Van</option><option>Reefer</option><option>Flatbed</option><option>Step Deck</option>
            </select>
          </div>
          <button onClick={run} disabled={loading} className="w-full flex items-center justify-center gap-2 bg-[#0B3D91] hover:bg-[#0a3580] disabled:opacity-60 text-white font-semibold py-2.5 rounded-lg transition-colors">
            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}{loading ? 'Analyzing loads...' : 'Recommend Best Load'}
          </button>
          <p className="text-[11px] text-slate-400 text-center">Analyzing {available.length} available loads</p>
        </div>
      </div>

      <div className="bg-white rounded-xl border border-slate-200 p-6">
        <h3 className="font-semibold text-slate-900 mb-4">Recommendation</h3>
        {!rec && !loading && <div className="flex flex-col items-center justify-center h-64 text-center text-slate-400"><Truck className="w-10 h-10 mb-3" /><p className="text-sm">Run the assistant to get an AI-optimized load match.</p></div>}
        {loading && <div className="flex flex-col items-center justify-center h-64 text-slate-400"><Loader2 className="w-8 h-8 animate-spin mb-3" /><p className="text-sm">Crunching profitability & deadhead...</p></div>}
        {rec && (
          <div className="space-y-4">
            {rec.raw ? <p className="text-sm text-slate-600 whitespace-pre-wrap">{rec.raw}</p> : (
              <>
                <div className="bg-gradient-to-br from-[#0B3D91] to-[#0a3580] rounded-lg p-4 text-white">
                  <p className="text-xs text-blue-200">Recommended Load</p><p className="text-2xl font-bold font-mono">{rec.recommendedLoad}</p><p className="text-sm text-blue-100 mt-1">{rec.reason}</p>
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <div className="bg-emerald-50 rounded-lg p-3"><TrendingUp className="w-4 h-4 text-[#00C853] mb-1" /><p className="text-xs text-slate-500">Est. Profit/mi</p><p className="font-bold text-slate-900">{rec.estProfitPerMile}</p></div>
                  <div className="bg-amber-50 rounded-lg p-3"><MapPin className="w-4 h-4 text-[#FF9800] mb-1" /><p className="text-xs text-slate-500">Deadhead</p><p className="text-sm font-medium text-slate-700">{rec.deadheadNote}</p></div>
                </div>
                {rec.tips && <div className="space-y-2">{rec.tips.map((t, i) => <div key={i} className="flex gap-2 text-sm text-slate-600"><Lightbulb className="w-4 h-4 text-[#FF9800] shrink-0 mt-0.5" /><span>{t}</span></div>)}</div>}
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
};
export default AIAssistant;
