import React, { useEffect, useState } from 'react'

type UpdateStatus = 'idle' | 'checking' | 'update-available' | 'update-downloaded' | 'latest' | 'error'

interface SettingsModalProps {
  isOpen: boolean
  onClose: () => void
  currentUserId: number | null
  currentUserName: string
  onLogout: () => void
  updateStatus?: UpdateStatus
  updateError?: string
  updateDownloadProgress?: number | null
  onCheckForUpdates?: () => void
}

export const SettingsModal: React.FC<SettingsModalProps> = ({
  isOpen,
  onClose,
  currentUserId,
  currentUserName,
  onLogout,
  updateStatus = 'idle',
  updateError = '',
  updateDownloadProgress = null,
  onCheckForUpdates
}) => {
  const [appVersion, setAppVersion] = useState<string | null>(null)

  useEffect(() => {
    if (!isOpen) return
    const ipc = typeof window !== 'undefined' && window.electron?.ipcRenderer
    if (!ipc) {
      setAppVersion(null)
      return
    }
    let cancelled = false
    ipc
      .invoke('get-app-version')
      .then((v: unknown) => {
        if (!cancelled && typeof v === 'string') setAppVersion(v)
      })
      .catch(() => {
        if (!cancelled) setAppVersion(null)
      })
    return () => {
      cancelled = true
    }
  }, [isOpen])

  if (!isOpen) return null

  const hasUpdateAPI = typeof window !== 'undefined' && window.electron?.ipcRenderer

  const updateStatusText =
    updateStatus === 'checking'
      ? '检查中…'
      : updateStatus === 'update-available'
        ? '发现新版本，正在下载…'
        : updateStatus === 'update-downloaded'
          ? '新版本已下载，请重启以更新'
          : updateStatus === 'latest'
            ? '当前已是最新版本'
            : updateStatus === 'error'
              ? updateError || '检查失败'
              : ''

  return (
    <div 
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0,0,0,0.5)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 1000
      }} 
      onClick={onClose}
    >
      <div 
        style={{
          backgroundColor: '#fff',
          padding: '30px',
          borderRadius: '8px',
          minWidth: '400px',
          maxWidth: '500px',
          boxShadow: '0 4px 12px rgba(0,0,0,0.15)'
        }} 
        onClick={(e) => e.stopPropagation()}
      >
        <h2 style={{ marginTop: 0, marginBottom: '20px', fontSize: '20px', fontWeight: '500' }}>设置</h2>
        <div style={{ marginTop: '20px' }}>
          <div style={{ marginBottom: '15px', paddingBottom: '15px', borderBottom: '1px solid #f0f0f0' }}>
            <div style={{ color: '#999', fontSize: '12px', marginBottom: '5px' }}>用户ID</div>
            <div style={{ color: '#333', fontSize: '14px' }}>{currentUserId || '未知'}</div>
          </div>
          <div style={{ marginBottom: '20px', paddingBottom: '15px', borderBottom: '1px solid #f0f0f0' }}>
            <div style={{ color: '#999', fontSize: '12px', marginBottom: '5px' }}>用户名</div>
            <div style={{ color: '#333', fontSize: '14px' }}>{currentUserName || '未知'}</div>
          </div>
          <div style={{ marginBottom: '20px', paddingBottom: '15px', borderBottom: '1px solid #f0f0f0' }}>
            <div style={{ color: '#999', fontSize: '12px', marginBottom: '5px' }}>当前版本</div>
            <div style={{ color: '#333', fontSize: '14px' }}>{appVersion ?? '—'}</div>
          </div>

          {hasUpdateAPI && onCheckForUpdates && (
            <div style={{ marginBottom: '20px', paddingBottom: '15px', borderBottom: '1px solid #f0f0f0' }}>
              <div style={{ color: '#999', fontSize: '12px', marginBottom: '8px' }}>检查更新</div>
              <button
                onClick={onCheckForUpdates}
                disabled={updateStatus === 'checking' || updateStatus === 'update-available' || updateStatus === 'update-downloaded'}
                style={{
                  width: '100%',
                  padding: '10px 20px',
                  backgroundColor: updateStatus === 'checking' || updateStatus === 'update-available' ? '#ccc' : '#1aad19',
                  color: '#fff',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: updateStatus === 'checking' || updateStatus === 'update-available' || updateStatus === 'update-downloaded' ? 'not-allowed' : 'pointer',
                  fontSize: '14px',
                  fontWeight: '500'
                }}
              >
                {updateStatus === 'checking' || updateStatus === 'update-available' ? '检查中…' : '检查更新'}
              </button>
              {updateStatus === 'update-available' && updateDownloadProgress != null && (
                <div style={{ marginTop: '10px' }}>
                  <div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>
                    正在下载… {Math.round(updateDownloadProgress)}%
                  </div>
                  <div style={{ height: 6, backgroundColor: '#eee', borderRadius: 3, overflow: 'hidden' }}>
                    <div
                      style={{
                        height: '100%',
                        width: `${Math.min(100, Math.round(updateDownloadProgress))}%`,
                        backgroundColor: '#1aad19',
                        transition: 'width 0.2s ease'
                      }}
                    />
                  </div>
                </div>
              )}
              {updateStatusText && (
                <div style={{ marginTop: '8px', fontSize: '13px', color: updateStatus === 'error' ? '#ff3b30' : '#666' }}>
                  {updateStatusText}
                </div>
              )}
            </div>
          )}

          <button 
            onClick={() => {
              onLogout()
              onClose()
            }}
            style={{
              width: '100%',
              padding: '12px 20px',
              backgroundColor: '#ff3b30',
              color: '#fff',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px',
              fontWeight: '500',
              transition: 'background-color 0.2s'
            }}
            onMouseOver={(e) => e.currentTarget.style.backgroundColor = '#ff2d20'}
            onMouseOut={(e) => e.currentTarget.style.backgroundColor = '#ff3b30'}
          >
            退出登录
          </button>
        </div>
      </div>
    </div>
  )
}
