import React, { useRef, useState } from 'react';
import { IonContent, IonPage, useIonViewDidEnter, useIonViewWillLeave } from '@ionic/react';
import { useHistory } from 'react-router-dom';
import { Capacitor } from '@capacitor/core';
import back from '../../assets/back.png';
import carIconUrl from '../../assets/icons/carrito.png';
import { useFunctionService } from '../components/Layout';
import $ from 'jquery';

declare const google: any;

type GLL = { lat: number; lng: number };

const mapContainerStyle: React.CSSProperties = {
  width: '100%',
  height: '95vh',
};

const Tracker: React.FC = () => {
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const animationRef = useRef<number | null>(null);

  const { registerFunction } = useFunctionService();
  const mapRef = useRef<HTMLDivElement>(null);
  const history = useHistory();

  const mapInstance = useRef<any>(null);
  const directionsServiceRef = useRef<any>(null);
  const directionsRendererRef = useRef<any>(null);
  const vehicleMarker = useRef<any>(null);
  const clientMarkerRef = useRef<any>(null);
  const clientWaveRef = useRef<any>(null);
  const clientWaveAnimRef = useRef<number | null>(null);
  const carElRef = useRef<HTMLElement | null>(null);
  const useAdvancedMarker = useRef(false);
  const lastPos = useRef<GLL | null>(null);

  const SAME_POS_METERS = 0.8;
  const MAP_ID = '9ddca00df2fb738619fd9108';
  const CAR_SIZE_PX = 48;

  const [pin, setPin] = useState(0);
  const [estado, setEstado] = useState('');
  const [nombre, setNombre] = useState('');
  const [modelo, setModelo] = useState('');
  const [placa, setPlaca] = useState('');
  const [foto, setFoto] = useState('');
  const [marca, setMarca] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [metodo_pago, setMetodo_pago] = useState('');
  const [monto, setMonto] = useState(0);
  const [minutes_ago, setminutes_ago] = useState(0);
  const [coolmessage, setCoolMessage] = useState('');
  const [latEnCero, setLatEnCero] = useState(false);
  const [billing_account, setBilling_account] = useState('');

  const initdata = () => {
    $.getJSON(
      localStorage.apiurl,
      {
        op: 'carrera_detail',
        id_carrera: localStorage.carreraencurso,
      },
      (data) => {
        if (data[0].estado == 1) {
          setCoolMessage('Mantente pendiente de tu celular, en breve recibirás una llamada de confirmación de tu Duper');
        }

        if (data[0].estado == 2 || data[0].estado == 3) {
          setCoolMessage('0');
          setPin(data[0].pin);
          setEstado(data[0].estado);
          setNombre(data[0].nombre);
          setModelo(data[0].modelo);
          setPlaca(data[0].placa);
          setFoto(data[0].foto);
          setMarca(data[0].marca);
          setMetodo_pago(data[0].metodo_pago);
          setminutes_ago(data[0].minutes_ago);
          setMonto(data[0].monto);
          setBilling_account(data[0].billing_account);
        }

        if (data[0].estado == 4) {
          setCoolMessage('0');
          alert('Carrera Finalizada');
          history.replace('/home');
        }
      }
    );
  };

  const supportsAdvancedMarker = (): boolean => {
    try {
      return !!(
        google &&
        google.maps &&
        google.maps.marker &&
        google.maps.marker.AdvancedMarkerElement
      );
    } catch {
      return false;
    }
  };

  const setupCarElement = () => {
    const container = document.createElement('div');
    container.style.width = `${CAR_SIZE_PX}px`;
    container.style.height = `${CAR_SIZE_PX}px`;
    container.style.transformOrigin = '50% 100%';
    container.style.willChange = 'transform';
    container.style.userSelect = 'none';
    container.style.pointerEvents = 'none';

    const img = document.createElement('img');
    img.src = carIconUrl;
    img.alt = 'car';
    img.style.width = '100%';
    img.style.height = '100%';
    img.style.display = 'block';

    container.appendChild(img);
    carElRef.current = container;
  };

  const distMeters = (a: GLL, b: GLL): number => {
    const A = new google.maps.LatLng(a.lat, a.lng);
    const B = new google.maps.LatLng(b.lat, b.lng);
    return google.maps.geometry.spherical.computeDistanceBetween(A, B);
  };

  const computeBearing = (from: GLL, to: GLL): number => {
    const toRad = (deg: number) => (deg * Math.PI) / 180;
    const toDeg = (rad: number) => (rad * 180) / Math.PI;

    const φ1 = toRad(from.lat);
    const φ2 = toRad(to.lat);
    const Δλ = toRad(to.lng - from.lng);

    const y = Math.sin(Δλ) * Math.cos(φ2);
    const x =
      Math.cos(φ1) * Math.sin(φ2) -
      Math.sin(φ1) * Math.cos(φ2) * Math.cos(Δλ);

    let θ = toDeg(Math.atan2(y, x));
    return (θ + 360) % 360;
  };

  const createOrUpdateVehicleMarker = (position: GLL, rotationDeg: number) => {
    if (!mapInstance.current) return;

    const latLng = new google.maps.LatLng(position.lat, position.lng);

    if (useAdvancedMarker.current) {
      if (!carElRef.current) setupCarElement();

      if (!vehicleMarker.current) {
        vehicleMarker.current = new google.maps.marker.AdvancedMarkerElement({
          map: mapInstance.current,
          position: latLng,
          content: carElRef.current,
          zIndex: 999,
        });
      } else {
        vehicleMarker.current.position = latLng;
      }

      if (carElRef.current) {
        carElRef.current.style.transform = `rotate(${rotationDeg}deg)`;
      }
    } else {
      // Marcador clásico: PNG resuelto por Vite (funciona en Android/Capacitor; rutas "assets/..." no).
      const iconObj: any = {
        url: carIconUrl,
        scaledSize: new google.maps.Size(CAR_SIZE_PX, CAR_SIZE_PX),
        anchor: new google.maps.Point(CAR_SIZE_PX / 2, CAR_SIZE_PX),
      };

      if (!vehicleMarker.current) {
        vehicleMarker.current = new google.maps.Marker({
          position: latLng,
          map: mapInstance.current,
          icon: iconObj,
          zIndex: 999,
          optimized: false,
          rotation: rotationDeg,
        } as any);
      } else {
        vehicleMarker.current.setIcon(iconObj);
        vehicleMarker.current.setPosition(latLng);
        if (typeof (vehicleMarker.current as any).setRotation === 'function') {
          (vehicleMarker.current as any).setRotation(rotationDeg);
        } else {
          (vehicleMarker.current as any).setOptions({ rotation: rotationDeg });
        }
      }
    }
  };

  const startClientWaveAnimation = (center: any) => {
    if (!mapInstance.current) return;

    if (!clientWaveRef.current) {
      clientWaveRef.current = new google.maps.Circle({
        map: mapInstance.current,
        center,
        radius: 0,
        strokeColor: '#f97316',
        strokeOpacity: 0.9,
        strokeWeight: 2,
        fillColor: '#f97316',
        fillOpacity: 0.25,
        zIndex: 400,
      });
    } else {
      clientWaveRef.current.setCenter(center);
    }

    if (clientWaveAnimRef.current) {
      cancelAnimationFrame(clientWaveAnimRef.current);
      clientWaveAnimRef.current = null;
    }

    const maxRadius = 80; // metros aprox
    const minRadius = 10;
    const duration = 1800;

    const animate = (startTs: number) => {
      const now = performance.now();
      const t = ((now - startTs) % duration) / duration;
      const radius = minRadius + (maxRadius - minRadius) * t;
      const opacity = 0.35 * (1 - t);

      if (clientWaveRef.current) {
        clientWaveRef.current.setRadius(radius);
        clientWaveRef.current.setOptions({ fillOpacity: opacity, strokeOpacity: opacity + 0.2 });
      }

      clientWaveAnimRef.current = requestAnimationFrame(() => animate(startTs));
    };

    clientWaveAnimRef.current = requestAnimationFrame((ts) => animate(ts));
  };

  const animateVehicle = (from: GLL, to: GLL, bearing: number, durationMs = 4000) => {
    if (!mapInstance.current) return;

    if (distMeters(from, to) < SAME_POS_METERS) {
      lastPos.current = to;
      return;
    }

    if (animationRef.current) {
      cancelAnimationFrame(animationRef.current);
      animationRef.current = null;
    }

    const start = performance.now();
    const startLat = from.lat;
    const startLng = from.lng;
    const dLat = to.lat - startLat;
    const dLng = to.lng - startLng;

    createOrUpdateVehicleMarker(from, bearing);

    const step = (now: number) => {
      const t = Math.min(1, (now - start) / durationMs);
      const ease = t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;

      const curLat = startLat + dLat * ease;
      const curLng = startLng + dLng * ease;
      const curPos: GLL = { lat: curLat, lng: curLng };

      createOrUpdateVehicleMarker(curPos, bearing);

      if (mapInstance.current) {
        mapInstance.current.panTo(new google.maps.LatLng(curPos.lat, curPos.lng));
      }

      if (t < 1) {
        animationRef.current = requestAnimationFrame(step);
      } else {
        createOrUpdateVehicleMarker(to, bearing);
        lastPos.current = to;
        animationRef.current = null;
      }
    };

    animationRef.current = requestAnimationFrame(step);
  };

  const initMapIfNeeded = () => {
    if (!mapRef.current || mapInstance.current) return;

    mapInstance.current = new google.maps.Map(mapRef.current, {
      center: { lat: 14.081999, lng: -87.202438 },
      zoom: 16,
      clickableIcons: false,
      streetViewControl: false,
      fullscreenControl: false,
      mapTypeControl: false,
      disableDefaultUI: true,
      mapId: MAP_ID,
      heading: 0,
      tilt: 0,
    });

    if (!directionsServiceRef.current) {
      directionsServiceRef.current = new google.maps.DirectionsService();
    }
    if (!directionsRendererRef.current) {
      directionsRendererRef.current = new google.maps.DirectionsRenderer({
        suppressMarkers: true,
        preserveViewport: true,
        polylineOptions: {
          strokeColor: '#4ade80',
          strokeOpacity: 0.9,
          strokeWeight: 5,
        },
      });
      directionsRendererRef.current.setMap(mapInstance.current);
    }

    // En Android WebView, AdvancedMarker + <img src="assets/..."> suele fallar; el clásico con URL empaquetada es estable.
    const isAndroidNative =
      Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android';
    useAdvancedMarker.current = supportsAdvancedMarker() && !isAndroidNative;
    if (useAdvancedMarker.current) {
      setupCarElement();
    }
  };

  const updateMarker = () => {
    initdata();

    $.getJSON(
      localStorage.apiurl,
      {
        op: 'getlocation',
        id_carrera: localStorage.carreraencurso,
      },
      (data) => {
        if (!data || !data[0]) return;

        const lat = parseFloat(data[0].lat);
        const lon = parseFloat(data[0].lon);
        const clienteDesdeLat = data[0].cliente_desde_lat
          ? parseFloat(data[0].cliente_desde_lat)
          : NaN;
        const clienteDesdeLon = data[0].cliente_desde_lon
          ? parseFloat(data[0].cliente_desde_lon)
          : NaN;

        if (lat === 0) {
          setLatEnCero(true);
          return;
        }

        if (lat === 1) {
          alert('Carrera Finalizada');

          if (intervalRef.current) {
            clearInterval(intervalRef.current);
            intervalRef.current = null;
          }

          history.push('/home');
          return;
        }

        if (lat === -1) {
          alert('Carrera Cancelada por el Duper');

          if (intervalRef.current) {
            clearInterval(intervalRef.current);
            intervalRef.current = null;
          }

          history.push('/home');
          return;
        }

        if (!Number.isFinite(lat) || !Number.isFinite(lon)) return;

        setLatEnCero(false);
        setCoolMessage('0');

        const newPos: GLL = { lat, lng: lon };

        if (!mapInstance.current) {
          initMapIfNeeded();
        }

        if (!mapInstance.current) return;

        // Marker bonito en el punto de origen del cliente + ondas
        if (Number.isFinite(clienteDesdeLat) && Number.isFinite(clienteDesdeLon)) {
          const clientPos = new google.maps.LatLng(clienteDesdeLat, clienteDesdeLon);
          if (!clientMarkerRef.current) {
            clientMarkerRef.current = new google.maps.Marker({
              position: clientPos,
              map: mapInstance.current,
              icon: {
                path: google.maps.SymbolPath.CIRCLE,
                scale: 7,
                fillColor: '#ef4444',
                fillOpacity: 1,
                strokeColor: '#ffffff',
                strokeWeight: 2,
              },
              zIndex: 550,
            });
          } else {
            clientMarkerRef.current.setPosition(clientPos);
          }

          startClientWaveAnimation(clientPos);
        }

        // Dibujar ruta probable desde el driver hasta el origen del cliente
        if (
          directionsServiceRef.current &&
          directionsRendererRef.current &&
          Number.isFinite(clienteDesdeLat) &&
          Number.isFinite(clienteDesdeLon)
        ) {
          directionsServiceRef.current.route(
            {
              origin: new google.maps.LatLng(newPos.lat, newPos.lng),
              destination: new google.maps.LatLng(clienteDesdeLat, clienteDesdeLon),
              travelMode: google.maps.TravelMode.DRIVING,
            },
            (result: any, status: any) => {
              if (status === google.maps.DirectionsStatus.OK && result) {
                directionsRendererRef.current.setDirections(result);
              }
            }
          );
        }

        if (!lastPos.current) {
          lastPos.current = newPos;
          createOrUpdateVehicleMarker(newPos, 0);
          mapInstance.current.setCenter(newPos);
          mapInstance.current.setZoom(16);
          return;
        }

        const dist = distMeters(lastPos.current, newPos);

        if (dist < SAME_POS_METERS) {
          return;
        }

        const bearing = computeBearing(lastPos.current, newPos);
        animateVehicle(lastPos.current, newPos, bearing, 4000);
      }
    );
  };

  useIonViewWillLeave(() => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }

    if (animationRef.current) {
      cancelAnimationFrame(animationRef.current);
      animationRef.current = null;
    }

    if (clientWaveAnimRef.current) {
      cancelAnimationFrame(clientWaveAnimRef.current);
      clientWaveAnimRef.current = null;
    }
  });

  useIonViewDidEnter(() => {
    initMapIfNeeded();
    initdata();
    updateMarker();

    if (!intervalRef.current) {
      intervalRef.current = setInterval(updateMarker, 10000);
    }

    registerFunction('updateTracker', () => {
      initdata();
    });
  });

  const openpagarmodal = () => {
    setShowModal(true);
  };

  const gotochat = () => {
    history.push('/chatuser');
  };

  const backtohome = () => {
    history.replace('/home');
  };

  const pagartarjeta = () => {
    history.push(`/pagarcarrera?monto=${monto}`);
  };

  const pagarefectivo = () => {
    alert('Entregue el monto de ' + monto + ' al Duper, ellos registrarán el pago');
    setShowModal(false);
    initdata();
  };

  const cerrar = () => {
    setShowModal(false);
    initdata();
  };

  const finalizarCarrera = () => {
    if (confirm('¿Está seguro que desea finalizar la carrera?')) {
      $.getJSON(
        localStorage.apiurl,
        {
          op: 'finalizarCarreraForzar',
          id_carrera: localStorage.carreraencurso,
          estado: 4,
        },
        (data) => {
          if (data[0].status === 'OK') {
            history.replace('/home');
          } else {
            alert(data[0].message);
          }
        }
      );
    }
  };

  return (
    <IonPage>
      <IonContent>
        <div className="relative">
          <div className="abscardtwo page2" style={{ paddingBottom: '0px' }}>
            {coolmessage !== '0' ? (
              <p
                style={{
                  fontFamily: 'Montserrat, sans-serif',
                  fontSize: 15,
                  fontWeight: 600,
                  color: 'var(--v2-text2)',
                  textAlign: 'center',
                  margin: '4px 0',
                }}
              >
                ⏳ {coolmessage}
              </p>
            ) : (
              <>
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    gap: 12,
                    marginBottom: 10,
                  }}
                >
                  <div
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: 10,
                      background: 'rgba(6,47,129,0.2)',
                      border: '1px solid rgba(77,139,255,0.2)',
                      borderRadius: 10,
                      padding: '8px 16px',
                    }}
                  >
                    <span
                      style={{
                        fontFamily: 'Montserrat, sans-serif',
                        fontSize: 19,
                        fontWeight: 700,
                        color: 'var(--v2-muted)',
                        textTransform: 'uppercase',
                        letterSpacing: '0.1em',
                      }}
                    >
                      PIN
                    </span>
                    <span
                      style={{
                        fontFamily: 'Montserrat, sans-serif',
                        fontSize: 22,
                        fontWeight: 800,
                        color: 'var(--v2-text)',
                        letterSpacing: 5,
                      }}
                    >
                      {pin}
                    </span>
                  </div>

                  <div
                    onClick={gotochat}
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: 6,
                      background: 'rgba(6,47,129,0.25)',
                      border: '1px solid rgba(77,139,255,0.25)',
                      borderRadius: 10,
                      padding: '10px 16px',
                      cursor: 'pointer',
                    }}
                  >
                    <span style={{ fontSize: 16 }}>💬</span>
                    <span
                      style={{
                        fontFamily: 'Montserrat, sans-serif',
                        fontSize: 14,
                        fontWeight: 700,
                        color: 'var(--v2-text)',
                      }}
                    >
                      Chat
                    </span>
                  </div>

                  <div className="v2_back_btn" onClick={backtohome} style={{ width: 36, height: 36 }}>
                    <img src={back} alt="back" />
                  </div>
                </div>

                {minutes_ago > 60 && (
                  <div
                    onClick={finalizarCarrera}
                    style={{
                      padding: '11px',
                      borderRadius: 10,
                      background: 'rgba(75,7,2,0.5)',
                      border: '1px solid rgba(239,68,68,0.25)',
                      textAlign: 'center',
                      cursor: 'pointer',
                    }}
                  >
                    <p
                      style={{
                        fontFamily: 'Montserrat, sans-serif',
                        fontSize: 14,
                        fontWeight: 700,
                        color: '#f87171',
                        margin: 0,
                      }}
                    >
                      ⚠️ Finalizar Carrera
                    </p>
                  </div>
                )}
              </>
            )}
          </div>

          <div className="abscardthree page2">
            {coolmessage !== '0' ? (
              <p
                style={{
                  fontFamily: 'Montserrat, sans-serif',
                  fontSize: 15,
                  fontWeight: 600,
                  color: 'var(--v2-text2)',
                  textAlign: 'center',
                  margin: '4px 0',
                }}
              >
                {coolmessage}
              </p>
            ) : (
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <img
                  src={foto}
                  alt="vehiculo"
                  style={{
                    width: 64,
                    height: 64,
                    objectFit: 'cover',
                    borderRadius: 12,
                    border: '1px solid var(--v2-border)',
                    flexShrink: 0,
                  }}
                />

                <div style={{ flex: 1, minWidth: 0 }}>
                  <p
                    style={{
                      fontFamily: 'Montserrat, sans-serif',
                      fontSize: 16,
                      fontWeight: 700,
                      color: 'var(--v2-text)',
                      margin: '0 0 3px',
                    }}
                  >
                    {nombre}
                  </p>
                  <p
                    style={{
                      fontFamily: 'Montserrat, sans-serif',
                      fontSize: 14,
                      fontWeight: 600,
                      color: 'var(--v2-text2)',
                      margin: '0 0 3px',
                    }}
                  >
                    {modelo} · {marca}
                  </p>
                  <p
                    style={{
                      fontFamily: 'Montserrat, sans-serif',
                      fontSize: 13,
                      fontWeight: 500,
                      color: 'var(--v2-muted)',
                      margin: 0,
                    }}
                  >
                    🚗 {placa}
                  </p>
                </div>

                <div style={{ flexShrink: 0 }}>
                  {metodo_pago === '0' ? (
                    estado === '3' ? (
                      billing_account === 'me' || billing_account === '' ? (
                        <div
                          onClick={openpagarmodal}
                          style={{
                            padding: '10px 16px',
                            borderRadius: 10,
                            background: 'linear-gradient(135deg, var(--v2-brand-mid), var(--v2-brand))',
                            border: '1px solid rgba(77,139,255,0.3)',
                            cursor: 'pointer',
                            boxShadow: '0 4px 14px rgba(6,47,129,0.4)',
                          }}
                        >
                          <p
                            style={{
                              fontFamily: 'Montserrat, sans-serif',
                              fontSize: 16,
                              fontWeight: 700,
                              color: 'white',
                              margin: 0,
                            }}
                          >
                            💳 Pagar
                          </p>
                        </div>
                      ) : (
                        <p
                          style={{
                            fontFamily: 'Montserrat, sans-serif',
                            fontSize: 16,
                            fontWeight: 600,
                            color: 'var(--v2-green)',
                            margin: 0,
                          }}
                        >
                          ✅ Pagado
                        </p>
                      )
                    ) : null
                  ) : (
                    <p
                      style={{
                        fontFamily: 'Montserrat, sans-serif',
                        fontSize: 16,
                        fontWeight: 600,
                        color: 'var(--v2-green)',
                        margin: 0,
                      }}
                    >
                      ✅ Pagado
                    </p>
                  )}
                </div>
              </div>
            )}
          </div>

          {latEnCero && (
            <div
              style={{
                position: 'absolute',
                zIndex: 999,
                inset: 0,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                background: 'rgba(3,8,26,0.65)',
                backdropFilter: 'blur(4px)',
              }}
            >
              <div className="spinner-border text-light" role="status">
                <span className="visually-hidden">Loading...</span>
              </div>
              <p
                style={{
                  fontFamily: 'Montserrat, sans-serif',
                  fontSize: 14,
                  fontWeight: 600,
                  color: 'var(--v2-text)',
                  marginTop: 14,
                  background: 'rgba(6,47,129,0.35)',
                  border: '1px solid var(--v2-border)',
                  padding: '8px 18px',
                  borderRadius: 999,
                  backdropFilter: 'blur(8px)',
                }}
              >
                En breve iniciará la carrera...
              </p>
            </div>
          )}

          <div id="map" ref={mapRef} className="absolute page1" style={mapContainerStyle} />
        </div>

        {showModal && (
          <div className="v2_modal_overlay">
            <div className="v2_modal_box">
              <p className="v2_modal_title">Método de Pago</p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 4 }}>
                <button className="v2_modal_btn_primary" onClick={pagartarjeta}>
                  💳 Usar Tarjeta
                </button>
                <button className="v2_modal_btn_secondary" onClick={pagarefectivo}>
                  💵 Usar Efectivo
                </button>
                <button className="v2_modal_btn_close" onClick={cerrar}>
                  Cerrar
                </button>
              </div>
            </div>
          </div>
        )}
      </IonContent>
    </IonPage>
  );
};

export default Tracker;