import player from '@/web/states/player'
import Icon from './Icon'
import { IpcChannels } from '@/shared/IpcChannels'
import useIpcRenderer from '@/web/hooks/useIpcRenderer'
import { useState, useMemo } from 'react'
import { useSnapshot } from 'valtio'
import { cx } from '@emotion/css'

const Controls = () => {
  const [isMaximized, setIsMaximized] = useState(false)

  useIpcRenderer(IpcChannels.IsMaximized, (e, value) => {
    setIsMaximized(value)
  })

  const minimize = () => {
    window.ipcRenderer?.send(IpcChannels.Minimize)
  }

  const maxRestore = () => {
    window.ipcRenderer?.send(IpcChannels.MaximizeOrUnmaximize)
  }

  const close = () => {
    window.ipcRenderer?.send(IpcChannels.Close)
  }

  return (
    <div className='app-region-no-drag flex h-full'>
      <button
        onClick={minimize}
        className='flex w-[2.875rem] items-center justify-center hover:bg-[#e9e9e9]'
      >
        <Icon className='h-3 w-3' name='windows-minimize' />
      </button>
      <button
        onClick={maxRestore}
        className='flex w-[2.875rem] items-center justify-center hover:bg-[#e9e9e9]'
      >
        <Icon
          className='h-3 w-3'
          name={isMaximized ? 'windows-un-maximize' : 'windows-maximize'}
        />
      </button>
      <button
        onClick={close}
        className='flex w-[2.875rem] items-center justify-center hover:bg-[#c42b1c] hover:text-white'
      >
        <Icon className='h-3 w-3' name='windows-close' />
      </button>
    </div>
  )
}

const Title = ({ className }: { className?: string }) => {
  const playerSnapshot = useSnapshot(player)
  const track = useMemo(() => playerSnapshot.track, [playerSnapshot.track])

  return (
    <div className={cx('text-sm text-gray-500', className)}>
      {track?.name && (
        <>
          <span>{track.name}</span>
          <span className='mx-2'>-</span>
        </>
      )}
      <span>YesPlayMusic</span>
    </div>
  )
}

const Win = () => {
  return (
    <div className='flex h-8 w-screen items-center justify-between bg-gray-50'>
      <Title className='ml-3' />
      <Controls />
    </div>
  )
}

const Linux = () => {
  return (
    <div className='flex h-8 w-screen items-center justify-between bg-gray-50'>
      <div></div>
      <Title className='text-center' />
      <Controls />
    </div>
  )
}

const TitleBar = () => {
  return (
    <div className='app-region-drag fixed z-30'>
      {window.env?.isWindows ? <Win /> : <Linux />}
    </div>
  )
}

export default TitleBar
