import { useState, useEffect } from 'react'
import { useAuth } from '../auth/AuthProvider.tsx'
import { TTL_OPTIONS, getDeviceSession, updateDeviceTTL, getDeviceName } from '../auth/DeviceSession.ts'
import '../styles/auth.css'

interface SecuritySettingsProps {
  onClose: () => void
}

export function SecuritySettings({ onClose }: SecuritySettingsProps) {
  const auth = useAuth()
  const [currentTTL, setCurrentTTL] = useState<number>(86400)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const deviceName = getDeviceName()

  useEffect(() => {
    if (!auth.user) return
    getDeviceSession(auth.user.id).then(session => {
      if (session) setCurrentTTL(session.session_ttl_seconds)
      setLoading(false)
    })
  }, [auth.user])

  const handleTTLChange = async (ttl: number) => {
    if (!auth.user) return
    setSaving(true)
    setCurrentTTL(ttl)
    await updateDeviceTTL(auth.user.id, ttl)
    setSaving(false)
  }

  return (
    <div className="auth-backdrop" onClick={onClose}>
      <div className="auth-modal" onClick={e => e.stopPropagation()}>
        <h2>Security Settings</h2>
        <button className="auth-close" onClick={onClose} aria-label="Close">&times;</button>

        <div className="auth-field">
          <label>Current Device</label>
          <p style={{ margin: '4px 0', fontSize: '14px', color: 'var(--text-h)' }}>{deviceName}</p>
        </div>

        <div className="auth-field">
          <label>Re-enter password every</label>
          {loading ? (
            <p style={{ fontSize: '13px', color: 'var(--text)' }}>Loading...</p>
          ) : (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', marginTop: '8px' }}>
              {TTL_OPTIONS.map(opt => (
                <button
                  key={opt.value}
                  className={`auth-btn ${currentTTL === opt.value ? 'auth-btn-primary' : ''}`}
                  style={{
                    width: 'auto',
                    padding: '6px 14px',
                    fontSize: '13px',
                    marginTop: 0,
                    background: currentTTL === opt.value ? 'var(--accent)' : 'var(--bg-secondary)',
                    color: currentTTL === opt.value ? '#fff' : 'var(--text-h)',
                    border: `1px solid ${currentTTL === opt.value ? 'var(--accent)' : 'var(--border)'}`,
                  }}
                  onClick={() => handleTTLChange(opt.value)}
                  disabled={saving}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          )}
        </div>

        <p style={{ fontSize: '12px', color: 'var(--text)', marginTop: '16px', lineHeight: '1.5' }}>
          This setting controls how often you need to re-enter your password on this device.
          Other devices are not affected.
        </p>
      </div>
    </div>
  )
}
