import { useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { apiFetch } from '../api/client'
import { useAuthStore } from '../store/auth'
import type { AuthResponse } from '../types'

export function Register() {
  const [username, setUsername] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState<string | null>(null)
  const { setAuth } = useAuthStore()
  const navigate = useNavigate()

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError(null)
    try {
      const res = await apiFetch<AuthResponse>('/auth/register', {
        method: 'POST',
        body: JSON.stringify({ username, email, password }),
      })
      setAuth(res.token, res.user)
      navigate('/')
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Registration failed')
    }
  }

  return (
    <div style={{ maxWidth: 340, margin: '30px auto' }}>
      <table width="100%" cellPadding={0} cellSpacing={0} style={{ border: '1px solid #7080b0' }}>
        <thead>
          <tr>
            <th
              colSpan={2}
              style={{
                background: '#003399',
                color: '#fff',
                padding: '5px 8px',
                textAlign: 'left',
                fontSize: 12,
              }}
            >
              Create Account
            </th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td colSpan={2} style={{ padding: 12 }}>
              <form onSubmit={handleSubmit}>
                {error && (
                  <p style={{ color: 'red', margin: '0 0 8px', fontSize: 11 }}>{error}</p>
                )}
                <table cellPadding={4}>
                  <tbody>
                    <tr>
                      <td>Username:</td>
                      <td>
                        <input
                          value={username}
                          onChange={(e) => setUsername(e.target.value)}
                          style={{ border: '1px solid #999', padding: 2 }}
                          autoFocus
                        />
                      </td>
                    </tr>
                    <tr>
                      <td>Email:</td>
                      <td>
                        <input
                          type="email"
                          value={email}
                          onChange={(e) => setEmail(e.target.value)}
                          style={{ border: '1px solid #999', padding: 2 }}
                        />
                      </td>
                    </tr>
                    <tr>
                      <td>Password:</td>
                      <td>
                        <input
                          type="password"
                          value={password}
                          onChange={(e) => setPassword(e.target.value)}
                          style={{ border: '1px solid #999', padding: 2 }}
                        />
                      </td>
                    </tr>
                    <tr>
                      <td colSpan={2} style={{ paddingTop: 8 }}>
                        <input
                          type="submit"
                          value="Register"
                          style={{
                            background: '#003399',
                            color: '#fff',
                            border: '1px solid #001166',
                            padding: '2px 12px',
                            cursor: 'pointer',
                            fontFamily: 'Verdana, sans-serif',
                            fontSize: 11,
                          }}
                        />
                        &nbsp;&nbsp;
                        <Link to="/login" style={{ color: '#003399', fontSize: 11 }}>
                          Already registered?
                        </Link>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </form>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  )
}
