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

import React, { useState, useEffect, useRef } from 'react';
import { Booking, Property } from '../types';
import { motion, AnimatePresence } from 'motion/react';
import { 
  Zap, 
  Play, 
  Pause, 
  X, 
  IndianRupee, 
  BatteryCharging, 
  CheckCircle, 
  Activity, 
  Thermometer, 
  Clock, 
  Printer, 
  AlertTriangle 
} from 'lucide-react';

interface ChargingSimulatorModalProps {
  booking: Booking;
  property: Property;
  userWalletBalance: number;
  onUpdateWallet: (newBalance: number) => void;
  onCompleteBooking: (bookingId: string, finalFare: number) => void;
  onClose: () => void;
}

export default function ChargingSimulatorModal({
  booking,
  property,
  userWalletBalance,
  onUpdateWallet,
  onCompleteBooking,
  onClose
}: ChargingSimulatorModalProps) {
  // Preset values based on vehicle and charger type
  const isFastCharger = (property.chargerTypes || []).some(type => 
    type.toLowerCase().includes('ccs2') || 
    type.toLowerCase().includes('fast') || 
    type.toLowerCase().includes('gbt')
  );

  const chargerSpeedKw = isFastCharger ? 50 : 7.4; // 50kW fast DC vs 7.4kW AC
  
  // State variables for active session
  const [soc, setSoc] = useState<number>(15); // Starts at 15% state of charge
  const [energyDelivered, setEnergyDelivered] = useState<number>(0);
  const [accruedCost, setAccruedCost] = useState<number>(0);
  const [chargingSpeed, setChargingSpeed] = useState<number>(chargerSpeedKw);
  const [temperature, setTemperature] = useState<number>(32); // Celcius
  const [elapsedSeconds, setElapsedSeconds] = useState<number>(0);
  const [isActive, setIsActive] = useState<boolean>(true);
  const [isCompleted, setIsCompleted] = useState<boolean>(false);
  const [receiptMode, setReceiptMode] = useState<boolean>(false);

  const timerRef = useRef<NodeJS.Timeout | null>(null);

  // Math config
  const batteryCapacityKwh = 40.5; // typical Tata Nexon EV
  const chargingRatePerHour = property.fare; // rupees per hour
  
  useEffect(() => {
    if (isActive && soc < 100 && !isCompleted) {
      timerRef.current = setInterval(() => {
        setElapsedSeconds(prev => prev + 1);

        // 1 second in real life corresponds to ~1.5 minutes of simulated charge
        // Calculate SoC increment
        setSoc(prevSoc => {
          if (prevSoc >= 100) {
            setIsActive(false);
            setIsCompleted(true);
            return 100;
          }
          // Fast charger adds ~0.8% per simulated tick, slow adds ~0.15%
          const increment = isFastCharger ? 0.75 : 0.15;
          const nextSoc = Math.min(100, +(prevSoc + increment).toFixed(2));
          return nextSoc;
        });

        // Energy delivered (kWh)
        setEnergyDelivered(prev => {
          // energy = speed in kW * hours
          // Let's increment by matching the SoC addition
          const addedEnergy = (batteryCapacityKwh * (isFastCharger ? 0.0075 : 0.0015));
          return +(prev + addedEnergy).toFixed(3);
        });

        // Fluctuating power rate for realism
        setChargingSpeed(prev => {
          const base = chargerSpeedKw;
          const fluctuation = (Math.random() - 0.5) * (isFastCharger ? 3 : 0.4);
          // Fast charging slows down after 80% SoC
          const taper = soc > 80 ? (100 - soc) / 20 : 1;
          return Math.max(1, +( (base + fluctuation) * taper ).toFixed(1));
        });

        // Fluctuating battery temperature
        setTemperature(prev => {
          const maxTemp = isFastCharger ? 43 : 36;
          if (prev < maxTemp) {
            return +(prev + 0.1).toFixed(1);
          }
          return +(prev + (Math.random() - 0.5) * 0.2).toFixed(1);
        });

      }, 1000);
    }

    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [isActive, soc, isFastCharger, isCompleted]);

  // Derive simulated cost based on property fare rate (rupees per hour)
  // Let's say 1 simulated minute = 1 elapsed second
  // cost = elapsedHours * rate
  const simulatedHours = (elapsedSeconds * 2.5) / 60; // 1 second is 2.5 minutes
  const calculatedCost = Math.max(15, Math.round(simulatedHours * chargingRatePerHour));

  const handleToggleActive = () => {
    setIsActive(!isActive);
  };

  const handleStopCharging = () => {
    setIsActive(false);
    setIsCompleted(true);
    setReceiptMode(true);
    
    // Deduct final accrued cost from user wallet
    const finalWalletBalance = Math.max(0, +(userWalletBalance - calculatedCost).toFixed(2));
    onUpdateWallet(finalWalletBalance);

    // Call upstream to save completed booking status and total fare
    onCompleteBooking(booking.id, calculatedCost);
  };

  // Human-readable simulated elapsed time
  const formatSimulatedTime = (seconds: number) => {
    const totalSimulatedMinutes = Math.round(seconds * 2.5);
    const hrs = Math.floor(totalSimulatedMinutes / 60);
    const mins = totalSimulatedMinutes % 60;
    if (hrs > 0) return `${hrs}h ${mins}m`;
    return `${mins} mins`;
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-950/85 p-4 flex items-center justify-center backdrop-blur-md">
      <motion.div
        initial={{ scale: 0.93, y: 20, opacity: 0 }}
        animate={{ scale: 1, y: 0, opacity: 1 }}
        exit={{ scale: 0.93, y: 20, opacity: 0 }}
        className="w-full max-w-lg bg-slate-900 border border-slate-800 rounded-3xl overflow-hidden shadow-2xl relative"
      >
        {/* Header Ribbon */}
        <div className="bg-gradient-to-r from-emerald-600 to-teal-700 px-6 py-4 flex items-center justify-between text-white select-none">
          <div className="flex items-center gap-2">
            <div className="p-1.5 bg-white/10 rounded-lg backdrop-blur-xs">
              <BatteryCharging className="w-5 h-5 text-emerald-300" />
            </div>
            <div>
              <h3 className="font-extrabold text-sm tracking-tight">Bihar EV Telemetry Portal</h3>
              <p className="text-[10px] text-emerald-100 font-mono">LIVE STATION SOCKET INTEGRATION</p>
            </div>
          </div>
          {!receiptMode && (
            <button 
              onClick={onClose}
              className="p-1 rounded-lg hover:bg-white/10 text-white/80 hover:text-white transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          )}
        </div>

        {/* Dynamic Inner Body */}
        <div className="p-6">
          <AnimatePresence mode="wait">
            {!receiptMode ? (
              <motion.div
                key="simulation"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="space-y-6 text-center"
              >
                {/* Station Meta */}
                <div className="bg-slate-950 border border-slate-850 p-3.5 rounded-2xl text-left space-y-1">
                  <span className="text-[9px] font-mono text-slate-500 font-extrabold uppercase tracking-widest block">CONNECTED HARNESS SPOT</span>
                  <h4 className="font-extrabold text-white text-sm line-clamp-1">{property.title}</h4>
                  <div className="flex justify-between text-[10px] text-slate-400 font-semibold font-mono pt-1">
                    <span>Vehicle: {booking.vehicleNumber}</span>
                    <span className="text-emerald-400">Power Speed: {chargingSpeed} kW</span>
                  </div>
                </div>

                {/* Main Glowing Circular Progress Meter */}
                <div className="relative w-48 h-48 mx-auto flex items-center justify-center">
                  {/* Glowing Pulse Backdrop */}
                  <div className={`absolute inset-4 rounded-full filter blur-xl opacity-20 transition-all duration-700
                    ${isActive ? 'bg-emerald-500 animate-pulse' : 'bg-amber-500'}`} 
                  />

                  {/* SVG Circle Progress */}
                  <svg className="w-full h-full transform -rotate-90">
                    <circle
                      cx="96"
                      cy="96"
                      r="84"
                      className="stroke-slate-800 fill-none"
                      strokeWidth="10"
                    />
                    <circle
                      cx="96"
                      cy="96"
                      r="84"
                      className={`fill-none transition-all duration-300 stroke-emerald-500`}
                      strokeWidth="10"
                      strokeDasharray={2 * Math.PI * 84}
                      strokeDashoffset={2 * Math.PI * 84 * (1 - soc / 100)}
                      strokeLinecap="round"
                    />
                  </svg>

                  {/* Interior SoC Texts */}
                  <div className="absolute inset-0 flex flex-col items-center justify-center select-none">
                    <div className="flex items-center gap-0.5 text-slate-455">
                      <Zap className={`w-4 h-4 ${isActive ? 'text-emerald-450 fill-emerald-550 animate-bounce' : 'text-slate-500'}`} />
                      <span className="text-[10px] font-mono font-black tracking-widest text-slate-400 uppercase">STATE OF CHARGE</span>
                    </div>
                    <span className="text-4xl font-black text-white font-mono tracking-tight my-1">
                      {Math.round(soc)}<span className="text-lg font-bold text-slate-400">%</span>
                    </span>
                    <span className="text-[10.5px] font-mono font-bold bg-slate-950 px-2.5 py-0.5 rounded-full border border-slate-850 text-slate-350">
                      {energyDelivered} kWh
                    </span>
                  </div>
                </div>

                {/* Telemetry Stats Rows */}
                <div className="grid grid-cols-3 gap-3">
                  <div className="bg-slate-950 p-3 rounded-2xl border border-slate-850 text-center">
                    <Thermometer className="w-4 h-4 text-rose-455 mx-auto mb-1" />
                    <span className="text-[9px] font-mono font-bold text-slate-500 uppercase tracking-wider block">BATTERY TEMP</span>
                    <span className="text-xs font-black text-white font-mono mt-0.5 block">{temperature}°C</span>
                  </div>

                  <div className="bg-slate-950 p-3 rounded-2xl border border-slate-850 text-center">
                    <Clock className="w-4 h-4 text-cyan-450 mx-auto mb-1" />
                    <span className="text-[9px] font-mono font-bold text-slate-500 uppercase tracking-wider block">CHARGING TIME</span>
                    <span className="text-xs font-black text-white font-mono mt-0.5 block">{formatSimulatedTime(elapsedSeconds)}</span>
                  </div>

                  <div className="bg-slate-950 p-3 rounded-2xl border border-slate-850 text-center">
                    <IndianRupee className="w-4 h-4 text-amber-400 mx-auto mb-1" />
                    <span className="text-[9px] font-mono font-bold text-slate-500 uppercase tracking-wider block">SESSION COST</span>
                    <span className="text-xs font-black text-amber-400 font-mono mt-0.5 block">₹{calculatedCost}</span>
                  </div>
                </div>

                {/* Control Action Buttons */}
                <div className="flex items-center gap-3 pt-3">
                  <button
                    type="button"
                    onClick={handleToggleActive}
                    className={`flex-1 flex items-center justify-center gap-2 py-3.5 px-4 rounded-xl text-xs font-black uppercase transition-all select-none cursor-pointer
                      ${isActive
                        ? 'bg-slate-950 text-amber-500 border border-slate-800 hover:bg-slate-850'
                        : 'bg-emerald-600 hover:bg-emerald-500 text-white'
                      }`}
                  >
                    {isActive ? (
                      <>
                        <Pause className="w-4 h-4 stroke-[3]" />
                        <span>Pause Charging</span>
                      </>
                    ) : (
                      <>
                        <Play className="w-4 h-4 fill-white" />
                        <span>Resume Charging</span>
                      </>
                    )}
                  </button>

                  <button
                    type="button"
                    onClick={handleStopCharging}
                    className="flex-1.2 py-3.5 px-4 bg-gradient-to-r from-amber-500 to-amber-600 text-slate-950 hover:from-amber-400 hover:to-amber-500 font-black rounded-xl text-xs uppercase shadow-lg shadow-amber-500/10 tracking-wider flex items-center justify-center gap-2 select-none cursor-pointer"
                  >
                    <CheckCircle className="w-4 h-4 stroke-[3]" />
                    <span>Stop & Settle Bill</span>
                  </button>
                </div>

                <div className="flex items-center justify-center gap-1.5 text-[10px] text-slate-500 font-semibold font-mono">
                  <span className="w-2 h-2 bg-emerald-500 rounded-full inline-block animate-ping"></span>
                  <span>Charging at ₹{property.fare}/hr • Smart payment simulator active</span>
                </div>
              </motion.div>
            ) : (
              <motion.div
                key="receipt"
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ duration: 0.3 }}
                className="space-y-6 text-left"
              >
                {/* Visual Stamp Certificate */}
                <div className="bg-emerald-500/10 border border-emerald-500/30 rounded-2xl p-4 flex items-center gap-3 select-none">
                  <div className="w-10 h-10 rounded-full bg-emerald-500/20 flex items-center justify-center text-emerald-400 shrink-0">
                    <CheckCircle className="w-5 h-5 text-emerald-400" />
                  </div>
                  <div>
                    <h4 className="font-extrabold text-sm text-emerald-400">VEHICLE CHARGED SUCCESS</h4>
                    <p className="text-slate-400 text-xs">Payment debited safely from ChargeBuddy virtual wallet.</p>
                  </div>
                </div>

                {/* Thermal Invoice card */}
                <div className="bg-white text-slate-900 rounded-2xl p-5 shadow-inner space-y-4 font-mono text-xs border border-slate-200">
                  <div className="text-center pb-3 border-b border-dashed border-slate-300 space-y-1 select-none">
                    <h3 className="font-black text-sm tracking-widest text-slate-950 uppercase">CHARGEBUDDY BIHAR</h3>
                    <p className="text-[10px] text-slate-500">SASARAM REGIONAL STATION GATEWAY</p>
                    <p className="text-[9px] text-slate-400">{new Date().toLocaleString('en-IN')}</p>
                  </div>

                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="text-slate-500">Receipt Pass No:</span>
                      <strong className="text-slate-950 font-bold">INV-{booking.id}</strong>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-500">EV Station Name:</span>
                      <strong className="text-slate-950 font-bold truncate max-w-[180px]" title={property.title}>{property.title}</strong>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-500">Driver Account:</span>
                      <strong className="text-slate-950 font-bold">{booking.userEmail}</strong>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-500">Vehicle Number:</span>
                      <strong className="text-slate-950 font-bold">{booking.vehicleNumber}</strong>
                    </div>
                    
                    <div className="h-px bg-slate-200 my-2" />

                    <div className="grid grid-cols-2 gap-y-1 bg-slate-50 p-2 rounded-lg text-[11px]">
                      <div className="text-slate-500">Initial SoC:</div>
                      <div className="text-slate-950 text-right font-bold">15%</div>
                      
                      <div className="text-slate-500">Final SoC:</div>
                      <div className="text-slate-950 text-right font-bold">{Math.round(soc)}% (+{Math.round(soc - 15)}%)</div>
                      
                      <div className="text-slate-500">Energy Delivered:</div>
                      <div className="text-slate-950 text-right font-bold">{energyDelivered} kWh</div>
                      
                      <div className="text-slate-500">Elapsed Sim Duration:</div>
                      <div className="text-slate-950 text-right font-bold">{formatSimulatedTime(elapsedSeconds)}</div>
                    </div>

                    <div className="h-px bg-slate-200 my-2" />

                    <div className="flex justify-between text-sm pt-1 select-none">
                      <span className="font-black text-slate-950 uppercase">TOTAL DEBIT</span>
                      <strong className="text-emerald-600 font-extrabold text-base flex items-center">
                        <IndianRupee className="w-3.5 h-3.5 stroke-[2.5]" />
                        <span>{calculatedCost}.00</span>
                      </strong>
                    </div>

                    <div className="flex justify-between text-[10px] text-slate-500 pt-0.5 font-sans">
                      <span>Remaining Wallet Balance:</span>
                      <span className="font-bold">₹{userWalletBalance}</span>
                    </div>
                  </div>

                  {/* Foot notes */}
                  <div className="text-center pt-3 border-t border-dashed border-slate-300 text-[9px] text-slate-400 select-none">
                    <p>Thank you for promoting green mobility in Bihar!</p>
                    <p className="font-black tracking-widest mt-1">⭐⭐⭐⭐⭐</p>
                  </div>
                </div>

                {/* Final receipt controls */}
                <div className="flex items-center gap-3 select-none">
                  <button
                    type="button"
                    onClick={() => {
                      alert("Connecting local AirPrint device...\nSimulating printing of physical tax invoice INV-" + booking.id);
                    }}
                    className="flex-1 py-3 bg-slate-950 hover:bg-slate-850 text-slate-300 border border-slate-800 rounded-xl text-xs font-bold flex items-center justify-center gap-2 cursor-pointer focus:outline-none"
                  >
                    <Printer className="w-4 h-4 text-slate-500" />
                    <span>Print Bill</span>
                  </button>

                  <button
                    type="button"
                    onClick={onClose}
                    className="flex-1 py-3 bg-amber-500 hover:bg-amber-400 text-slate-950 font-black rounded-xl text-xs uppercase tracking-wide text-center cursor-pointer focus:outline-none"
                  >
                    Close Simulator
                  </button>
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </motion.div>
    </div>
  );
}
