import React, { useState, useRef, useEffect } from 'react';
import * as Accordion from '@radix-ui/react-accordion';
import { TripCard } from './TripCard';
import { AccordionTrigger } from '../../lib/common/AccordionTrigger';
import { AccordionContent } from '../../lib/common/AccordionContent';
import { AllLoadsProps, BranchProps, TripData } from './type';
import { ContactCard } from './ContactCard';
import { useInView } from 'react-intersection-observer';
import { ChevronDownIcon } from '@radix-ui/react-icons';
import { useDebounce } from '../../hooks/useDebounce';
import Spinner from '../common/Spinner';

export const AllLoads = (props: AllLoadsProps) => {
  const {
    branchData,
    onClickBranch,
    onClickTrip,
    tripsData,
    translatedLoads,
    translatedTon,
    translatedStops,
    isTripCard,
    contactDetail,
    onClickCall,
    handleInterest,
    translatedDimension = '',
    translatedTarpulin = '',
    onClickShowMore,
    translatedText,
    showMoreLoading,
    onClickChat
  } = props;

  
  const [expandedAccordion, setExpandedAccordion] = useState<string | undefined>();
  const [expandedAccordionData, setExpandedAccordionData] = useState<any>();
  const [isInView, setIsInView] = useState<boolean>(false);
  const [lastExpandedAccordion, setLastExpandedAccordion] = useState<number>();
  const [isShowMoreInView, setShowMoreIsInView] = useState<boolean>(false);
  const showSticky = useDebounce(isInView, 250)
  const { showMore = 'Show more', trafficAgent = 'Traffic agent',speaks = 'Speaks', noRating = 'No Rating', toPay = 'To-Pay', newLabel = 'New', nos = 'Nos', more = 'more' } = translatedText || {};
  
  const triggersRef = useRef<(HTMLButtonElement | null)[]>([]);
  const branchRefs = useRef<{ [key: string]: HTMLButtonElement | null }>({});


  const topRef = useRef<HTMLDivElement | null>(null);

  // Use useInView hooks for view detection
  const { ref: oldLoaderRef } = useInView({
    fallbackInView: true,
    initialInView: false,
    skip: !expandedAccordion,
    onChange: (_inView: boolean, entry) => {    
      if(!topRef.current)return
      
      const topRefPosition = topRef.current.getBoundingClientRect().top;
      topRefPosition > entry.target.getBoundingClientRect().top && setIsInView(true)
      _inView && setIsInView(false)
    },
  });

  const { ref: showMoreref } = useInView({
    fallbackInView: true,
    initialInView: false,
    skip: !expandedAccordion,
    onChange: (_inView: boolean, entry) => {
      // Get the top position of both topRef and current ref
      
      if (topRef.current) {
        const topRefPosition = topRef.current.getBoundingClientRect().top;
        const refPosition = entry.target.getBoundingClientRect().top; // entry.target is the observed element

        if (topRefPosition > refPosition) {
          setShowMoreIsInView(true);
        } else {
          setShowMoreIsInView(false);
        }
      }
    },
  });

  const handleClickBranch = (id: number, name: string) => {   
    setLastExpandedAccordion(id)
    // Only reset states if the branch clicked is different from the current expandedAccordion
    if (expandedAccordion !== name) {
      onClickBranch(id);
      setExpandedAccordion(name);
    }
    // Reset other states
    setShowMoreIsInView(false);
  };  
  useEffect(() => {    
    if(lastExpandedAccordion){
      const targetBranch = branchRefs.current?.[`${lastExpandedAccordion}`];
    if (targetBranch && !expandedAccordion && isInView) {
      targetBranch.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
    if (expandedAccordion) {
      const selectedBranch = branchData.find((branch) => branch?.name === expandedAccordion);
      selectedBranch && setExpandedAccordionData(selectedBranch);
      }
    }
  }, [expandedAccordion, branchData]);

  return (
    <div className="fr-accordion-card">
      <Accordion.Root
        className="AccordionRoot scrollbar"
        type="single"
        collapsible
        value={expandedAccordion}
        onValueChange={(value) => {
          setExpandedAccordion(value); // Update accordion value when triggered
          const selectedBranch = branchData.find((branch) => branch.name === value);
          setExpandedAccordionData(selectedBranch); // Update selected data for the expanded accordion
        }}
      >
        <div style={{ position: 'sticky', top: 0, zIndex: 5}} ref={topRef}></div>
        {expandedAccordionData?.tripsCount > 0 && showSticky && !isShowMoreInView && (
          <Accordion.Item
            className="AccordionItem"
            style={{ position: 'sticky', top: 0, zIndex: 5 }}
            value={expandedAccordionData.name}
            key={expandedAccordionData.id}
          >
            <AccordionTrigger
              onClick={() => {}}
              ref={(el) => {
                if (el) triggersRef.current.push(el);
              }}
              data-name={expandedAccordionData.name}
            >
              <div className="fr-rounded-md fr-square-box">
                <div className="fr-square-box-data fr-trips-count fr-font-md">
                  {expandedAccordionData.tripsCount}
                </div>
                <div className="fr-square-box-data fr-font-regular fr-font-size-11">
                  {translatedLoads}
                </div>
              </div>
              <div className="fr-branch-name">{expandedAccordionData.name}</div>
            </AccordionTrigger>
          </Accordion.Item>
        )}
        {branchData?.map((data: BranchProps) => {
          const { id, name, tripsCount } = data;
          const hideShowMore = tripsCount > tripsData.length && tripsCount > 100;


          return (
              <Accordion.Item className="AccordionItem" value={name} key={id}>
              <AccordionTrigger
                onClick={() => handleClickBranch(id, name)} // Reset on branch click
                ref={(el) => {
                  if (el) triggersRef.current.push(el);
                  branchRefs.current[id] = el;

                }}
                data-name={name}
              >
                <div className="fr-rounded-md fr-square-box">
                  <div className="fr-square-box-data fr-trips-count fr-font-md">
                    {tripsCount}
                  </div>
                  <div className="fr-square-box-data fr-font-regular fr-font-size-11">
                    {translatedLoads}
                  </div>
                </div>
                <div className="fr-branch-name" ref={expandedAccordion === name ? oldLoaderRef : null}>
                  {name}
                </div>
              </AccordionTrigger>
              <AccordionContent>
                {isTripCard ? (
                  <>
                    {(
                      tripsData.map((trip: TripData, i: number) => (
                        <div key={i} className="fr-pt-2">
                          <TripCard
                            tripData={trip}
                            onClickTripCard={() => onClickTrip(trip?.id)}
                            translatedTon={translatedTon}
                            translatedStops={translatedStops}
                            handleInterest={() => handleInterest(trip?.id)}
                            translatedDimension={translatedDimension}
                            translatedTarpulin={translatedTarpulin}
                            employeeLanguages={trip.employee_languages}
                            translatedTexts={{trafficAgent, speaks, noRating, toPay, newLabel, nos, more}}
                          />
                        </div>
                      ))
                    )}
                    {onClickShowMore?
                    <div
                     className="flex justify-center items-center"
                     style={{ paddingTop: '9px', paddingBottom: '5px' }}
                   >
                     <div
                       className= {`text ${showMoreLoading? 'fr-text-slate-600 mr-3':'text-secondary'}`}
                       onClick={() => !showMoreLoading && onClickShowMore()}
                       ref={showMoreref}
                     >
                       {hideShowMore && showMore}
                     </div>
                     {showMoreLoading ?<Spinner />: hideShowMore && <ChevronDownIcon color="#008dd8" height={20} width={20} />}
                   </div>:null}
                  </>
                ) : (
                  <ContactCard contactDetail={contactDetail} onClickCall={onClickCall} onClickChat={onClickChat} trafficAgent={trafficAgent} speaks={speaks}/>
                )}
              </AccordionContent>
            </Accordion.Item>
          );
        })}
      </Accordion.Root>
    </div>
  );
};
