import styled from '@emotion/styled';
import clsx from 'clsx';
import { uniqBy } from 'lodash-es';
import { useCallback, useEffect, useMemo, useState } from 'react';

import { FocusedObjectContext } from '@/app/(root)/create/v2/useFocusedObject';
import useClickDrag from '@/hooks/useClickDrag';
import { useContextSelector } from '@/hooks/useContextSelector';
import {
  CaretDownIcon,
  CopyIcon,
  EditIcon,
  MicrophoneIcon,
  MoreVerticalIcon,
  PlaylistIcon,
  TakeLanesIcon,
  TrashIcon,
  TriangleDownIcon,
  VolumeMuteIcon,
  VolumeOnIcon,
  WaveformIcon,
} from '@/icons';
import sanitizeNumber from '@/utils/sanitizeNumber';

import Button, { ButtonVariant } from '../button/Button';
import { ResponsiveChild, useContainer } from '../containerQueries/components';
import {
  ContextMenuItem,
  ContextMenuTrigger,
} from '../contextMenu/ContextMenu';
import Modal from '../modal/Modal';
import SpinnerSVG from '../svg/SpinnerSVG';
import TextareaV2 from '../textarea/TextareaV2';
import { Tooltip } from '../tooltip/Tooltip';
import AudioInputStreamContext from './AudioInputStreamContext';
import {
  InstrumentPickerMenuContents,
  getInstrumentName,
  getInstrumentTypeIcon,
  isNewTrackOrCurrentInstrumentName,
} from './ContextualBar/ContextualBarInstrumentPicker';
import StudioContext from './StudioContext';
import StudioHorizontalFader, {
  dbToZeroOne,
  multiplierToScaledZeroOne,
  scaledZeroOneToMultiplier,
} from './StudioHorizontalFader';
import { addAndSelectTakeLane } from './actions/addTakeLane';
import { combineActions } from './actions/combineActions';
import deleteTrack from './actions/deleteTrack';
import { selectTrackIds } from './actions/dragSelect';
import duplicateTrack from './actions/duplicateTrack';
import focusTracks from './actions/focusTracks';
import renameTrack from './actions/renameTrack';
import reorderTracks from './actions/reorderTracks';
import setTrackAmplitude from './actions/setTrackAmplitude';
import setTrackArmed from './actions/setTrackArmed';
import setTrackBalance from './actions/setTrackBalance';
import setTrackHeight from './actions/setTrackHeight';
import setTrackInput from './actions/setTrackInput';
import toggleTakeLanes from './actions/toggleTakeLanes';
import toggleTrackMute from './actions/toggleTrackMute';
import toggleTrackSolo from './actions/toggleTrackSolo';
import updateTrack from './actions/updateTrack';
import { defaultStudioTrackHeight, minimumTrackHeight } from './createTrack';
import { getEffectivelyMutedTracks, getTracksById } from './selectors';
import shouldShowTakeLanes from './shouldShowTakeLanes';
import { InputSpec, InstrumentSpec } from './types';
import { formatDecibelValue } from './valueFormatting';

export const Wrapper = styled.div<{ selected: boolean }>`
  width: 100%;
  height: 100%;
  cursor: pointer;
  position: relative;
  .inherit-bg {
    background-color: rgb(var(--rgb-background-primary));
  }
  .hover-only {
    opacity: 0;
  }
  .not-hover-only {
    opacity: 1;
  }
  &:hover {
    .hover-only {
      opacity: 1;
    }
    .not-hover-only {
      opacity: 0;
    }
  }
  padding-left: 24px;
  ${({ selected }) =>
    selected
      ? `
      background-color: var(--color-background-tertiary);
      .inherit-bg {
        background-color: var(--color-background-tertiary);
      }
    `
      : `
      &:hover {
        background-color: var(--color-background-secondary);
        .inherit-bg {
          background-color: var(--color-background-secondary);
        }
      }
  `}
`;

export const Outline = styled.div`
  border: 1px solid transparent;
  height: 100%;
  width: 100%;
  position: relative;
  z-index: 1;
`;

