import { useConfiguration } from '../../../../core/configuration/useConfiguration';
import { Button, Form, Input } from 'antd';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import React, { useEffect, useRef, useState } from 'react';
import { BookingApi } from '../../booking.api';

export const BookingForm: React.FC = () => {
  const mapContainer = useRef(null);
  const map = useRef(null);
  const [form] = Form.useForm();
  const { mapboxAccessToken } = useConfiguration();
  const [pickup, setPickup] = useState<[number, number] | null>(null);
  const [destination, setDestination] = useState<[number, number] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [totalPrice, setTotalPrice] = useState<number>(0);
  const [directions, setDirections] = useState<any>(null);
  const [tollCost, setTollCost] = useState<number>(0);
  const origin = { lng: -100.0095504, lat: 26.509672 };
  const pricePerKm = 19;

  useEffect(() => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const userLocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          };
          setPickup([userLocation.lng, userLocation.lat]);
          if (map.current) {
            map.current.panTo([userLocation.lng, userLocation.lat]);
          }
        },
        (error) => {
          console.error('Error getting user location:', error);
          setError('Error getting user location: ' + error.message);
        }
      );
    } else {
      console.error('Geolocation is not supported by this browser.');
      setError('Geolocation is not supported by this browser.');
    }
  }, []);

  useEffect(() => {
    if (map.current) return;
    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [0, 0],
      zoom: 2,
      accessToken: mapboxAccessToken,
    });

    map.current.on('load', () => {
      map.current.addSource('route', {
        type: 'geojson',
        data: {
          type: 'Feature',
          properties: {},
          geometry: {
            type: 'LineString',
            coordinates: [],
          },
        },
      });

      map.current.addLayer({
        id: 'route',
        type: 'line',
        source: 'route',
        layout: {
          'line-join': 'round',
          'line-cap': 'round',
        },
        paint: {
          'line-color': '#888',
          'line-width': 8,
        },
      });
    });
  }, [mapboxAccessToken]);

  const onFinish = async () => {
    try {
      if (!pickup || !destination) {
        setError('Please fill in all required fields.');
        return;
      }
      const cost = await BookingApi.getEstimatedCost({
        pickup: pickup.join(','),
        destination: destination.join(','),
      });
      setEstimatedCost(cost);
    } catch (error) {
      console.error('Error calculating estimated cost:', error);
    }
  };

  const calculateRoute = () => {
    setError(null);
    if (!pickup || !destination) {
      setError('Please fill in all required fields.');
      return;
    }

    const directionsService = new window.google.maps.DirectionsService();
    directionsService.route(
      {
        origin: { lat: pickup[1], lng: pickup[0] },
        destination: { lat: destination[1], lng: destination[0] },
        travelMode: window.google.maps.TravelMode.DRIVING,
      },
      (result, status) => {
        if (status === window.google.maps.DirectionsStatus.OK) {
          setDirections(result);
          const distanceToDestination = result.routes[0].legs[0].distance.value / 1000;
          const price = calculatePrice(distanceToDestination);
          setTotalPrice(price);
          fetchTollData(pickup, destination);
        } else if (status === window.google.maps.DirectionsStatus.REQUEST_DENIED) {
          setError('Request denied. Please check your API key and permissions.');
          console.error('Request denied:', status, result);
        } else {
          setError('Error calculating the route: ' + status);
          console.error('Error calculating the route:', status, result);
        }
      }
    );
  };

  const calculatePrice = (distance: number) => {
    return distance * pricePerKm + 558 + tollCost;
  };

  const fetchTollData = async (origin: [number, number], destination: [number, number]) => {
    try {
      const response = await fetch(`https://api.tollguru.com/v1/calc/route?source=${origin[1]},${origin[0]}&destination=${destination[1]},${destination[0]}`, {
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': 'YOUR_TOLLGURU_API_KEY',
    },
  });
  if (response.ok) {
    const data = await response.json();
    const tollCost = data.route.totalTollCost || 0;
    setTollCost(tollCost);
  } else {
    console.error('Error fetching toll data:', response.statusText);
    setError('Error fetching toll data: ' + response.statusText);
  }
} catch (error) {
  console.error('Error fetching toll data:', error);
  setError('Error fetching toll data: ' + error.message);
}
};

return (


<div ref={mapContainer} style={{ width: '100%', height: '400px' }} />
<Form.Item name="pickup" label="Pickup">
<Input
placeholder="Latitude, Longitude"
onChange={(e) =>
setPickup(e.target.value.split(',').map(Number) as [number, number])
}
/>
</Form.Item>
<Form.Item name="destination" label="Destination">
<Input
placeholder="Latitude, Longitude"
onChange={(e) =>
setDestination(e.target.value.split(',').map(Number) as [number, number])
}
/>
</Form.Item>
<Form.Item>

Get Estimated Cost

</Form.Item>
{estimatedCost !== null && 
Estimated Cost: ${estimatedCost.toFixed(2)}
}
{totalPrice !== null && 
Total Price: ${totalPrice.toFixed(2)}
}
{error && 
Error: {error}
}

);
};