import React, { useEffect, useRef } 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, Grid, IconButton, Stack, ToggleButton, Typography } from '@mui/material';
import DisabledByDefaultOutlinedIcon from '@mui/icons-material/DisabledByDefaultOutlined';
import { useTheme } from '@emotion/react';
import { CloseCircleOutlined } from '@ant-design/icons';

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

// Define custom icon for start and end markers
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],
  popupAnchor: [1, -34],
  shadowSize: [41, 41]
});

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],
  popupAnchor: [1, -34],
  shadowSize: [41, 41]
});

const MapWithRoute = ({ coordinates, additionalProps, order, setMapOpen }) => {
  console.log('setMapOpen:', typeof setMapOpen);
  console.log('coordinates', coordinates);
  console.log(additionalProps.riderStart);
  console.log(additionalProps.riderEnd);
  console.log('order', order);
  const mapRef = useRef(null);

  const theme = useTheme;

  useEffect(() => {
    if (mapRef.current && coordinates.length > 0) {
      const bounds = calculateBounds(coordinates);
      mapRef.current.fitBounds(bounds);
    }
  }, [coordinates]);

  const calculateBounds = (coords) => {
    const latitudes = coords.map((coord) => coord.lat);
    const longitudes = coords.map((coord) => coord.lng);
    const minLat = Math.min(...latitudes);
    const maxLat = Math.max(...latitudes);
    const minLng = Math.min(...longitudes);
    const maxLng = Math.max(...longitudes);
    return [
      [minLat, minLng],
      [maxLat, maxLng]
    ];
  };

  const dottedOptions = { color: 'blue', weight: 8, dashArray: '4 4' };
  const length = coordinates.length;
  const midlenght = Math.round(coordinates.length / 2);
  const start = coordinates[0];
  const end = coordinates[length - 1];
  const center = coordinates[midlenght];

  const showList = (primary, secondary) => {
    return (
      <Stack direction="row" spacing={1} alignItems="center">
        <Typography variant="h5" color="text.primary" sx={{ fontSize: 13 }}>
          {primary}:
        </Typography>
        <Chip label={secondary || 'N/A'} color="primary" variant="combined" size="small" sx={{ fontWeight: 1000, fontSize: 14 }} />
      </Stack>
    );
  };

  return (
    coordinates &&
    coordinates.length > 0 && (
      <div
        id="map"
        style={{
          width: '100%',
          height: '90vh',
          margin: '0 auto',
          position: 'relative'
        }}
      >
        <Chip
          label="close"
          color="primary"
          variant="combined"
          onClick={() => setMapOpen(false)}
          size="large"
          sx={{
            position: 'absolute',
            top: 8,
            right: 8,
            zIndex: 1000,
            '&:hover': {},
            cursor: 'pointer'
          }}
          icon={<CloseCircleOutlined />}
        />

        {/* Overlay */}
        <Stack
          direction="row"
          gap={2}
          flexWrap="wrap"
          alignItems="center"
          justifyContent="flex-start"
          sx={{
            position: 'absolute',
            bottom: 0,
            zIndex: 1000,
            left: 0,
            right: 0,
            px: { xs: 1, custom500: 2, custom700: 2 },
            py: { xs: 1, custom500: 2, custom900: 4 },
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            maxWidth: '100%',
            width: 'auto',
            boxShadow: (theme) => theme.shadows[3]
          }}
        >
          {showList('Tenant', order?.tenantname)}
          {showList('Rider', order?.ridername)}
          {showList('Pickup', order?.pickupcustomer)}
          {showList('Drop', order?.deliverycustomer)}
          {showList('Kms', order?.kms)}
          {showList('Actual kms', order?.actualkms)}
          {showList('Rider kms', order?.riderkms)}
        </Stack>

        {/* Map */}
        <MapContainer center={center} zoom={15} scrollWheelZoom={false} style={{ height: '100%', width: '100%' }} ref={mapRef}>
          <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
          <Marker position={start} icon={startIcon}>
            <Tooltip direction="bottom">
              <span>
                {`Pickup Point: ${dayjs(additionalProps.riderStart).utc().format('DD-MM-YYYY')} (${dayjs(additionalProps.riderStart)
                  .utc()
                  .format('hh:mm A')})`}
              </span>
            </Tooltip>
          </Marker>
          <Marker position={end} icon={endIcon}>
            <Tooltip direction="bottom">
              <span>
                {`Drop Point: ${dayjs(additionalProps.riderEnd).utc().format('DD-MM-YYYY')} (${dayjs(additionalProps.riderEnd)
                  .utc()
                  .format('hh:mm A')})`}
              </span>
            </Tooltip>
          </Marker>
          <Polyline pathOptions={dottedOptions} positions={coordinates} />
        </MapContainer>
      </div>
    )
  );
};

export default MapWithRoute;