export const Grid = styled.div`
  height: 100%;
  max-height: 84px;
  padding: 3px;
  display: grid;
  grid-template-rows: 24px 24px 24px;
  gap: 4px;
  min-height: 0;
`;

export const HeaderRow = styled.div`
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 4px;
  position: relative;
`;

export const TrackHeaderButton = styled(Button)`
  width: 24px;
  height: 24px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--color-background-glass-thin);
  color: var(--color-foreground-tertiary);
`;

const AudioInputDropdownButton = styled(TrackHeaderButton)`
  width: 100%;
  font-size: 12px;
  padding-left: 4px;
  justify-content: stretch;
  position: relative;
  > * {
    width: 100%;
    flex-direction: row-reverse;
    justify-content: space-between;
    gap: 2px;
  }
  svg {
    width: 20px;
    height: 20px;
    margin: 0;
    padding: 4px;
  }
`;

const TruncatedLabel = styled.span`
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  position: absolute;
  left: 0;
  right: 20px;
  top: 0;
  bottom: 0;
  display: flex;
  align-items: center;
`;

const FaderWrapper = styled.div`
  height: 24px;
  border-radius: 5px;
  flex: 1;
  &.highlight-fader-wrapper {
    padding: 0 4px;
    background-color: var(--color-background-glass-thin);
  }
`;

const SoloButton = ({ trackId }: { trackId: string }) => {
  const setState = useContextSelector(
    StudioContext,
    (context) => context.setState
  );
  const trackSolo = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.solo
  );
  const toggleSolo = useCallback(
    (e: React.MouseEvent<HTMLButtonElement>) => {
      setState(toggleTrackSolo(trackId, e.shiftKey || e.ctrlKey || e.metaKey));
    },
    [setState, trackId]
  );
  return (
    <TrackHeaderButton
      onClick={toggleSolo}
      variant={trackSolo ? ButtonVariant.Primary : ButtonVariant.Standard}
      style={
        trackSolo
          ? {
              color: 'var(--color-background-primary)',
              backgroundColor: 'var(--color-foreground-primary)',
            }
          : {}
      }
      icon={<span className='text-[10px]'>S</span>}
    />
  );
};

const MuteButton = ({ trackId }: { trackId: string }) => {
  const setState = useContextSelector(
    StudioContext,
    (context) => context.setState
  );
  const trackMute = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.mute
  );
  const trackColor = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.color ?? '#ffffff'
  );
  const toggleMute = useCallback(() => {
    setState(toggleTrackMute(trackId));
  }, [setState, trackId]);
  const unmutedButtonStyle = useMemo(
    () => ({
      backgroundColor: trackColor,
      color: 'var(--color-foreground-primary)',
    }),
    [trackColor]
  );
  return (
    <TrackHeaderButton
      style={trackMute ? undefined : unmutedButtonStyle}
      onClick={toggleMute}
      icon={trackMute ? VolumeMuteIcon : VolumeOnIcon}
    />
  );
};

export const TrackNameContainer = styled.div`
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-family: 'PP Neue Montreal', sans-serif;
  font-size: 14px;
  flex-grow: 1;
  flex-shrink: 1;
  min-width: 0;
`;

export const HeaderSideButtons = styled.div`
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  display: flex;
  gap: 0;
`;

export const ColoredBorder = styled.div`
  height: 100%;
  width: 24px;
  color: var(--color-background-primary);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 4px 1px;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
`;

export const TrackBorderItem = styled.button`
  border: none;
  border-radius: 4px;
  &:hover {
    background-color: var(--color-background-glass-dense);
    cursor: pointer;
  }
  font-size: 12px;
  position: relative;
  width: 22px;
  height: 24px;
  font-weight: 600;
  text-align: center;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
`;

