import 'maplibre-gl/dist/maplibre-gl.css';

import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';

import { Save } from 'lucide-react';
import { IoPinSharp } from 'react-icons/io5';
import Map, { Marker } from 'react-map-gl/maplibre';

import { rpc } from '@/api/request';
import { GeopointType } from '@/api/types';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';
import { cn } from '@/lib/utils';

import { Button } from './ui/button';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from './ui/dialog';

export const geoSelectMapCommandRef = React.createRef<GeoSelectMapCommandRefProps>();

type GeoSelectMapCommandRefProps = {
  open: (onSelect: (item: GeopointType) => void, init?: GeopointType) => void;
  close: () => void;
}

export const GeoSelectMapCommand = forwardRef<GeoSelectMapCommandRefProps, {}>((_, ref) => {





  const [findItem, setFindItem] = useState<GeopointType | null>(null);

  const [open, setOpen] = useState(false);

  const onSelectRef = useRef<((item: GeopointType) => void) | null>(null);
  useImperativeHandle(ref, () => ({
    open: (onSelect: (item: GeopointType) => void, init?: GeopointType) => {
      setFindItem(init ?? null);
      setOpen(true);
      onSelectRef.current = onSelect;
    },
    close: () => {
      setOpen(false);
    }
  }));





  const onSave = () => {

  };

  const [clickCoords, setClickCoords] = useState<{ lng: number, lat: number } | null>(null);

  const { color } = useAppConfig();

  useEffect(() => {
    if (clickCoords) {


      rpc.geocode({
        byCoords: {
          latitude: clickCoords.lat,
          longitude: clickCoords.lng,
        },
      }).then((res) => {
        setFindItem(res?.result?.[0] ?? null);
      }).finally(() => {
        setClickCoords(null);
      })

    }
  }, [clickCoords]);

  return (

    <Dialog

      onOpenChange={(open) => {
        setOpen(open);
      }}

      open={open}
    >
      <DialogContent className="!w-[80vw] !max-w-[80vw] sm:!max-w-[80vw] h-[80vh] overflow-hidden ">

        <DialogHeader>
          <DialogTitle className={cn(clickCoords ? 'animate-pulse' : '')}>
            {findItem?.name ?? findItem?.address}
            <div className='text-sm text-gray-500'>
              {findItem?.context ?? ''}
            </div>
          </DialogTitle>
        </DialogHeader>

        <Map
          initialViewState={{
            longitude: findItem?.lng ?? 0,
            latitude: findItem?.lat ?? 0,
            zoom: 14,
          }}
          onClick={(e) => {
            const { lng, lat } = e.lngLat;
            setClickCoords({ lng, lat });
          }}
          style={{
            width: '100%',
            height: 'calc(80vh - 150px)',
          }}
          // Растровые тайлы OSM
          mapStyle={{
            version: 8,
            sources: {
              osm: {
                type: 'raster',
                tiles: [
                  'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
                ],
                tileSize: 256,
                attribution:
                  '',
              },
            },
            layers: [
              {
                id: 'osm',
                type: 'raster',
                source: 'osm',
              },
            ],
          }}
        >
          {!clickCoords && findItem?.lat != null && findItem?.lng != null && (
            <Marker
              longitude={findItem.lng}
              latitude={findItem.lat}
              anchor="bottom"
            >
              <IoPinSharp color={color} size={40} />
            </Marker>
          )}

          {clickCoords && (
            <Marker
              longitude={clickCoords.lng}
              latitude={clickCoords.lat}
              anchor="bottom"

            >
              <IoPinSharp
                className='animate-pulse'
                color={color} size={40} />
            </Marker>
          )}
        </Map>
        <DialogFooter >
          <div className='flex flex-row gap-2 w-full justify-between'>
            <div className='text-xs text-gray-500'>
              {Lang.key("click_on_map_to_select_location")}
            </div>
            <Button
              disabled={!findItem || clickCoords != null}
              variant="outline" onClick={() => {
                if (onSelectRef.current) {
                  onSelectRef.current(findItem!);
                }
                setOpen(false);
              }}>
              <Save size={20} /> {Lang.key("save")}
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>

    </Dialog>
  );
}
);

export default GeoSelectMapCommand;
