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

import {
  CopyIcon,
  Edit,
  MapIcon,
  SearchIcon,
  Trash2,
} from 'lucide-react';
import CountryPhoneInput from 'react-phone-input-2';

import { rpc } from '@/api/request';
import { GeopointType } from '@/api/types';
import { geoSearchCommandRef } from '@/componentsRoot/GeoSearchCommand';
import { geoSelectMapCommandRef } from '@/componentsRoot/GeoSelectMapCommand';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  copyTextToClipboard,
  getAnyGeoPointFormData,
} from '@/utils/helpers';

import { Lang } from '../../../../../lang/Lang';
import DataDescription from '../components/DataDescription';
import DataLabel from '../components/DataLabel';
import { ItemDataProps } from '../types';

export const GeoPointData = (props: ItemDataProps) => {


  const [addEntrance, setAddEntrance] = useState<boolean>(false);
  const [addFloor, setAddFloor] = useState<boolean>(false);
  const [addApartment, setAddApartment] = useState<boolean>(false);
  const [addPhone, setAddPhone] = useState<boolean>(false);
  const [addComment, setAddComment] = useState<boolean>(false);


  const [freeMode, setFreeMode] = useState<boolean>(false);

  const [search, setSearch] = useState<string>('');
  const [open, setOpen] = useState<boolean>(false);

  useEffect(() => {
    if (freeMode) {
      setSearch('');
    }
  }, [freeMode]);

  useEffect(() => {
    if (search) {
      handleSearch(search);
    }
  }, [search]);

  const [localValue, setLocalValue] = useState<GeopointType | null>(props.getValue() ?? null);

  useEffect(() => {
    props.setValue(localValue);
  }, [localValue]);


  const mapModal = useRef<any>(null);

  const openMap = () => {
    if (localValue?.lat && localValue?.lng) mapModal.current.open(localValue);
    else {
      if (props.getDataValue()) {
        let cords = getAnyGeoPointFormData(
          props.getDataValue(),
          props.getDataStructure()
        );

        mapModal.current.open(cords);
      }
    }
  };



  const [loading, setLoading] = useState<boolean>(false);

  const timeout = useRef<any>(null);

  const [byStringData, setByStringData] = useState<GeopointType[]>([]);

  const handleSearch = (newValue: string) => {
    clearTimeout(timeout.current);

    timeout.current = setTimeout(() => {
      setLoading(true);
      rpc.geocode({
        byString: {
          string: newValue,
        },
      }).then((res) => {
        setByStringData(res.result ?? []);
      })
        .finally(() => {
          setLoading(false);
        });
    }, 300);
  };

  const handleChange = (id: string) => {

    let _val = byStringData.find((e) => e.uuid == id);
    if (_val) {
      setLocalValue((prev) => {
        return {
          ..._val,
          meta: prev?.meta,
        }
      });

    }
  };

  useEffect(() => {

    if (!localValue) return;
    if (!localValue.meta) return;

    if (!!localValue?.meta?.entrance) {
      setAddEntrance(true);
    }
    if (!!localValue?.meta?.floor) {
      setAddFloor(true);
    }
    if (!!localValue?.meta?.apartment) {
      setAddApartment(true);
    }
    if (!!localValue?.meta?.phone) {
      setAddPhone(true);
    }
    if (!!localValue?.meta?.comment) {
      setAddComment(true);
    }



  }, []);


  if (props.onlyShow || !props.structure.editable) {



    return <>
      <DataLabel {...props} />
      <DataDescription {...props} />

      <Button variant="secondary" className='w-full  h-auto flex justify-between '
        onClick={() => {

          if (localValue?.lat && localValue?.lng) {

            let copy = [];
            if (localValue.address || localValue.name) copy.push(localValue.address ?? localValue.name);
            copy.push('\n');
            if (localValue.meta?.entrance) {

              copy.push(Lang.key('entrance') + ': ');
              copy.push(localValue.meta.entrance);
              copy.push('\n');
            }
            if (localValue.meta?.floor) {
              copy.push(Lang.key('floor') + ': ');
              copy.push(localValue.meta.floor);
              copy.push('\n');
            }
            if (localValue.meta?.apartment) {
              copy.push(Lang.key('apartment') + ': ');
              copy.push(localValue.meta.apartment);
              copy.push('\n');
            }
            if (localValue.meta?.phone) {
              copy.push(Lang.key('phone') + ': ');
              copy.push(localValue.meta.phone);
              copy.push('\n');
            }
            if (localValue.meta?.comment) {
              copy.push(Lang.key('comment') + ': ');
              copy.push(localValue.meta.comment);
              copy.push('\n');
            }

            copyTextToClipboard(copy.join(' '));
          }
        }}
      >
        <div className='flex flex-col items-start gap-0'>{localValue?.lat && localValue?.lng ? <>
          <div>{localValue?.address ?? localValue?.name ?? ""}</div>
          <div>
            {!!localValue.meta?.entrance && <span className='text-xs text-gray-500'> {Lang.key('entrance')}: {localValue.meta.entrance}</span>}
            {!!localValue.meta?.floor && <span className='text-xs text-gray-500'> {Lang.key('floor')}: {localValue.meta.floor}</span>}
            {!!localValue.meta?.apartment && <span className='text-xs text-gray-500'> {Lang.key('apartment')}: {localValue.meta.apartment}</span>}
            {!!localValue.meta?.phone && <span className='text-xs text-gray-500'> {Lang.key('phone')}: +{localValue.meta.phone}</span>}
            {!!localValue.meta?.comment && <span className='text-xs text-gray-500'> {Lang.key('comment')}: {localValue.meta.comment}</span>}
          </div>
        </> : Lang.key('no_data_short')}
        </div>
        <CopyIcon />
      </Button>

    </>



  }


  return (
    <div className=''>
      <DataLabel {...props} />
      <DataDescription {...props} />
      <div className='pr-2' >



        <div className='w-full flex items-center gap-1'>
          <Button
            disabled={!localValue?.lat || !localValue?.lng}
            onClick={() => {
              setFreeMode(!freeMode);
            }}
            variant="outline"
            tooltip={Lang.key(freeMode ? 'search_address' : 'edit_address')}
            aria-label={Lang.key(freeMode ? 'search_address' : 'edit_address')}
          >
            {freeMode ? <SearchIcon /> : <Edit />}
          </Button>

          {freeMode ? <div className='flex-1'>
            <Input
              className=' w-full'
              placeholder={Lang.key('address')}
              value={localValue?.address ?? localValue?.name ?? ''}
              onChange={(e) => {
                setLocalValue((prev) => {
                  return {
                    ...prev,
                    address: e.target.value,
                    name: e.target.value,
                  };
                });
              }}
            /> </div> : <>
            <Button
              variant="outline"
              className='flex-1 justify-between'
              onClick={() => {
                geoSearchCommandRef.current?.open((item) => {
                  setLocalValue(item);
                }, localValue?.address ?? localValue?.name ?? '');
              }}>

              {localValue?.address ?? localValue?.name ?? Lang.key('select_value_address')}
              <SearchIcon />
            </Button>

            <Button
              variant="outline"
              tooltip={Lang.key('select_on_map')}
              aria-label={Lang.key('select_on_map')}
              onClick={() => {
                geoSelectMapCommandRef.current?.open((item) => {
                  setLocalValue(item);
                }, localValue ?? undefined);
              }}>
              <MapIcon />
            </Button>


          </>}





        </div>





        {addEntrance && <div className='mt-2'>

          <Label>{Lang.key('entrance')}</Label>
          <div className='flex '>
            <div className='flex-1'>
              <Input
                className='w-full'
                placeholder={Lang.key('entrance')}
                value={localValue?.meta?.entrance ?? ''}
                onChange={(e) => {
                  setLocalValue((prev) => {
                    if (!prev) return null;
                    return {
                      ...prev,
                      meta: {
                        ...prev.meta,
                        entrance: e.target.value,
                      },
                    };
                  });
                }}

              />
            </div>
            <Button
              onClick={() => {
                setAddEntrance(false);
              }}
              variant="link"
              size="icon"
              tooltip={Lang.key('remove_entrance')}
              aria-label={Lang.key('remove_entrance')}
            >
              <Trash2 />
            </Button>
          </div>
        </div>}

        {addFloor && <div className='mt-2'>

          <Label>{Lang.key('floor')}</Label>
          <div className='flex '>
            <div className='flex-1'>
              <Input
                placeholder={Lang.key('floor')}
                value={localValue?.meta?.floor ?? ''}
                onChange={(e) => {
                  setLocalValue((prev) => {
                    if (!prev) return null;
                    return {
                      ...prev,
                      meta: {
                        ...prev.meta,
                        floor: e.target.value,
                      },
                    };
                  });
                }}
              />
            </div>
            <Button
              onClick={() => {
                setAddFloor(false);
              }}
              variant="link"
              size="icon"
              tooltip={Lang.key('remove_floor')}
              aria-label={Lang.key('remove_floor')}
            >
              <Trash2 />
            </Button>
          </div>
        </div>}

        {addApartment && <div className='mt-2'>

          <Label>{Lang.key('apartment')}</Label>
          <div className='flex '>
            <div className='flex-1'>
              <Input
                placeholder={Lang.key('apartment')}
                value={localValue?.meta?.apartment ?? ''}
                onChange={(e) => {
                  setLocalValue((prev) => {
                    if (!prev) return null;
                    return {
                      ...prev,
                      meta: {
                        ...prev.meta,
                        apartment: e.target.value,
                      },
                    };
                  });
                }}
              />
            </div>
            <Button
              onClick={() => {
                setAddApartment(false);
              }}
              variant="link"
              size="icon"
              tooltip={Lang.key('remove_apartment')}
              aria-label={Lang.key('remove_apartment')}
            >
              <Trash2 />
            </Button>
          </div>
        </div>}

        {addPhone && <div className='mt-2'>


          <Label>{Lang.key('phone')}</Label>

          <div className='flex '>
            <div className='flex-1'>
              <CountryPhoneInput
                containerClass="!w-full phone-input-field phone-input-field--no-flag "
                inputClass="ant-input !w-full isLogin"
                placeholder={Lang.key('phone')}
                value={!!localValue?.meta?.phone ? String(localValue?.meta?.phone) : undefined}
                onChange={(val) => {
                  setLocalValue((prev) => {
                    if (!prev) return null;
                    return {
                      ...prev,
                      meta: {
                        ...prev.meta,
                        phone: val ? Number(val) : undefined,
                      },
                    };
                  });
                }}

              />
            </div>
            <Button
              onClick={() => {
                setAddPhone(false);
              }}
              variant="link"
              size="icon"
              tooltip={Lang.key('remove_phone')}
              aria-label={Lang.key('remove_phone')}
            >
              <Trash2 />
            </Button>
          </div>

        </div>}

        {addComment && <div className='mt-2'>

          <Label>{Lang.key('comment')}</Label>
          <div className='flex '>
            <div className='flex-1'>
              <Textarea

                placeholder={Lang.key('comment')}
                value={localValue?.meta?.comment ?? ''}
                onChange={(e) => {
                  setLocalValue((prev) => {
                    if (!prev) return null;
                    return {
                      ...prev,
                      meta: {
                        ...prev.meta,
                        comment: e.target.value,
                      },
                    };
                  });
                }}
              />
            </div>
            <Button
              onClick={() => {
                setAddComment(false);
              }}
              variant="link"
              size="icon"
              tooltip={Lang.key('remove_comment')}
              aria-label={Lang.key('remove_comment')}
            >
              <Trash2 />
            </Button>
          </div>
        </div>}

        <div className='flex flex-wrap gap-1 mt-2'>
          {!addEntrance && <Badge
            variant={"outline"}
            onClick={() => setAddEntrance(true)}

            className='cursor-pointer'
          >{Lang.key('add_entrance')}</Badge>}

          {!addFloor && <Badge
            variant={"outline"}
            onClick={() => setAddFloor(true)}
            className='cursor-pointer'
          >{Lang.key('add_floor')}</Badge>}
          {!addApartment && <Badge
            variant={"outline"}
            onClick={() => setAddApartment(true)}
            className='cursor-pointer'
          >{Lang.key('add_apartment')}</Badge>}
          {!addPhone && <Badge
            variant={"outline"}
            onClick={() => setAddPhone(!addPhone)}
            className='cursor-pointer'
          >{Lang.key('add_phone')}</Badge>}
          {!addComment && <Badge
            variant={"outline"}
            onClick={() => setAddComment(!addComment)}
            className='cursor-pointer'
          >{Lang.key('add_comment')}</Badge>}
        </div>
      </div>



    </div>
  );
}