const TrackMenuButton = ({
  trackId,
  setRenaming,
}: {
  trackId: string;
  setRenaming: (renaming: boolean) => void;
}) => {
  const setState = useContextSelector(
    StudioContext,
    (context) => context.setState
  );
  const isReadOnlyMode = useContextSelector(
    StudioContext,
    (context) => context.isReadOnlyMode
  );
  const showingTakeLanes = useContextSelector(StudioContext, (context) =>
    shouldShowTakeLanes(getTracksById(context.state)[trackId])
  );
  const hasTakeLanes = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.takeLanes.length > 0
  );
  return (
    <ContextMenuTrigger
      placement='bottom-right'
      ButtonComponent={(props) => (
        <TrackHeaderButton
          className='!bg-transparent'
          {...props}
          icon={<MoreVerticalIcon />}
        />
      )}
      ContentsComponent={() => (
        <>
          {!isReadOnlyMode ? (
            <>
              <ContextMenuItem
                icon={<PlaylistIcon />}
                onClick={(e) => {
                  setState(addAndSelectTakeLane(trackId));
                  e.stopPropagation();
                }}
              >
                Add Take Lane
              </ContextMenuItem>
              {hasTakeLanes && (
                <ContextMenuItem
                  icon={<TakeLanesIcon />}
                  onClick={() => {
                    setState(toggleTakeLanes(trackId));
                  }}
                >
                  {showingTakeLanes ? 'Hide Take Lanes' : 'Show Take Lanes'}
                </ContextMenuItem>
              )}
              <ContextMenuItem
                icon={<TrashIcon />}
                onClick={() => {
                  setState(deleteTrack(trackId));
                }}
              >
                Delete
              </ContextMenuItem>
              <ContextMenuItem
                icon={<CopyIcon />}
                onClick={() => {
                  setState(duplicateTrack(trackId));
                }}
              >
                Duplicate
              </ContextMenuItem>
              <ContextMenuItem
                icon={<EditIcon />}
                onClick={() => {
                  setRenaming(true);
                }}
              >
                Rename
              </ContextMenuItem>
            </>
          ) : (
            <>
              <ContextMenuItem disabled icon={<TrashIcon />}>
                Delete (Read-only)
              </ContextMenuItem>
              <ContextMenuItem disabled icon={<CopyIcon />}>
                Duplicate (Read-only)
              </ContextMenuItem>
              <ContextMenuItem disabled icon={<EditIcon />}>
                Rename (Read-only)
              </ContextMenuItem>
            </>
          )}
        </>
      )}
    />
  );
};

const AmplitudeFader = ({ trackId }: { trackId: string }) => {
  const setState = useContextSelector(
    StudioContext,
    (context) => context.setState
  );
  const trackAmplitude = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.amplitude
  );
  const setPlaybackTrackAmplitude = useContextSelector(
    StudioContext,
    (context) => context.playbackController.setTrackGain
  );
  const getTrackMeter = useContextSelector(
    StudioContext,
    (ctx) => ctx.playbackController.getTrackMeter
  );
  const trackColor = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.color ?? '#ffffff'
  );
  return (
    <FaderWrapper>
      <StudioHorizontalFader
        defaultValue={dbToZeroOne(0)}
        anchorValue={dbToZeroOne(0)}
        value={multiplierToScaledZeroOne(trackAmplitude)}
        formatValue={(x) => formatDecibelValue(scaledZeroOneToMultiplier(x))}
        onChange={(value) => {
          const multiplier = sanitizeNumber(scaledZeroOneToMultiplier(value));
          setPlaybackTrackAmplitude(trackId, multiplier);
        }}
        onCommit={(value) => {
          const multiplier = sanitizeNumber(scaledZeroOneToMultiplier(value));
          setState(setTrackAmplitude(trackId, multiplier));
        }}
        getMeterValue={(index: number) => getTrackMeter(trackId, index)}
        color={trackColor}
      />
    </FaderWrapper>
  );
};

const formatBalanceValue = (value: number) => {
  if (value < 0) {
    return `PAN: ${(value * -100).toFixed(0)}L`;
  } else if (value > 0) {
    return `PAN: ${(value * 100).toFixed(0)}R`;
  } else {
    return 'PAN: C';
  }
};

const getInputTitle = (input: InputSpec) => {
  return `${input.channel + 1} | ${input.label}`;
};

