/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useMemo } from 'react';
import { Property } from '../types';
import { motion } from 'motion/react';
import { 
  Compass, 
  MapPin, 
  Clock, 
  Zap, 
  Car, 
  CheckCircle, 
  AlertTriangle, 
  Info, 
  Gauge, 
  IndianRupee 
} from 'lucide-react';

interface TripRangeEstimatorProps {
  property: Property;
  userVehicleModel?: string;
}

interface EVPreset {
  name: string;
  capacity: number; // kWh
  range: number; // km
}

const EV_PRESETS: EVPreset[] = [
  { name: 'Tata Nexon EV Max', capacity: 40.5, range: 312 },
  { name: 'MG ZS EV Standard', capacity: 50.3, range: 360 },
  { name: 'BYD Atto 3 Premium', capacity: 60.48, range: 420 },
  { name: 'Mahindra XUV400', capacity: 39.4, range: 280 },
  { name: 'Ola S1 Pro Gen 2', capacity: 4.0, range: 140 },
  { name: 'Generic EV 2-Wheeler', capacity: 3.0, range: 90 },
];

export default function TripRangeEstimator({
  property,
  userVehicleModel
}: TripRangeEstimatorProps) {
  // Try to pre-select preset matching the user's vehicle model
  const initialEVIndex = useMemo(() => {
    if (!userVehicleModel) return 0;
    const idx = EV_PRESETS.findIndex(preset => 
      preset.name.toLowerCase().includes(userVehicleModel.toLowerCase()) ||
      userVehicleModel.toLowerCase().includes(preset.name.toLowerCase().split(' ')[0])
    );
    return idx !== -1 ? idx : 0;
  }, [userVehicleModel]);

  const [selectedEVIndex, setSelectedEVIndex] = useState<number>(initialEVIndex);
  const [currentSoC, setCurrentSoC] = useState<number>(45); // %
  const [targetSoC, setTargetSoC] = useState<number>(80); // %

  const selectedEV = EV_PRESETS[selectedEVIndex];

  // Base coords representing the "Driver's Current Location" (simulated as Sasaram Station center)
  const sasaramStationCoords = { lat: 24.9540, lng: 84.0142 };

  // Calculate actual Haversine distance in km
  const routeStats = useMemo(() => {
    const lat1 = sasaramStationCoords.lat;
    const lon1 = sasaramStationCoords.lng;
    const lat2 = property.location.lat;
    const lon2 = property.location.lng;

    const R = 6371; // Radius of the earth in km
    const dLat = (lat2 - lat1) * Math.PI / 180;
    const dLon = (lon2 - lon1) * Math.PI / 180;
    const a = 
      Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
      Math.sin(dLon/2) * Math.sin(dLon/2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    
    // Direct distance
    const directD = R * c; 
    
    // Road multiplier (~1.3x for state/district highways)
    const roadD = +(directD * 1.3).toFixed(1);

    // Driving time based on average 45km/h speed
    const drivingMins = Math.round((roadD / 45) * 60);

    // Energy consumption calculation
    const energyUsedKwh = +(roadD * (selectedEV.capacity / selectedEV.range)).toFixed(2);
    const percentSoCUsed = Math.round((energyUsedKwh / selectedEV.capacity) * 100);
    const arrivalSoC = Math.max(-100, currentSoC - percentSoCUsed);

    // Determine fast charging eligibility
    const chargerTypes = property.chargerTypes || [];
    const isFast = chargerTypes.some(type => 
      type.toLowerCase().includes('ccs2') || 
      type.toLowerCase().includes('fast') || 
      type.toLowerCase().includes('gbt')
    );
    const chargerPowerKw = isFast ? 50 : 7.4; // 50kW DC fast vs 7.4kW AC slow
    const isChargingAvailable = property.type === 'charging' || property.type === 'both';

    // Charging time from arrivalSoC to targetSoC
    let chargingTimeMins = 0;
    let chargingCost = 0;

    if (arrivalSoC > 0 && isChargingAvailable && targetSoC > arrivalSoC) {
      const neededKwh = selectedEV.capacity * ((targetSoC - arrivalSoC) / 100);
      const hrs = neededKwh / chargerPowerKw;
      chargingTimeMins = Math.round(hrs * 60);
      chargingCost = Math.round(hrs * property.fare);
    }

    return {
      distance: roadD,
      drivingTime: drivingMins,
      energyUsed: energyUsedKwh,
      socUsed: percentSoCUsed,
      arrivalSoC,
      chargerPowerKw,
      isChargingAvailable,
      chargingTimeMins,
      chargingCost
    };
  }, [property, selectedEV, currentSoC, targetSoC]);

  // Adjust target SoC if current SoC or arrival SoC exceeds it
  const validArrivalSoC = Math.max(0, routeStats.arrivalSoC);
  const minTarget = Math.min(100, validArrivalSoC + 5);

  return (
    <div className="bg-slate-900 border border-slate-800 rounded-3xl p-5 shadow-lg space-y-5 text-left select-none">
      <div className="flex items-center justify-between pb-3 border-b border-slate-800">
        <div className="flex items-center gap-2">
          <div className="p-1.5 bg-amber-500/10 text-amber-500 rounded-xl border border-amber-900/20">
            <Gauge className="w-5 h-5" />
          </div>
          <div>
            <h4 className="font-extrabold text-white text-sm tracking-tight">Trip Range Optimizer</h4>
            <p className="text-[10px] text-slate-500 font-mono">INTELLIGENT ENERGY ESTIMATOR</p>
          </div>
        </div>
        <span className="text-[9.5px] bg-slate-950 px-2 py-0.5 rounded border border-slate-850 font-bold font-mono text-slate-400">
          FROM SASARAM JUNCTION
        </span>
      </div>

      {/* EV Vehicle Selector dropdown */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div className="space-y-1.5">
          <label className="text-[10px] text-slate-500 font-bold uppercase tracking-wider block">Your Electric Vehicle</label>
          <div className="relative">
            <Car className="absolute left-3 top-2.5 w-4 h-4 text-slate-400" />
            <select
              value={selectedEVIndex}
              onChange={(e) => setSelectedEVIndex(parseInt(e.target.value))}
              className="w-full pl-9 pr-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-xs font-semibold text-slate-200 outline-none focus:ring-1 focus:ring-amber-500 appearance-none cursor-pointer"
            >
              {EV_PRESETS.map((preset, idx) => (
                <option key={idx} value={idx}>{preset.name} ({preset.capacity} kWh)</option>
              ))}
            </select>
          </div>
        </div>

        {/* Current Battery % state */}
        <div className="space-y-1.5">
          <div className="flex justify-between text-[10px] font-bold text-slate-500 uppercase tracking-wider">
            <span>Current Battery (SoC)</span>
            <span className="text-amber-400 font-extrabold font-mono">{currentSoC}%</span>
          </div>
          <input
            type="range"
            min="5"
            max="100"
            step="1"
            value={currentSoC}
            onChange={(e) => {
              const val = parseInt(e.target.value);
              setCurrentSoC(val);
              if (targetSoC < val + 5) {
                setTargetSoC(Math.min(100, val + 10));
              }
            }}
            className="w-full h-1 bg-slate-800 rounded-lg appearance-none cursor-pointer accent-amber-500 focus:outline-none"
          />
        </div>
      </div>

      {/* Trip Calculation Outputs */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 bg-slate-950 p-3.5 rounded-2xl border border-slate-850/80">
        <div className="space-y-0.5">
          <span className="text-[9px] text-slate-500 font-bold uppercase block font-mono">Distance</span>
          <strong className="text-white text-sm font-black font-mono">{routeStats.distance} km</strong>
        </div>
        <div className="space-y-0.5">
          <span className="text-[9px] text-slate-500 font-bold uppercase block font-mono">Drive Time</span>
          <strong className="text-white text-sm font-black font-mono">{routeStats.drivingTime} mins</strong>
        </div>
        <div className="space-y-0.5">
          <span className="text-[9px] text-slate-500 font-bold uppercase block font-mono">Energy Needed</span>
          <strong className="text-white text-sm font-black font-mono text-emerald-400">{routeStats.energyUsed} kWh</strong>
        </div>
        <div className="space-y-0.5">
          <span className="text-[9px] text-slate-500 font-bold uppercase block font-mono">Est. Arrival SoC</span>
          <strong className={`text-sm font-black font-mono block
            ${routeStats.arrivalSoC <= 0 ? 'text-rose-400' : 'text-amber-400'}`}
          >
            {routeStats.arrivalSoC <= 0 ? '0% (Dead)' : `${routeStats.arrivalSoC}%`}
          </strong>
        </div>
      </div>

      {/* Safety / Range Feasibility Warning Alert */}
      {routeStats.arrivalSoC <= 0 ? (
        <div className="p-3 bg-rose-950/20 border border-rose-900/30 rounded-xl flex items-start gap-2 text-rose-300 text-xs leading-relaxed">
          <AlertTriangle className="w-5 h-5 shrink-0 text-rose-500 mt-0.5" />
          <div>
            <strong className="font-bold text-rose-400 block">Insufficient Charge Alert!</strong>
            The distance exceeds your current battery range. You will run out of charge in approximately{' '}
            <span className="font-bold font-mono text-white">
              {Math.round(selectedEV.range * (currentSoC / 100))} km
            </span>{' '}
            before reaching your destination. Please charge your battery locally first or pre-book roadside SOS support in sasaram.
          </div>
        </div>
      ) : (
        <div className="space-y-4">
          <div className="p-3 bg-emerald-950/25 border border-emerald-900/30 rounded-xl flex items-center gap-2 text-emerald-300 text-xs">
            <CheckCircle className="w-4 h-4 text-emerald-400 shrink-0" />
            <span>Feasible Route! You will arrive safely with approx <span className="font-bold text-white">{routeStats.arrivalSoC}% SoC</span> remaining.</span>
          </div>

          {/* Charging Estimates Controls */}
          {routeStats.isChargingAvailable ? (
            <div className="border-t border-slate-800/60 pt-4 space-y-4">
              <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
                <div className="space-y-0.5">
                  <h5 className="text-xs font-black text-white uppercase tracking-wide">Target SoC on Arrival</h5>
                  <p className="text-[10px] text-slate-500">Choose how much you want to charge your EV up to</p>
                </div>
                
                <div className="flex gap-2 bg-slate-950 p-1 rounded-xl border border-slate-850 w-full sm:w-auto">
                  {[80, 100].map((socValue) => (
                    <button
                      key={socValue}
                      type="button"
                      disabled={routeStats.arrivalSoC >= socValue}
                      onClick={() => setTargetSoC(socValue)}
                      className={`flex-1 sm:flex-initial px-4 py-1.5 rounded-lg text-[10px] sm:text-xs font-bold transition-all disabled:opacity-30 disabled:cursor-not-allowed
                        ${targetSoC === socValue
                          ? 'bg-amber-500 text-slate-950 font-extrabold shadow-sm'
                          : 'text-slate-400 hover:text-white'
                        }`}
                    >
                      Charge to {socValue}%
                    </button>
                  ))}
                </div>
              </div>

              {/* Slider for precision Target SoC */}
              <div className="space-y-1.5">
                <div className="flex justify-between text-[10px] font-bold text-slate-500 uppercase font-mono">
                  <span>Custom Target Battery Limit</span>
                  <span className="text-emerald-400 font-extrabold">{targetSoC}%</span>
                </div>
                <input
                  type="range"
                  min={minTarget}
                  max="100"
                  step="1"
                  value={targetSoC}
                  onChange={(e) => setTargetSoC(parseInt(e.target.value))}
                  className="w-full h-1 bg-slate-800 rounded-lg appearance-none cursor-pointer accent-emerald-500 focus:outline-none"
                />
              </div>

              {/* Charging output calculations */}
              <div className="grid grid-cols-3 gap-3 bg-slate-950/40 border border-slate-850 p-3 rounded-2xl">
                <div className="text-center">
                  <span className="text-[8.5px] font-mono font-bold text-slate-500 uppercase block">CHARGING RATE</span>
                  <strong className="text-white text-xs font-bold font-mono block mt-0.5">{routeStats.chargerPowerKw} kW ({routeStats.chargerPowerKw === 50 ? 'DC Fast' : 'AC Slow'})</strong>
                </div>
                <div className="text-center border-x border-slate-850/70">
                  <span className="text-[8.5px] font-mono font-bold text-slate-500 uppercase block">DURATION</span>
                  <strong className="text-amber-400 text-xs font-black font-mono block mt-0.5">
                    {routeStats.chargingTimeMins >= 60 
                      ? `${Math.floor(routeStats.chargingTimeMins / 60)}h ${routeStats.chargingTimeMins % 60}m`
                      : `${routeStats.chargingTimeMins} mins`}
                  </strong>
                </div>
                <div className="text-center">
                  <span className="text-[8.5px] font-mono font-bold text-slate-500 uppercase block">ESTIMATED COST</span>
                  <strong className="text-emerald-400 text-xs font-black font-mono block mt-0.5 flex items-center justify-center">
                    <IndianRupee className="w-3.5 h-3.5" />
                    <span>{routeStats.chargingCost}</span>
                  </strong>
                </div>
              </div>
            </div>
          ) : (
            <div className="p-3 bg-indigo-950/15 border border-indigo-900/30 rounded-xl flex items-start gap-2 text-indigo-300 text-xs">
              <Info className="w-4.5 h-4.5 shrink-0 text-indigo-400 mt-0.5" />
              <div>
                <strong className="font-bold text-indigo-400 block">Smart Parking Hub Only</strong>
                This spot has no EV charger couplings installed. Select an alternate green charging point on the map if you require recharging capacity.
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
