const { h, preactHooks } = globalThis.ami
const { useState } = preactHooks

function AdminLogin() {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  const handleLogin = async (e) => {
    e.preventDefault()
    setError('')
    setLoading(true)

    try {
      const response = await fetch('/api/admin/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
      })

      const data = await response.json()

      if (response.ok) {
        // Store token in localStorage
        localStorage.setItem('adminToken', data.token)
        localStorage.setItem('adminUser', username)
        // Redirect to dashboard
        window.location.href = '/admin/dashboard'
      } else {
        setError(data.message || 'Invalid credentials')
      }
    } catch (err) {
      setError('Login failed. Please try again.')
    } finally {
      setLoading(false)
    }
  }

  return h('div', { className: 'min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 py-12 px-4 sm:px-6 lg:px-8' },
    h('div', { className: 'max-w-md w-full space-y-8 bg-white p-10 rounded-2xl shadow-2xl' },
      h('div', {},
        h('h2', { className: 'text-center text-3xl font-extrabold text-gray-900' }, 'Admin Login'),
        h('p', { className: 'mt-2 text-center text-sm text-gray-600' }, 'Shiv Shakti Hardware - Product Management')
      ),
      h('form', { className: 'mt-8 space-y-6', onSubmit: handleLogin },
        error && h('div', { className: 'bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-lg text-sm' }, error),
        h('div', { className: 'space-y-4' },
          h('div', {},
            h('label', { htmlFor: 'username', className: 'block text-sm font-medium text-gray-700 mb-1' }, 'Username'),
            h('input', {
              id: 'username',
              name: 'username',
              type: 'text',
              required: true,
              className: 'appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm',
              placeholder: 'Enter username',
              value: username,
              onInput: (e) => setUsername(e.target.value)
            })
          ),
          h('div', {},
            h('label', { htmlFor: 'password', className: 'block text-sm font-medium text-gray-700 mb-1' }, 'Password'),
            h('input', {
              id: 'password',
              name: 'password',
              type: 'password',
              required: true,
              className: 'appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm',
              placeholder: 'Enter password',
              value: password,
              onInput: (e) => setPassword(e.target.value)
            })
          )
        ),
        h('div', {},
          h('button', {
            type: 'submit',
            disabled: loading,
            className: `group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-lg text-white ${loading ? 'bg-indigo-400 cursor-not-allowed' : 'bg-indigo-600 hover:bg-indigo-700'} focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors`
          }, loading ? 'Logging in...' : 'Sign in')
        )
      ),
      h('div', { className: 'text-center text-xs text-gray-500 mt-4' },
        ''
      )
    )
  )
}

globalThis.ami.register(AdminLogin, 'admin-login')
