import { Tooltip } from '@cherrystudio/ui'
import { usePreference } from '@data/hooks/usePreference'
import { ipcApi } from '@renderer/ipc'
import { useIpcOn } from '@renderer/ipc/useIpcOn'
import { isLinux, isWin } from '@renderer/utils/platform'
import { Minus, Square, X } from 'lucide-react'
import type { SVGProps } from 'react'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'

import { ControlButton, WindowControlsContainer } from './WindowControls.styled'

interface WindowRestoreIconProps extends SVGProps<SVGSVGElement> {
  size?: string | number
}

const DEFAULT_DELAY = 1000

export const WindowRestoreIcon = ({ size = '1.1em', ...props }: WindowRestoreIconProps) => (
  <svg
    width={size}
    height={size}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
    className="lucide lucide-square-icon lucide-square"
    version="1.1"
    id="svg4"
    xmlns="http://www.w3.org/2000/svg"
    {...props}>
    <defs id="defs1" />
    <rect
      width="14.165795"
      height="14.165795"
      x="2.7646871"
      y="7.0695167"
      rx="1.2377932"
      id="rect2"
      style={{ strokeWidth: '1.57397' }}
    />
    <path
      d="m 8.8907777,2.8269172 c -0.5045461,0 -0.9490675,0.2424833 -1.2285866,0.6160739 H 18.993677 c 0.866756,0 1.563332,0.696576 1.563332,1.5633319 v 11.331486 c 0.37359,-0.279519 0.616074,-0.72404 0.616074,-1.228587 V 4.3635407 c 0,-0.8505156 -0.686108,-1.5366235 -1.536624,-1.5366235 z"
      style={{ strokeWidth: '0.911647', strokeDasharray: 'none' }}
      id="path5"
    />
  </svg>
)

/**
 * Whether the renderer draws the OS window controls. Windows is always frameless (custom
 * controls); Linux is frameless unless the user opted into the system title bar, in which
 * case the OS draws them. Exported so frameless surfaces can reserve corner space to match.
 */
export function useHasWindowControls(): boolean {
  const [useSystemTitleBar] = usePreference('app.use_system_title_bar')
  return isWin || (isLinux && !useSystemTitleBar)
}

const WindowControls: React.FC = () => {
  const [isMaximized, setIsMaximized] = useState(false)
  const { t } = useTranslation()
  const hasWindowControls = useHasWindowControls()

  useEffect(() => {
    // Check initial maximized state
    void ipcApi.request('window.is_maximized').then(setIsMaximized)
  }, [])

  // Listen for maximized state changes (auto-unsubscribes on unmount)
  useIpcOn('window.maximized_changed', setIsMaximized)

  if (!hasWindowControls) {
    return null
  }

  const handleMinimize = () => {
    void ipcApi.request('window.minimize')
  }

  const handleMaximize = () => {
    if (isMaximized) {
      void ipcApi.request('window.unmaximize')
    } else {
      void ipcApi.request('window.maximize')
    }
  }

  const handleClose = () => {
    void ipcApi.request('window.close')
  }

  const tooltipTriggerWrap = { placeholder: 'relative z-10 flex h-full min-h-0' } as const

  return (
    <WindowControlsContainer>
      <Tooltip
        placement="bottom"
        content={t('navbar.window.minimize')}
        delay={DEFAULT_DELAY}
        classNames={tooltipTriggerWrap}>
        <ControlButton onClick={handleMinimize} aria-label={t('navbar.window.minimize')}>
          <Minus size={14} />
        </ControlButton>
      </Tooltip>
      <Tooltip
        placement="bottom"
        content={isMaximized ? t('navbar.window.restore') : t('navbar.window.maximize')}
        delay={DEFAULT_DELAY}
        classNames={tooltipTriggerWrap}>
        <ControlButton
          onClick={handleMaximize}
          aria-label={isMaximized ? t('navbar.window.restore') : t('navbar.window.maximize')}>
          {isMaximized ? <WindowRestoreIcon size={14} /> : <Square size={14} />}
        </ControlButton>
      </Tooltip>
      <Tooltip
        placement="bottom"
        content={t('navbar.window.close')}
        delay={DEFAULT_DELAY}
        classNames={tooltipTriggerWrap}>
        <ControlButton $isClose onClick={handleClose} aria-label={t('navbar.window.close')}>
          <X size={17} />
        </ControlButton>
      </Tooltip>
    </WindowControlsContainer>
  )
}

export default WindowControls
