import React, { RefObject, useEffect, useRef, useState } from "react"
import { BackArrowSvg } from "../assets/svg/BackArrowSvg";
import { DestinationSearchSvg } from "../assets/svg/DestinationSearchSvg";
import { SourceDotSvg } from "../assets/svg/SourceDotSvg";
import { LocationSvg } from "../assets/svg/LocationSvg"
import { RegionWiseBranches } from "./RegionWiseBranches"
import {CloseIconSvg} from "../assets/svg/closeIconSvg";
import {SearchIconSvg} from "../assets/svg/searchIconSvg"
import EditSvg from "../assets/svg/EditSvg";



const useSwipe = (ref: RefObject<HTMLDivElement>) => {
    const [startY, setStartY] = useState(0);
    const [swipedUp, setSwipedUp] = useState(false);
    const [swipedDown, setSwipedDown] = useState(false);

    useEffect(() => {
        const handleTouchStart = (e: TouchEvent) => {
            setStartY(e.touches[0].clientY);
        };

        const handleTouchEnd = (e: TouchEvent) => {
            if (!ref.current) return;

            const endY = e.changedTouches[0].clientY;
            const deltaY = endY - startY;

            if (deltaY < 0) {
                setSwipedUp(true);
                setSwipedDown(false);
            } else if (deltaY > 0) {
                setSwipedDown(true);
                setSwipedUp(false);
            } else {
                setSwipedUp(false);
                setSwipedDown(false);
            }
        };

        const element = ref.current;

        if (element) {
            element.addEventListener('touchstart', handleTouchStart);
            element.addEventListener('touchend', handleTouchEnd);
        }

        return () => {
            if (element) {
                element.removeEventListener('touchstart', handleTouchStart);
                element.removeEventListener('touchend', handleTouchEnd);
            }
        };
    }, [ref, startY]);

    return { swipedUp, swipedDown, setSwipedUp, setSwipedDown };
};

interface SearchLoadsProps{
    truckNo:string; //truck number
    fetching?:boolean; //Fetching city with lat lng
    expanded:boolean; //state of the input containing Drawer
    setExpanded:(data: any) => void;
    stage?:string; //current stage of search load setStage
    setStage:(data: any) => void;
    searchedCity?:any //data of already searched city
    setSearchedcity:(data: any) => void;
    cityList?:any // city list for searched text
    city?:any // source city detail
    setCity:(data: any) => void;
    cityLoading?:boolean //loading while search for entered ity with text 
    searchLoading?:boolean //loading to get fastag city
    onClickSearchLoads?:any // Function calling search loads mutation
    defaultBranches?:any //data of default selected branches 
    regionBranches:any; //all branches baced on region,
    handleCallback:any; //callback to get seleted braches
    lang?: 'en' | 'ta' | 'hi' | 'kn' | 'bn' | 'te' // user language,
    destinations?:any // selected destinations , 
    placeholder?:string // placeholder acording to language
    is_next_load?:boolean // searching for next load , 
    goBack ?:any // router to go back page
    loading?:boolean // loading while search with source and destination
    setMapSource:(data: any) => void;
    platform?: string
    /** optional localized UI labels; English fallbacks used when omitted */
    translatedWords?: {
        selectDestinations?: string
        searchLoads?: string
        loading?: string
        dragMapToMovePin?: string
        confirmTruckLocation?: string
    }
}

