import React, { useMemo, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { ThumbnailList } from '../ThumbnailList';

import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '../Accordion';

const StudyItem = ({
  date,
  description,
  numInstances,
  modalities,
  isActive,
  onClick,
  isExpanded,
  displaySets,
  activeDisplaySetInstanceUIDs,
  onClickThumbnail,
  onDoubleClickThumbnail,
  onClickUntrack,
  viewPreset = 'thumbnails',
  onThumbnailContextMenu,
  servicesManager, // Tambah servicesManager as a prop
  studyInstanceUid = '',
}: withAppTypes) => {
  const prevShowExpertiseRef = useRef(false);

  /*
   * V1: If the display sets only contain ECG or PDFs, don't show expertise button
   * Tips: use .every
   */
  const shouldShowExpertiseButton = useMemo(() => {
    // If no display sets, don't show expertise by default
    if (!displaySets?.length) {
      return false;
    }

    // Check if all display sets are ECG or PDF
    const allECGOrPDF = displaySets.every(
      ds => ds.modality === 'ECG' || (ds.modality === 'OT' && ds.description === 'PDF')
    );

    // If all display sets are ECG or PDF, don't show expertise button
    return !allECGOrPDF;
  }, [displaySets]);

  /*
   * V2: Show expertise button only if:
   * - There are display sets and active display set
   * - The active display set is not ECG or PDF
   * - If the active display is ECG, don't show expertise button and close the panel reset expertise panel
   *
   * This logic ensures that the expertise button is shown only when appropriate.
   TODO: Need to fix this logic
   */
  // const shouldShowExpertiseButton = useMemo(() => {
  //   // If no display sets or no active display set, didnt show expertise by default
  //   if (!displaySets?.length || !activeDisplaySetInstanceUIDs?.length) {
  //     return false;
  //   }

  //   // Get the active display set UID (first item in the array)
  //   const activeUID = activeDisplaySetInstanceUIDs[0];

  //   // Find the active display set
  //   const activeDisplaySet = displaySets.find(ds => ds.displaySetInstanceUID === activeUID);

  //   // If active display set not found, show expertise button
  //   if (!activeDisplaySet) {
  //     return false;
  //   }

  //   // Hide expertise button for ECG
  //   if (activeDisplaySet.modality === 'ECG') {
  //     return false;
  //   }

  //   // Hide expertise button for PDFs
  //   if (activeDisplaySet.modality === 'OT' && activeDisplaySet.description === 'PDF') {
  //     return false;
  //   }

  //   // Default to showing expertise
  //   return true;
  // }, [displaySets, activeDisplaySetInstanceUIDs]);

  // console.log('Display sets:', displaySets);
  // console.log('Prev show expertise:', prevShowExpertiseRef.current);
  // console.log('Current show expertise button:', shouldShowExpertiseButton);

  // // TODO: Fix this logic
  // // Kalau ganti dari Series yang ada Expertise ke Series yang tidak ada Expertise, deactivate panel (jarang terjadi) (masih bug)
  // useEffect(() => {
  //   // If changing from true to false
  //   if (prevShowExpertiseRef.current === true && shouldShowExpertiseButton === false) {
  //     servicesManager.services.panelService.activatePanel(
  //       `@ohif/extension-cornerstone.panelModule.panelSegmentation-exp-${studyInstanceUid}`,
  //       true
  //     );
  //   }

  //   // Update ref with current value for next comparison
  //   prevShowExpertiseRef.current = shouldShowExpertiseButton;
  // }, [shouldShowExpertiseButton, servicesManager, studyInstanceUid]);

  return (
    <Accordion
      type="single"
      collapsible
      onClick={onClick}
      onKeyDown={() => {}}
      className="flex-shrink-0"
      role="button"
      tabIndex={0}
      defaultValue={isActive ? 'study-item' : undefined}
    >
      <AccordionItem value="study-item">
        <AccordionTrigger className={classnames('hover:bg-accent bg-popover rounded')}>
          <div className="flex h-[40px] flex-1 flex-row">
            <div className="flex w-full flex-row items-center justify-between">
              <div className="flex flex-col items-start text-[13px]">
                <div className="text-white">{date}</div>
                <div className="text-muted-foreground h-[18px] max-w-[160px] overflow-hidden truncate whitespace-nowrap">
                  {description}
                </div>
              </div>
              <div className="text-muted-foreground mr-2 flex flex-col items-end text-[12px]">
                <div className="max-w-[150px] overflow-hidden text-ellipsis">{modalities}</div>
                <div>{numInstances}</div>
              </div>
            </div>
          </div>
        </AccordionTrigger>
        <AccordionContent
          onClick={event => {
            event.stopPropagation();
          }}
        >
          {isExpanded && displaySets && (
            <>
              {/* Expertise Button - Only show if not ECG */}
              {shouldShowExpertiseButton && (
                <div
                  className="bg-primary-dark hover:bg-primary-active mx-8 my-4 cursor-pointer rounded-lg border border-white py-3 text-center text-white"
                  onClick={() => {
                    servicesManager.services.panelService.activatePanel(
                      `@ohif/extension-cornerstone.panelModule.panelSegmentation-exp-${studyInstanceUid}`,
                      true
                    );
                  }}
                >
                  Expertise
                </div>
              )}

              {/* Thumbnails */}
              <ThumbnailList
                thumbnails={displaySets}
                activeDisplaySetInstanceUIDs={activeDisplaySetInstanceUIDs}
                onThumbnailClick={onClickThumbnail}
                onThumbnailDoubleClick={onDoubleClickThumbnail}
                onClickUntrack={onClickUntrack}
                viewPreset={viewPreset}
                onThumbnailContextMenu={onThumbnailContextMenu}
              />
            </>
          )}
        </AccordionContent>
      </AccordionItem>
    </Accordion>
  );
};

StudyItem.propTypes = {
  date: PropTypes.string.isRequired,
  description: PropTypes.string,
  modalities: PropTypes.string.isRequired,
  numInstances: PropTypes.number.isRequired,
  trackedSeries: PropTypes.number,
  isActive: PropTypes.bool,
  onClick: PropTypes.func.isRequired,
  isExpanded: PropTypes.bool,
  displaySets: PropTypes.array,
  activeDisplaySetInstanceUIDs: PropTypes.array,
  onClickThumbnail: PropTypes.func,
  onDoubleClickThumbnail: PropTypes.func,
  onClickUntrack: PropTypes.func,
  viewPreset: PropTypes.string,
  servicesManager: PropTypes.object.isRequired, // Tambah servicesManager prop
  studyInstanceUid: PropTypes.string.string,
};

export { StudyItem };