const BalanceFader = ({ trackId }: { trackId: string }) => {
  const setState = useContextSelector(
    StudioContext,
    (context) => context.setState
  );
  const trackBalance = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.balance
  );
  const setPlaybackTrackBalance = useContextSelector(
    StudioContext,
    (context) => context.playbackController.updateTrackPan
  );
  const trackColor = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.color ?? '#ffffff'
  );
  return (
    <FaderWrapper className='highlight-fader-wrapper'>
      <StudioHorizontalFader
        defaultValue={0.5}
        anchorValue={0.5}
        value={(trackBalance + 1) / 2}
        formatValue={(x) => formatBalanceValue(x * 2 - 1)}
        onChange={(value) => setPlaybackTrackBalance(trackId, value * 2 - 1)}
        onCommit={(value) => setState(setTrackBalance(trackId, value * 2 - 1))}
        color={trackColor}
      />
    </FaderWrapper>
  );
};

const InstrumentPicker = ({
  instrument,
  setInstrument,
}: {
  instrument: InstrumentSpec;
  setInstrument: (instrument: InstrumentSpec) => void;
}) => {
  const instrumentTypeIcon = useMemo(() => {
    return getInstrumentTypeIcon(instrument);
  }, [instrument]);

  return (
    <ContextMenuTrigger
      placement='bottom-right'
      ButtonComponent={(props) => (
        <TrackHeaderButton
          {...props}
          icon={instrumentTypeIcon ?? <WaveformIcon />}
        />
      )}
      ContentsComponent={() => (
        <InstrumentPickerMenuContents setInstrument={setInstrument} />
      )}
    />
  );
};

const InputPicker = ({ trackId }: { trackId: string }) => {
  const trackInput = useContextSelector(
    StudioContext,
    (ctx) => getTracksById(ctx.state)[trackId]?.input
  );
  const discoverInputs = useContextSelector(
    AudioInputStreamContext,
    (ctx) => ctx.discoverInputs
  );
  const inputs = useContextSelector(
    AudioInputStreamContext,
    (ctx) => ctx.inputs
  );
  const isDiscoveringInputs = useContextSelector(
    AudioInputStreamContext,
    (ctx) => ctx.isDiscoveringInputs
  );
  const setState = useContextSelector(
    StudioContext,
    (context) => context.setState
  );

  const [inputSpecList, setInputSpecList] = useState<InputSpec[]>([]);
  useEffect(() => {
    if (inputs) {
      Promise.all(
        Object.entries(inputs).map(([id, input]) =>
          input
            .getNumberOfChannels()
            .then((channel) =>
              new Array(channel)
                .fill(0)
                .map((_, i) => ({ id, label: input.label, channel: i }))
            )
        )
      ).then((specs) => {
        setInputSpecList(
          uniqBy(
            specs.flat() as InputSpec[],
            (input: InputSpec) => `${input.label}-${input.channel}`
          ) as InputSpec[]
        );
      });
    }
  }, [inputs]);

  return (
    <ContextMenuTrigger
      placement='bottom-right'
      ButtonComponent={(props) => (
        <AudioInputDropdownButton
          {...props}
          icon={TriangleDownIcon}
          onClick={() => {
            if (!inputs && !isDiscoveringInputs) {
              discoverInputs();
            }
          }}
        >
          <TruncatedLabel>
            {trackInput ? getInputTitle(trackInput) : 'No Input'}
          </TruncatedLabel>
        </AudioInputDropdownButton>
      )}
      ContentsComponent={() =>
        isDiscoveringInputs || !inputs ? (
          <ContextMenuItem>
            <SpinnerSVG /> Finding inputs...
          </ContextMenuItem>
        ) : (
          <>
            {inputSpecList.map((input) => (
              <ContextMenuItem
                key={`${input.id}-${input.channel}`}
                icon={<MicrophoneIcon />}
                variant={
                  trackInput?.id === input.id &&
                  trackInput.channel === input.channel
                    ? ButtonVariant.Primary
                    : ButtonVariant.Standard
                }
                onClick={() => {
                  setState(
                    setTrackInput(trackId, {
                      id: input.id,
                      label: input.label,
                      channel: input.channel,
                    })
                  );
                }}
              >
                {getInputTitle(input)}
              </ContextMenuItem>
            ))}
          </>
        )
      }
    />
  );
};

