import { useEffect, useState } from 'react'
import { useStore } from '../store'
import type { AppInfo } from '../types'

function MinIcon(): React.JSX.Element {
  return (
    <svg viewBox="0 0 12 12">
      <rect x="0" y="5.5" width="12" height="1.4" rx="0.7" fill="currentColor" />
    </svg>
  )
}

function MaxIcon(): React.JSX.Element {
  return (
    <svg viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.3">
      <rect x="1.5" y="1.5" width="9" height="9" rx="1.5" />
    </svg>
  )
}

function RestoreIcon(): React.JSX.Element {
  return (
    <svg viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.3">
      <rect x="1.5" y="3.5" width="7" height="7" rx="1.2" />
      <path d="M4 1.5h5a1.5 1.5 0 0 1 1.5 1.5v5" />
    </svg>
  )
}

function CloseIcon(): React.JSX.Element {
  return (
    <svg viewBox="0 0 12 12" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
      <path d="M2 2l8 8M10 2l-8 8" />
    </svg>
  )
}

export default function TitleBar(): React.JSX.Element {
  const [maximized, setMaximized] = useState(false)
  const [info, setInfo] = useState<AppInfo | null>(null)
  const filePath = useStore((s) => s.filePath)
  const dirty = useStore((s) => s.dirty)

  useEffect(() => {
    const off = window.api.win.onMaximized((v) => setMaximized(v))
    return off
  }, [])

  useEffect(() => {
    void window.api.app.info().then(setInfo)
  }, [])

  return (
    <div className="titlebar">
      <svg className="tb-logo" viewBox="0 0 24 24" fill="none">
        <path
          d="M4 3h16a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"
          stroke="#8fd19a"
          strokeWidth="1.6"
        />
        <path d="M7 16l3-4 2.5 3 2-2.5 2.5 3.5" stroke="#8fd19a" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
        <circle cx="17" cy="8.5" r="1.6" fill="#8fd19a" />
      </svg>
      <span className="tb-title">智慧农业大数据可视化控制中心</span>
      <span className="tb-ver">系统版本号 v{info?.appVersion ?? '…'}</span>
      <span className="tb-file">
        {filePath ? filePath : '未命名工程'}
        {dirty ? ' ●' : ''}
      </span>
      <div className="tb-controls">
        <button className="tb-btn" title="最小化" onClick={() => window.api.win.minimize()}>
          <MinIcon />
        </button>
        <button className="tb-btn" title="最大化 / 还原" onClick={() => window.api.win.toggleMaximize()}>
          {maximized ? <RestoreIcon /> : <MaxIcon />}
        </button>
        <button className="tb-btn close" title="关闭" onClick={() => window.api.win.close()}>
          <CloseIcon />
        </button>
      </div>
    </div>
  )
}
