import styled from '@emotion/styled';
import { noop } from 'lodash-es';
import { useLocalStorage } from 'usehooks-ts';

import { useContextSelector } from '@/hooks/useContextSelector';
import { CheckboxIcon, CheckboxOutlineIcon } from '@/icons';

import { ButtonVariant } from '../button/Button';
import {
  ContextMenuItem,
  ContextMenuItemSubtext,
  ContextMenuTrigger,
} from '../contextMenu/ContextMenu';
import { CurrentBeats, CurrentSeconds } from './CurrentTime';
import StudioContext from './StudioContext';
import TransportPopup from './TransportPopup';
import { TransportButton } from './components';

const Wrapper = styled.div`
  display: flex;
  flex-direction: row;
  gap: 5px;
`;

const ClockPopup = ({
  onClose,
  showBoth,
  setDualReadoutPref,
  setSingleReadoutPref,
  dualReadoutPref,
  singleReadoutPref,
}: {
  onClose: () => void;
  showBoth?: boolean;
  setDualReadoutPref: (pref: 'both' | 'beats' | 'seconds') => void;
  setSingleReadoutPref: (pref: 'beats' | 'seconds') => void;
  dualReadoutPref: 'both' | 'beats' | 'seconds';
  singleReadoutPref: 'beats' | 'seconds';
}) => {
  const secondsActive = showBoth
    ? dualReadoutPref === 'both' || dualReadoutPref === 'seconds'
    : singleReadoutPref === 'seconds';
  const beatsActive = showBoth
    ? dualReadoutPref === 'both' || dualReadoutPref === 'beats'
    : singleReadoutPref === 'beats';
  return (
    <TransportPopup title='Clock Settings' onClose={onClose}>
      <ContextMenuItem
        keepMenusOpen
        variant={ButtonVariant.Tertiary}
        icon={secondsActive ? CheckboxIcon : CheckboxOutlineIcon}
        onClick={() => {
          setDualReadoutPref(secondsActive ? 'beats' : 'both');
          setSingleReadoutPref(secondsActive ? 'beats' : 'seconds');
        }}
      >
        Time <ContextMenuItemSubtext>(M:S.MS)</ContextMenuItemSubtext>
      </ContextMenuItem>
      <ContextMenuItem
        keepMenusOpen
        className='mb-1'
        variant={ButtonVariant.Tertiary}
        icon={beatsActive ? CheckboxIcon : CheckboxOutlineIcon}
        onClick={() => {
          setDualReadoutPref(beatsActive ? 'seconds' : 'both');
          setSingleReadoutPref(beatsActive ? 'seconds' : 'beats');
        }}
      >
        Beats
      </ContextMenuItem>
    </TransportPopup>
  );
};

export default function TransportReadouts({
  showBoth,
}: {
  showBoth?: boolean;
}) {
  const [dualReadoutPref, setDualReadoutPref] = useLocalStorage<
    'both' | 'beats' | 'seconds'
  >('aug-26-2025-studio-transport-readouts-both', 'both');
  const [singleReadoutPref, setSingleReadoutPref] = useLocalStorage<
    'beats' | 'seconds'
  >('aug-26-2025-studio-transport-readouts-single', 'beats');
  const previewingOffTimeline = useContextSelector(
    StudioContext,
    (ctx) => ctx.previewController.previewPackage?.offTimeline
  );

  if (showBoth) {
    return (
      <ContextMenuTrigger
        placement='top-middle'
        menuClassName='!bg-transparent'
        ButtonComponent={(props) => (
          <Wrapper {...props}>
            {dualReadoutPref !== 'beats' && (
              <TransportButton
                onClick={noop}
                className='min-w-[85px] font-mono'
                variant={ButtonVariant.Tertiary}
              >
                <span className='-mt-[2px]'>
                  <CurrentSeconds suspend={previewingOffTimeline} />
                </span>
              </TransportButton>
            )}
            {dualReadoutPref !== 'seconds' && (
              <TransportButton
                onClick={noop}
                className='min-w-[85px] font-mono'
                variant={ButtonVariant.Tertiary}
              >
                <span className='-mt-[2px]'>
                  <CurrentBeats suspend={previewingOffTimeline} />
                </span>
              </TransportButton>
            )}
          </Wrapper>
        )}
        ContentsComponent={({ onClose }) => (
          <ClockPopup
            onClose={onClose}
            showBoth={showBoth}
            setDualReadoutPref={setDualReadoutPref}
            setSingleReadoutPref={setSingleReadoutPref}
            dualReadoutPref={dualReadoutPref}
            singleReadoutPref={singleReadoutPref}
          />
        )}
      />
    );
  } else {
    return (
      <ContextMenuTrigger
        placement='top-middle'
        menuClassName='!bg-transparent'
        ButtonComponent={(props) => (
          <Wrapper {...props}>
            {singleReadoutPref !== 'beats' && (
              <TransportButton
                onClick={noop}
                className='min-w-[80px] font-mono'
                variant={ButtonVariant.Tertiary}
              >
                <span className='-mt-[2px]'>
                  <CurrentSeconds suspend={previewingOffTimeline} />
                </span>
              </TransportButton>
            )}
            {singleReadoutPref !== 'seconds' && (
              <TransportButton
                onClick={noop}
                className='min-w-[80px] font-mono'
                variant={ButtonVariant.Tertiary}
              >
                <span className='-mt-[2px]'>
                  <CurrentBeats suspend={previewingOffTimeline} />
                </span>
              </TransportButton>
            )}
          </Wrapper>
        )}
        ContentsComponent={({ onClose }) => (
          <ClockPopup
            onClose={onClose}
            showBoth={showBoth}
            setDualReadoutPref={setDualReadoutPref}
            setSingleReadoutPref={setSingleReadoutPref}
            dualReadoutPref={dualReadoutPref}
            singleReadoutPref={singleReadoutPref}
          />
        )}
      />
    );
  }
}