export const SearchLoads = (props: SearchLoadsProps) => {
    const { truckNo, fetching, expanded, setExpanded, stage, setStage, searchedCity, setSearchedcity, cityList, city, setCity, cityLoading, searchLoading, onClickSearchLoads, defaultBranches, regionBranches, handleCallback, lang = 'en', destinations, placeholder, is_next_load, goBack ,loading,setMapSource,platform, translatedWords} = props
    const labels = {
        selectDestinations: translatedWords?.selectDestinations || 'Select destinations',
        searchLoads: translatedWords?.searchLoads || 'Search loads',
        loading: translatedWords?.loading || 'Loading...',
        dragMapToMovePin: translatedWords?.dragMapToMovePin || 'Drag map to move pin',
        confirmTruckLocation: translatedWords?.confirmTruckLocation || 'Confirm truck location',
    }
    const [destinationCities,setDestinationCities]=useState([])
    const [clearAll,setClearAll]=useState(false)
    useEffect(()=>{
        setDestinationCities(defaultBranches)
    },[defaultBranches?.length])
    const swipeRef = useRef<HTMLDivElement>(null);
    const { swipedUp, swipedDown } = useSwipe(swipeRef);
    if (swipedUp && !expanded) {
        setExpanded(true)
    }
    if (swipedDown && expanded) {
        setExpanded(false)
    }
    const expand = () => {
        setExpanded(true)
    }
    const onSelectSource = (city: any) => {
        setCity(city?.city)
        setSearchedcity(city?.city?.name)
        setExpanded(false)
        setMapSource(city?.city?.location)
    }
    const isDestination = stage === 'destination'

    const clearDestinations=()=>{
        handleCallback([])
        setDestinationCities([])
        setClearAll(!clearAll)
    }
    const padding = platform === 'ios' ? 'fr-pt-10' : ''


    return (
        <div>
            {isDestination ? <><div className={`${padding} fr-destination-header-container`} ><div className="fr-destination-header" ><button className="fr-border-none" onClick={ () =>  {typeof goBack.goBack==='function'?goBack.goBack(): goBack.back()}}>
                <BackArrowSvg />
            </button><div><p className="fr-font-bold">{truckNo}</p><p className="fr-center-flex"><SourceDotSvg />&nbsp;&nbsp;<span>{city?.city?.name || searchedCity}</span></p></div></div><div  className="fr-edit-svg" onClick={is_next_load ? () => goBack.back() : () => setStage('source')}>  <EditSvg /></div></div>
                <div className="fr-destination-subheader">
                <div className="fr-font-bold fr-select-destinations">{labels.selectDestinations}</div>
                <div className="fr-searchinput-container">
                    <button className="fr-destination-icon"><DestinationSearchSvg /></button>
                    <div  className="fr-drawer-input" >{(lang && lang !== 'en' ? destinations?.names?.[lang] : null) || destinations?.names?.name}</div>
                    {destinations?.cityIds?.length?<button className="fr-destination-clear-icon" onClick={clearDestinations}><CloseIconSvg/></button>:null}
                </div>
                </div>
                <div className="fr-region-container">
                    <RegionWiseBranches defaultCities={destinationCities} regions={regionBranches}  clearAll={clearAll} callback={handleCallback} multiSelect lang={lang}/>
                </div>
                <div className="fr-search-button-container" ><button id="search_load" className={ `fr-searchload-button ${!destinations?.cityIds?.length||loading?"fr-confirm-button-disable":"" }`} disabled={!destinations?.cityIds?.length||loading} onClick={() => onClickSearchLoads()}>{loading?labels.loading:labels.searchLoads}</button></div></>
                : !searchLoading ?
                    <div className={expanded ? "fr-drawer-open" : "fr-drawer-close"} ref={swipeRef} >
                        <div className="fr-modal-picker"></div>
                        {expanded ? <button className="fr-back-button" onClick={() => setExpanded(false)}>
                            <BackArrowSvg />
                        </button> : null}
                        <div className={`fr-pin-captions ${expanded?"fr-pin-captions-expanded":""}`}>{!expanded ? labels.dragMapToMovePin : labels.confirmTruckLocation}</div>

                        <div className="fr-input-container">
                            <button className="fr-source-icon"><SourceDotSvg /></button>
                            <input type='text' placeholder={placeholder} className="fr-drawer-input" onChange={(e) => setSearchedcity(e.target.value)} value={searchedCity} onClick={expand} />
                            <div className="fr-input-end-icon" onClick={expanded?()=>{setSearchedcity('')}:undefined}>{expanded?<CloseIconSvg/>:<SearchIconSvg />}</div>
                        </div>
                        {!expanded ? <button className={`fr-confirm-button ${fetching || !searchedCity || searchLoading ? "fr-confirm-button-disable" : ""}`} onClick={() => { setStage('destination') }} disabled={!searchedCity || fetching || searchLoading}>{fetching || searchLoading ? labels.loading : labels.confirmTruckLocation}</button> : null
                        }
                        {cityList?.length && expanded ? cityList.map((city: any, i: number) => {
                            return <div key={i} className="fr-city-list-container" onClick={() => onSelectSource(city)}> <LocationSvg /> {(lang && lang !== 'en' ? city?.city?.[lang] : null) || city?.city?.name}</div>
                        }) : cityLoading ?
                            <Skeleton /> : expanded && !cityList?.length ? <div className="fr-city-list-caption">{placeholder}</div> : null}
                    </div> : null}
        </div>

    )
}

const Skeleton = () => {
    return (
        <div className="fr-loading-skeleton">
            <div className="fr-loading-skeleton-item short"></div>
            <div className="fr-loading-skeleton-item"></div>
            <div className="fr-loading-skeleton-item fr-short"></div>
            <div className="fr-loading-skeleton-item"></div>
        </div>
    )
}


