import React, { useEffect, useRef, useState } from 'react';
import { MapContainer, TileLayer, Marker, Polyline, Tooltip } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import dayjs from 'dayjs';
import { Chip, Stack, Typography, Box } from '@mui/material';
import { CloseCircleOutlined } from '@ant-design/icons';
import { useTheme } from '@mui/material/styles';
import CircularLoader from 'components/CircularLoader';

var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);

// Start marker
const startIcon = new L.Icon({
  iconUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  shadowSize: [41, 41]
});

// End marker
const endIcon = new L.Icon({
  iconUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  shadowSize: [41, 41]
});

const MapWithRoute = ({ coordinates, additionalProps, order, setMapOpen }) => {
  console.log('additionalProps', additionalProps);

  const mapRef = useRef(null);
  const theme = useTheme();
  const [routePoints, setRoutePoints] = useState([]);
  const [loading, setLoading] = useState(false);

  // Fit the map to bounds
  useEffect(() => {
    if (mapRef.current && coordinates.length > 0) {
      const bounds = [
        [Math.min(...coordinates.map((c) => c.lat)), Math.min(...coordinates.map((c) => c.lng))],
        [Math.max(...coordinates.map((c) => c.lat)), Math.max(...coordinates.map((c) => c.lng))]
      ];
      mapRef.current.fitBounds(bounds);
    }
  }, [coordinates]);

  // Fetch OSRM Route → REAL ROAD ROUTE
  useEffect(() => {
    const getOSRMRoute = async () => {
      setLoading(true);

      // FIX: If only one coordinate, stop loader and exit
      if (coordinates.length < 2) {
        setRoutePoints([]); // no route
        setLoading(false);
        return;
      }

      const start = coordinates[0];
      const end = coordinates[coordinates.length - 1];

      const url = `https://router.project-osrm.org/route/v1/driving/${start.lng},${start.lat};${end.lng},${end.lat}?overview=full&geometries=geojson`;

      try {
        const res = await fetch(url);
        const data = await res.json();

        if (data.routes?.length) {
          const points = data.routes[0].geometry.coordinates.map(([lng, lat]) => ({
            lat,
            lng
          }));
          setRoutePoints(points);
        }
      } catch (err) {
        console.error('OSRM Error:', err);
      } finally {
        setLoading(false); // ALWAYS STOP LOADING
      }
    };

    getOSRMRoute();
  }, [coordinates]);

  if (!coordinates || coordinates.length === 0) return null;

  const start = coordinates[0];
  const end = coordinates[coordinates.length - 1];
  const center = coordinates[Math.floor(coordinates.length / 2)];

  const InfoItem = ({ label, value }) => (
    <Stack direction="row" spacing={1} alignItems="center">
      <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
        {label}:
      </Typography>
      <Chip label={value || '0.00'} color="primary" sx={{ fontWeight: 700 }} />
    </Stack>
  );

  return (
    <Box sx={{ width: '100%', height: '100vh', position: 'relative', overflow: 'hidden' }}>
      {loading && <CircularLoader />}
      {/* CLOSE BUTTON */}
      <Chip
        label="Close"
        icon={<CloseCircleOutlined style={{ fontSize: 18 }} />}
        onClick={() => setMapOpen(false)}
        sx={{
          position: 'absolute',
          top: 12,
          right: 12,
          zIndex: 2000,
          bgcolor: theme.palette.error.main,
          color: '#fff',
          fontWeight: 600,
          borderRadius: '12px',
          px: 1.5,
          py: 0.5,
          boxShadow: theme.shadows[4],
          cursor: 'pointer',
          '& .MuiChip-icon': { color: '#fff' }
        }}
      />

      {/* MAP */}
      <MapContainer center={center} zoom={14} scrollWheelZoom style={{ height: '100%', width: '100%' }} ref={mapRef}>
        <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />

        {/* START MARKER */}
        <Marker position={start} icon={startIcon}>
          <Tooltip direction="bottom">{`Pickup: ${dayjs(additionalProps.riderStart).format('DD-MM-YYYY hh:mm A')}`}</Tooltip>
        </Marker>

        {/* END MARKER */}
        <Marker position={end} icon={endIcon}>
          <Tooltip direction="bottom">{`Drop: ${dayjs(additionalProps.riderEnd).format('DD-MM-YYYY hh:mm A')}`}</Tooltip>
        </Marker>

        {/* REAL OSRM ROUTE */}
        {routePoints.length > 0 && <Polyline positions={routePoints} pathOptions={{ color: 'blue', weight: 5 }} />}
      </MapContainer>

      {/* BOTTOM DETAILS */}
      <Box
        sx={{
          position: 'absolute',
          bottom: 0,
          width: '100%',
          bgcolor: 'rgba(255,255,255,0.96)',
          p: 2,
          boxShadow: theme.shadows[3],
          zIndex: 1500
        }}
      >
        <Stack direction="row" flexWrap="wrap" rowGap={1.5} columnGap={3} alignItems="center">
          <InfoItem label="Tenant" value={order?.tenantname} />
          <InfoItem label="Rider" value={order?.ridername} />
          <InfoItem label="Pickup" value={order?.pickupcustomer} />
          <InfoItem label="Drop" value={order?.deliverycustomer} />
          <InfoItem label="Kms" value={order?.kms} />
          <InfoItem label="Actual Kms" value={order?.actualkms} />
          <InfoItem label="Rider Kms" value={order?.riderkms} />
        </Stack>
      </Box>
    </Box>
  );
};

export default MapWithRoute;
