import React, { ReactNode, useEffect, useState } from 'react';
import { Badge } from '../../lib/common/badge';
import * as Dialog from '@radix-ui/react-dialog';
import { city } from '../../json/cities';
import { ICity, SourceDestinationState, TruckRatesTranslatedWords } from './type';
import { CloseIconSvg } from '../../assets/svg/closeIconSvg';
import Nodata from '../../lib/common/nodata';
import util from '../../lib/util';

const SelectedRoute = (props: any) => {
  const { route, handleSelectCity, translatedWords } = props;
  const {
    from = 'From',
    to = 'To',
    sourceCity = 'Source City',
    destinationCity = 'Destination City',
    searchCityPlaceholder = 'Search City (min 3 letter)',
    noData,
  }: TruckRatesTranslatedWords = translatedWords || {};

  const initial: SourceDestinationState = {
    source_id: null,
    source: null,
    destination: null,
    destination_id: null,
    alias: null,
  };
  const [selected, setSelected] = useState(initial);
  useEffect(() => {
    setSelected(initial);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selected.source_id, selected.destination_id]);

  const handleSourceSelect = (city: ICity) => {
    const _source = {
      source_id: city.id,
      source: {
        id: city.id,
        branch_id: city.branch_id,
        name: city.city,
        alias: (city.alias as any) || null,
      },
    };
    setSelected({ ...selected, ..._source });
    handleSelectCity({ ...selected, ..._source }, 'source');
  };

  const handleDestinationSelect = (city: ICity) => {
    const _destination = {
      destination_id: city.id,
      destination: {
        id: city.id,
        branch_id: city.branch_id,
        name: city.city,
        alias: (city.alias as any) || null,
      },
    };
    setSelected({ ...selected, ..._destination });
    handleSelectCity({ ...selected, ..._destination }, 'destination');
  };

  return (
    <div className="fr-flex fr-items-center fr-justify-between fr-my-2">
      <DialogBox
        selected={selected}
        onSelect={handleSourceSelect}
        type="source"
        sourceCityLabel={sourceCity}
        destinationCityLabel={destinationCity}
        searchCityPlaceholder={searchCityPlaceholder}
        noData={noData}
        trigger={
          <div className="fr-w-1/2 fr-cursor-pointer">
            <label className="fr-font-bold fr-text-sm">{from}</label>
            <div className="fr-input-box">
              <Badge color="#16a34a" /> {route.sourceName}
            </div>
          </div>
        }
      />
      <DialogBox
        selected={selected}
        onSelect={handleDestinationSelect}
        type="destination"
        sourceCityLabel={sourceCity}
        destinationCityLabel={destinationCity}
        searchCityPlaceholder={searchCityPlaceholder}
        noData={noData}
        trigger={
          <div className="fr-w-1/2 fr-cursor-pointer">
            <label className="fr-font-bold fr-text-sm">{to}</label>
            <div className="fr-input-box">
              <Badge color="#dc2626" /> {route.destinationName}
            </div>
          </div>
        }
      />
    </div>
  );
};

export default SelectedRoute;

interface Props {
  selected: any;
  onSelect: any;
  type: 'source' | 'destination';
  trigger: ReactNode;
  sourceCityLabel?: string;
  destinationCityLabel?: string;
  searchCityPlaceholder?: string;
  noData?: string;
}
export const DialogBox = (props: Props) => {
  const { selected, onSelect, type, trigger, sourceCityLabel = 'Source City', destinationCityLabel = 'Destination City', searchCityPlaceholder = 'Search City (min 3 letter)', noData } = props;
  const [open, setOpen] = React.useState(false);
  const topCity = city.slice(0, 15);
  const [cities, setCities] = useState(topCity);
  const onSearch = (e: any) => {
    const value = e.target.value.toUpperCase();
    const result =
      value.length > 2
        ? city.filter((c: any) => c.city.toUpperCase().includes(value))
        : topCity;
    setCities(result);
  };
  const handleSelect = (city: ICity) => {
    onSelect(city);
    setOpen(false);
    setCities(topCity);
  };
  return (
    <Dialog.Root open={open} onOpenChange={setOpen}>
      <Dialog.Trigger asChild>{trigger}</Dialog.Trigger>
      <Dialog.Portal>
        <Dialog.Overlay className="fr-DialogOverlay" />
        <Dialog.Content className="fr-DialogSheet scrollbar">
          <div className="-fr-mt-3 fr-w-full">
            {type === 'source' ? (
              <div>
                <Badge color="#16a34a" />{' '}
                {selected.source?.name || (
                  <span className="fr-text-slate-500">{sourceCityLabel}</span>
                )}
              </div>
            ) : null}
            {type === 'destination' ? (
              <div>
                <Badge color="#dc2626" />{' '}
                {selected.destination?.name || (
                  <span className="fr-text-slate-500">{destinationCityLabel}</span>
                )}
              </div>
            ) : null}
            <Dialog.Close asChild>
              <button className="fr-IconButton" aria-label="Close">
                <CloseIconSvg />
              </button>
            </Dialog.Close>
            <input
              onChange={e => onSearch(e)}
              placeholder={searchCityPlaceholder}
              autoFocus
              className="fr-w-full fr-mt-2 fr-py-2 fr-border-0 fr-border-b fr-border-slate-200"
            />
          </div>
          <div
            className="fr-mt-3 scrollbar fr-overflow-y"
            style={{ height: 'calc(100vh - 100px)' }}
          >
            {util.isEmptyArray(city) ? (
              <Nodata label={noData} />
            ) : (
              cities.map((_city: ICity, index: number) => {
                return (
                  <button
                    key={`${_city.id}${index}`}
                    onClick={() => handleSelect(_city)}
                    className={`fr-w-full ${
                      index % 2 === 0 ? 'fr-bg-slate-50' : 'fr-bg-white'
                    } fr-border-0 fr-py-3 fr-text-left fr-cursor-pointer fr-border-b fr-border-slate-200 hover:bg-slate-100`}
                  >
                    {_city?.city}, {_city?.state}
                  </button>
                );
              })
            )}
          </div>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
};
