import React, { useEffect, useRef } from 'react';
import { useState } from 'react'
import { TopRoutes } from './truckRatesComponents/topRoutes'
import { RouteType, SourceDestinationType, TruckRatesProps, TruckType } from './truckRatesComponents/type'
import { truckTypePrimaryGroup } from '../json/truckTypePrimaryGroup';
import PriceRange from './truckRatesComponents/priceRange';
import RateByTruckGroup from './truckRatesComponents/rateByTruckGroup';
import SelectedRoute from './truckRatesComponents/selectedRoute';
import { DailyRates } from './dailyRates';
import util from '../lib/util';
import { GraphSvg } from '../assets/svg/GraphSvg';
import { ListSvg } from '../assets/svg/ListSvg';
import constants from '../lib/common/constants';

type Section = 'graph' | 'history'
interface ButtonList {
  id: number;
  value: Section;
  icon: (props: {
      fillColor: string;
  }) => React.JSX.Element;
}

type TruckGroup = {
  id: number;
  sort_Name: string;
  param: string;
  type: string;
  truck_type_ids: number[];
}

export const TruckRates = (props: TruckRatesProps) => {
    const {
        initialRoute,
        onTruckGroupSelect,
        onRouteChange,
        priceRange,
        cityPriceData,
        hasLoadMore,
        loadMore,
        priceLoading,
        tripsLoading,
        showBookLink,
        utmSource,
        onPeriodChange,
        rateData,
        showGraph,
        translatedWords
    } = props
    const {
        transportTruckRates = 'Transport Truck Rates',
        truckFreightCalculator = 'Truck Freight Calculator',
        rateHistory = 'Rate history',
        graph = 'Graph',
        history = 'History',
        open: openLabel = 'Open',
        container: containerLabel = 'Container',
    } = translatedWords || {}

    const [route, setRoute] = useState<RouteType>(initialRoute)
    const [activeTab, setActiveTab] = useState('graph');
    const [width, setWidth] = useState(305);
    const containerRef = useRef<HTMLDivElement>(null);

    const [showRatePerTon, setShowRatePerTon] = useState(false)
    const handleSelectRoute = (city: SourceDestinationType) => {
        const selectedRoute = {
            sAliasId: city?.source?.alias?.id || null,
            sourceId: city?.source_id,
            sourceBranchId: city?.source?.branch_id,
            sourceName: city?.source?.alias?.name || city?.source?.name,
            dAliasId: city?.destination?.alias?.id || null,
            destinationId: city?.destination_id,
            destinationBranchId: city?.destination?.branch_id,
            destinationName: city?.destination?.alias?.name || city?.destination?.name
        }
        setRoute({ ...route, ...selectedRoute })
        onRouteChange(selectedRoute)
    }

    const handleSelectCity = (city: SourceDestinationType, type: "source" | "destination") => {
        const selectedRoute = {
            ...(type === "source" ?{sAliasId: city?.source?.alias?.id || null,
            sourceId: city?.source_id,
            sourceBranchId: city?.source?.branch_id,
            sourceName: city?.source?.alias?.name || city?.source?.name} : {}),

            ...(type === "destination" ? {dAliasId: city?.destination?.alias?.id || null,
            destinationId: city?.destination_id,
            destinationBranchId: city?.destination?.branch_id,
                destinationName: city?.destination?.alias?.name || city?.destination?.name
            } : {})
        }
        setRoute({ ...route, ...selectedRoute })
        onRouteChange({ ...route, ...selectedRoute })
    }

    const [selectedIndex, setSelectedIndex] = useState(0);
    
    const tabData = truckTypePrimaryGroup?.map((tab) => {
        const truck_type:any = tab?.truck_type && tab?.truck_type.length > 0 ? tab.truck_type[0] : {}
        const type = truck_type?.truck_type_group_id
        return ({
            id: tab.id,
            sort_Name: tab.name,
            param: tab.param,
            type: (type === 1) ? openLabel : containerLabel,
            truck_type_ids: tab?.truck_type?.map((tt: TruckType) => tt.id) || []
        })
    })

    const handleItemChange = (index: number, truck_group: TruckGroup) => {
      if(showGraph) {
        handleItemChangeshowGraph(index, truck_group)
      }
      else {
        handleItemChangeNonGraph(index, truck_group?.id)
      }
    }

    const handleItemChangeNonGraph = (index: number, primary_group_id: number) => {
        if (tabData[index]?.truck_type_ids?.some(id => constants.ratePerTonTruckTypes.includes(id)))   
            setShowRatePerTon(true);
        else
            setShowRatePerTon(false);
        setSelectedIndex(index);
        onTruckGroupSelect({
            primary_group_id,
            truck_type_ids: tabData[index].truck_type_ids
        })
    };

    const handleItemChangeshowGraph = ( index: number, truck_group: TruckGroup ) => {
      if (tabData[index]?.truck_type_ids?.some((id) => constants.ratePerTonTruckTypes.includes(id)))
        setShowRatePerTon(true);
      else
        setShowRatePerTon(false);
        setSelectedIndex(index);
        onTruckGroupSelect({
          primary_group_id: truck_group.id,
          truck_type_ids: tabData[index].truck_type_ids,
          transport_service: truck_group.param,
        });
        setRoute({...route, transport_service: truck_group.param})
        if (containerRef.current) {
          containerRef.current.scrollTo({
            top: 0,
            behavior: 'smooth',
          });
        }
    
    };

    const buttonList: ButtonList[] = [
      { id: 0, value: 'graph', icon: GraphSvg },
      { id: 1, value: 'history', icon: ListSvg },
    ];

    const handleButtonChange = (section: Section) => {
      setActiveTab(section);
      if (containerRef.current) {
        containerRef.current.scrollTo({
          top: section === 'history' ? width : 0,
          behavior: 'smooth',
        });
      }
    };

    const handleScroll = () => {
        // Detect the scroll position to change tabs
        if (containerRef.current) {
          const scrollTop = containerRef.current.scrollTop;
          if (scrollTop >= width) {
            setActiveTab('history');
          } else {
            setActiveTab('graph');
          }
        }
      };
    
      useEffect(() => {
        const container = containerRef.current;
        if (container) {
          container.addEventListener('scroll', util.debounce(handleScroll));
        }
        const width = window.innerWidth;
        if (width < 640) {
          setWidth(305);
        }
        return () => {
          if (container) {
            container.removeEventListener(
              'scroll',
              util.debounce(handleScroll)
            );
          }
        };
      }, []);

      const onHandlePeriodChange = () => {
        if(onPeriodChange) onPeriodChange()
      }
    return (
        <div className="fr-grid fr-grid-cols-1 md:fr-grid-cols-5 fr-my-5 fr-gap-4">
            <div className={"fr-col-span-3 md:fr-order-2"}>
                <h1 className='fr-text-primary'>{transportTruckRates}</h1>
                <div className="fr-px-3 fr-pb-3 fr-border fr-border-slate-100 fr-bg-white fr-rounded-md">
                    <SelectedRoute route={route} handleSelectCity={handleSelectCity} translatedWords={translatedWords} />
                    <div className='fr-flex fr-overflow-x-auto scrollbar fr-pb-3 fr-mt-1 fr-w-full'>
                        {tabData.map((item, index) => (
                            <div
                                key={item.id}
                                className={selectedIndex === index ? "fr-active-tab-btn" : "fr-tab-btn"}
                                onClick={() => handleItemChange(index, item)}
                            >
                                <p className="fr-text-sm">{item.sort_Name}</p>
                                <p className="fr-truck-type">{`${item.type}`}</p>
                            </div>
                        ))}
                    </div>
                    <div className={`fr-border fr-border-slate-200 fr-rounded-md ${showGraph ? 'fr-px-2 fr-pb-2' : ''}`}>
                      {showGraph ? (<>
                      <ul className="fr-flex fr-justify-end fr-p-2 fr-gap-3 fr-border-b fr-border-slate-200 fr-m-0">
                            {buttonList.map((item) => {
                              const active = activeTab === item.value
                                return (
                                <li
                                    key={item.id}
                                    id={item.value}
                                    className={`${
                                      active
                                        ? 'fr-text-blue-600 btn-border-b fr-border-blue-600'
                                        : 'fr-cursor-pointer btn-border-b fr-border-transparent'
                                    } fr-rounded-sm btn-anime fr-flex fr-items-center fr-gap-1 fr-text-base`}
                                    onClick={() => handleButtonChange(item.value)}
                                >
                                    <item.icon fillColor={active ? '#2563eb' : 'gray'} />
                                    {item.value === 'graph' ? graph : history}
                                </li>
                                );
                            })}
                      </ul>
                      <div id='historys' ref={containerRef} className='fr-h-screen fr-overflow-auto fr-mt-1'>
                        <DailyRates selectedTruckType={route?.transport_service} period={route?.p} rateData={rateData || []} showRatePerTon={showRatePerTon} onPeriodChange={onHandlePeriodChange} translatedWords={translatedWords} />
                        <div className='fr-border fr-border-slate-200 fr-rounded-md fr-mt-3'>
                            <p className='fr-px-3 fr-py-2 fr-border-b-[1px] fr-border-slate-200 fr-text-base'>{rateHistory}</p>
                            <RateByTruckGroup
                                cityPriceData={cityPriceData}
                                loading={tripsLoading}
                                hasLoadMore={hasLoadMore}
                                loadMore={loadMore}
                                showBookLink={showBookLink}
                                utmSource={utmSource}
                                showRatePerTon={showRatePerTon}
                                translatedWords={translatedWords}
                            />
                        </div>
                      </div>
                    </>) : ( <>
                        <PriceRange priceRange={priceRange} loading={priceLoading} showRatePerTon={showRatePerTon} translatedWords={translatedWords}/>
                        <RateByTruckGroup
                            cityPriceData={cityPriceData}
                            loading={tripsLoading}
                            hasLoadMore={hasLoadMore}
                            loadMore={loadMore}
                            showBookLink={showBookLink}
                            utmSource={utmSource}
                            showRatePerTon={showRatePerTon}
                            translatedWords={translatedWords}
                        /> </>)}
                    </div>
                </div>
            </div>
            <div className="fr-col-span-2 h-full overflow-y-auto w-full scrollbar fr-hidden md:fr-block">
                <h1 className='fr-text-primary'>{truckFreightCalculator}</h1>
                <TopRoutes selectedRoute={route} handleSelectRoute={handleSelectRoute} />
            </div>
        </div>
    )
}