const TrackDropzoneWrapper = styled.div`
  position: absolute;
  top: -2px;
  bottom: -2px;
  left: 0;
  right: 0;

  z-index: 2;
  display: none;
  grid-template-rows: 1fr 1fr;
  .dragging-track & {
    display: grid;
  }
`;

const BeforeDropper = styled.div`
  &:hover {
    border-top: 3px solid white;
  }
`;

const AfterDropper = styled.div`
  &:hover {
    border-bottom: 3px solid white;
  }
`;

export default function StudioTrackHeader({
  trackId,
  onDoubleClick,
  trackIndex,
}: {
  trackId: string;
  onDoubleClick: () => void;
  trackIndex: number;
}) {
  const { containerRef, containerName } = useContainer();
  const setState = useContextSelector(
    StudioContext,
    (context) => context.setState
  );
  const armed = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.arm
  );
  const toggleArmed = useCallback(() => {
    setState(setTrackArmed(trackId, !armed));
  }, [setState, trackId, armed]);
  const hasInput = useContextSelector(
    StudioContext,
    (context) => !!getTracksById(context.state)[trackId]?.input
  );
  const trackName = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.name
  );
  const [renaming, setRenaming] = useState(false);
  const [newName, setNewName] = useState(trackName ?? '');
  useEffect(() => {
    setNewName(trackName ?? '');
  }, [trackName]);
  const trackHeight = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.height
  );
  const selected = useContextSelector(StudioContext, (context) =>
    context.state.selection.trackIds.includes(trackId)
  );
  const focused = useContextSelector(
    StudioContext,
    (context) =>
      context.state.selection.focusedTrackId === trackId &&
      context.state.selection.focusedArea === 'tracks'
  );

  const setFocusedObject = useContextSelector(
    FocusedObjectContext,
    (ctx) => ctx.setFocusedObject
  );

  const handleClick = useCallback(
    (e: React.MouseEvent<HTMLDivElement>) => {
      setState(
        combineActions(
          focusTracks,
          selectTrackIds(trackId, trackId, trackId, e.shiftKey)
        )
      );
      setFocusedObject({ type: 'studio' });
    },
    [setState, trackId, setFocusedObject]
  );

  const showingTakeLanes = useContextSelector(StudioContext, (context) =>
    shouldShowTakeLanes(getTracksById(context.state)[trackId])
  );

  const numUnheardTakeLanes = useContextSelector(
    StudioContext,
    (context) =>
      getTracksById(context.state)[trackId].takeLanes.filter(
        (tl) => context.unheardTakeLanesController.unheardTakeLanes[tl.id]
      ).length
  );

  const effectivelyMuted = useContextSelector(
    StudioContext,
    (context) => getEffectivelyMutedTracks(context.state)[trackId]
  );

  const trackColor = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.color ?? '#ffffff'
  );
  const hasTakeLanes = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.takeLanes.length > 0
  );
  const fixBounds = useContextSelector(
    StudioContext,
    (context) => context.timelineController.fixBounds
  );
  const instrument = useContextSelector(
    StudioContext,
    (context) => getTracksById(context.state)[trackId]?.instrument
  );

  const setInstrument = useCallback(
    (
      nextInstrument:
        | InstrumentSpec
        | ((prev: InstrumentSpec) => InstrumentSpec)
    ) => {
      if (!instrument) return;
      const finalInstrument =
        typeof nextInstrument === 'function'
          ? nextInstrument(instrument)
          : nextInstrument;
      setState(
        updateTrack(trackId, (track) => ({
          ...track,
          name: isNewTrackOrCurrentInstrumentName(track.name, track.instrument)
            ? getInstrumentName(finalInstrument)
            : track.name,
          instrument: finalInstrument,
        }))
      );
    },
    [setState, trackId, instrument]
  );

  const [isDragging, setIsDragging] = useState(false);
  const mouseDownRef = useClickDrag(
    useCallback(() => {
      setIsDragging(true);
      document.body.classList.add('dragging-track');

      return {
        onMouseUp: ({ event }) => {
          setIsDragging(false);
          document.body.classList.remove('dragging-track');
          const targetTrackHeader = (event.target as HTMLElement)?.closest(
            '[data-track]'
          ) as HTMLElement | undefined;
          if (!targetTrackHeader) return;

          const targetTrackId = targetTrackHeader.dataset?.['track'];
          const targetDropPosition = targetTrackHeader.dataset?.['position'];
          if (!targetTrackId) return;

          setState(
            reorderTracks(
              trackId,
              targetTrackId,
              targetDropPosition === 'before'
            )
          );
        },
      };
    }, [setState, trackId]),
    true
  );

  return (
    <Wrapper
      ref={containerRef}
      onDoubleClick={onDoubleClick}
      onClick={handleClick}
      selected={selected}
    >
      <ColoredBorder style={{ backgroundColor: trackColor }}>
        <Tooltip
          openDelay={500}
          placement='right'
          label={
            trackHeight > minimumTrackHeight ? 'Collapse Track' : 'Expand Track'
          }
        >
          <TrackBorderItem
            className='group shrink-0'
            onClick={(e) => {
              e.stopPropagation();
              setState(
                setTrackHeight(
                  trackId,
                  trackHeight > minimumTrackHeight
                    ? minimumTrackHeight
                    : defaultStudioTrackHeight
                )
              );
            }}
          >
            <span className='not-hover-only absolute inset-0 flex items-center justify-center'>
              {trackIndex + 1}
            </span>
            <span className='hover-only absolute inset-0 flex items-center justify-center'>
              <CaretDownIcon
                className={clsx(
                  'h-4 w-4 transition-all duration-200 group-hover:text-foreground-primary',
                  {
                    'rotate-0': trackHeight <= minimumTrackHeight,
                    'rotate-180': trackHeight > minimumTrackHeight,
                  }
                )}
              />
            </span>
          </TrackBorderItem>
        </Tooltip>

        {hasTakeLanes && trackHeight >= minimumTrackHeight * 2 && (
          <Tooltip
            openDelay={500}
            placement='right'
            label={showingTakeLanes ? 'Hide Take Lanes' : 'Show Take Lanes'}
          >
            <TrackBorderItem
              className='group'
              style={
                numUnheardTakeLanes > 0
                  ? {
                      color: 'var(--color-foreground-primary)',
                    }
                  : undefined
              }
              onClick={(e) => {
                e.stopPropagation();
                setState(toggleTakeLanes(trackId));
                fixBounds();
              }}
            >
              {numUnheardTakeLanes > 0 ? (
                <>
                  <span className='relative bottom-1.5 h-3 w-3'>
                    +{numUnheardTakeLanes}
                  </span>
                  <CaretDownIcon
                    className={clsx(
                      'absolute -bottom-1 h-4 w-4 transition-all duration-200',
                      {
                        'rotate-0': !showingTakeLanes,
                        'rotate-180': showingTakeLanes,
                      }
                    )}
                  />
                </>
              ) : (
                <>
                  <span className='block group-hover:hidden'>
                    <TakeLanesIcon className='h-3 w-3' />
                  </span>
                  <span className='hidden group-hover:block'>
                    <CaretDownIcon
                      className={clsx(
                        'h-4 w-4 transition-all duration-200 group-hover:text-foreground-primary',
                        {
                          'rotate-0': !showingTakeLanes,
                          'rotate-180': showingTakeLanes,
                        }
                      )}
                    />
                  </span>
                  {/* {numUnheardTakeLanes > 0 ? (
                  <span className='relative bottom-1.5 h-3 w-3'>
                    +{numUnheardTakeLanes}
                  </span>
                ) : (
                  <TakeLanesIcon className='relative bottom-0 h-3 w-3 transition-all duration-200 group-hover:bottom-1' />
                )}
                <CaretDownIcon
                  className={clsx(
                    'absolute h-5 w-5 transition-all duration-200 group-hover:-bottom-0.5 group-hover:opacity-100',
                    {
                      'rotate-180': showingTakeLanes,
                      '-bottom-0.5 opacity-100': numUnheardTakeLanes > 0,
                      '-bottom-1 opacity-0': numUnheardTakeLanes === 0,
                    }
                  )}
                /> */}
                </>
              )}
            </TrackBorderItem>
          </Tooltip>
        )}
      </ColoredBorder>
      {renaming && (
        <Modal onClose={() => setRenaming(false)} title='Rename Track'>
          <p className='text-md mb-4 text-foreground-secondary'>
            Just a label for the track - does not affect instrument for new
            clips.
          </p>
          <TextareaV2
            autoFocus
            onFocus={(e) => {
              e.target.select();
            }}
            placeholder='Enter new track name'
            rows={1}
            resize={false}
            value={newName}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                e.preventDefault();
                setState(renameTrack(trackId, newName));
                setRenaming(false);
              }
            }}
            onChange={(e) => setNewName(e.target.value)}
          />
          <Button
            className='mt-4'
            variant={ButtonVariant.Primary}
            onClick={() => {
              setState(renameTrack(trackId, newName));
              setRenaming(false);
            }}
          >
            Rename
          </Button>
        </Modal>
      )}
      {!isDragging && !focused && (
        <TrackDropzoneWrapper>
          <BeforeDropper data-track={trackId} data-position='before' />
          <AfterDropper data-track={trackId} data-position='after' />
        </TrackDropzoneWrapper>
      )}
      <Outline
        style={focused ? { borderColor: trackColor } : {}}
        ref={mouseDownRef}
      >
        <Grid>
          <HeaderRow>
            <MuteButton trackId={trackId} />
            <ResponsiveChild containerName={containerName} showBelowHeight={60}>
              <SoloButton trackId={trackId} />
            </ResponsiveChild>
            <ResponsiveChild
              containerName={containerName}
              showBelowWidth={120}
              hideBelowHeight={60}
            >
              <SoloButton trackId={trackId} />
            </ResponsiveChild>
            {instrument && (
              <InstrumentPicker
                instrument={instrument}
                setInstrument={setInstrument}
              />
            )}
            <ResponsiveChild containerName={containerName} hideBelowWidth={120}>
              <div className='relative h-full w-full flex-1'>
                <TrackNameContainer>
                  <Tooltip
                    label='Double-click to rename'
                    openDelay={500}
                    placement='top'
                  >
                    <span
                      className='flex items-center justify-start gap-1'
                      onDoubleClick={(e) => {
                        e.stopPropagation();
                        setRenaming(true);
                      }}
                    >
                      {trackName || (
                        <span className='text-gray-500'>[Unnamed]</span>
                      )}
                    </span>
                  </Tooltip>
                </TrackNameContainer>
              </div>
              <HeaderSideButtons className='inherit-bg'>
                <TrackMenuButton trackId={trackId} setRenaming={setRenaming} />
              </HeaderSideButtons>
            </ResponsiveChild>
          </HeaderRow>
          <ResponsiveChild
            containerName={containerName}
            hideBelowHeight={60}
            hideBelowWidth={120}
          >
            <HeaderRow>
              <SoloButton trackId={trackId} />
              {effectivelyMuted ? (
                <TrackHeaderButton className='flex-1 !bg-transparent text-xs'>
                  Muted
                </TrackHeaderButton>
              ) : (
                <AmplitudeFader trackId={trackId} />
              )}
            </HeaderRow>
          </ResponsiveChild>
          <ResponsiveChild
            containerName={containerName}
            hideBelowHeight={88}
            hideBelowWidth={120}
          >
            <HeaderRow>
              <TrackHeaderButton
                disabled={!hasInput}
                onClick={toggleArmed}
                style={
                  armed
                    ? {
                        backgroundColor: 'var(--color-red-300)',
                      }
                    : {}
                }
                icon={
                  <div
                    className={clsx(
                      'icon h-3 w-3 rounded-full transition-all duration-300',
                      armed
                        ? 'scale-100 bg-accent-red-on-primary'
                        : 'scale-80 bg-foreground-inactive'
                    )}
                  />
                }
              />
              <div
                className='grid flex-1 gap-[4px]'
                style={{
                  gridTemplateColumns: '1.46fr 1fr',
                }}
              >
                <InputPicker trackId={trackId} />
                <BalanceFader trackId={trackId} />
              </div>
            </HeaderRow>
          </ResponsiveChild>
        </Grid>
      </Outline>
    </Wrapper>
  );
}
