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

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

import {
  Save,
  XIcon,
} 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';
import {
  MobileFab,
  MobileLink,
  MobileNavbar,
  MobilePage,
  MobilePopup,
} from './ui/mobile';

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 { isMobile } = useAppConfig();


  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]);


  if (isMobile) {
    return <MobilePopup opened={open} onBackdropClick={() => setOpen(false)} >
      <MobilePage className="flex flex-col">
        <MobileNavbar
          title={Lang.key('select_location_on_map')}
          right={<MobileLink onClick={() => setOpen(false)}><XIcon /></MobileLink>}
        />

        <div className='p-4 flex flex-col  text-center'>
          <div className={cn(clickCoords ? 'animate-pulse' : '')}>
            {findItem?.name ?? findItem?.address}

          </div>
          <div className='text-sm text-gray-500'>
            {findItem?.context ?? ''}
          </div>
        </div>

        <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>

        <div className='text-xs text-gray-500 p-2 text-center'>{Lang.key("click_on_map_to_select_location")}</div>


        <MobileFab
          disabled={!findItem || clickCoords != null}
          text={Lang.key("save")}
          className='fixed left-1/2 bottom-safe-4 transform -translate-x-1/2 z-20'
          icon={<Save size={20} />}
          onClick={() => {
            if (onSelectRef.current) {
              onSelectRef.current(findItem!);
            }
            setOpen(false);
          }}
        />



      </MobilePage>
    </MobilePopup>
  }

  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;
