import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { bootstrapCSRF, api, ApiError } from '../api/client'
import { z } from 'zod'
import { useQueryClient } from '@tanstack/react-query'

const userSchema = z.object({
  id: z.number(), username: z.string(), email: z.string(),
  avatarUrl: z.string(), isAdmin: z.boolean(), createdAt: z.string(), updatedAt: z.string(),
})

export default function LoginPage() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    setLoading(true)
    try {
      await bootstrapCSRF()
      await api.post('/api/v1/auth/login', userSchema, { username, password })
      queryClient.invalidateQueries({ queryKey: ['me'] })
      navigate('/')
    } catch (err) {
      setError(err instanceof ApiError && err.status === 401 ? 'Invalid username or password.' : 'Login failed. Please try again.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-[#F4F5F7] flex items-center justify-center p-4">
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <h1 className="text-2xl font-bold text-[#172B4D]">ForgeBucket</h1>
          <p className="text-sm text-[#5E6C84] mt-1">Sign in to your account</p>
        </div>

        <div className="bg-white border border-[#DFE1E6] rounded-lg p-6 shadow-sm">
          <form onSubmit={handleSubmit} className="flex flex-col gap-4">
            <div>
              <label className="block text-xs font-semibold text-[#172B4D] mb-1">Username</label>
              <input
                value={username} onChange={e => setUsername(e.target.value)}
                required autoFocus autoComplete="username"
                className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#4C9AFF] focus:ring-1 focus:ring-[#4C9AFF]"
              />
            </div>
            <div>
              <label className="block text-xs font-semibold text-[#172B4D] mb-1">Password</label>
              <input
                type="password" value={password} onChange={e => setPassword(e.target.value)}
                required autoComplete="current-password"
                className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#4C9AFF] focus:ring-1 focus:ring-[#4C9AFF]"
              />
            </div>
            {error && <p className="text-xs text-[#DE350B] bg-[#FFEBE6] rounded px-3 py-2">{error}</p>}
            <button
              type="submit" disabled={loading}
              className="w-full py-2.5 rounded bg-[#0052CC] text-white text-sm font-semibold hover:bg-[#0065FF] disabled:opacity-50 min-h-[44px]"
            >
              {loading ? 'Signing in…' : 'Sign in'}
            </button>
          </form>
        </div>

        <p className="text-center text-xs text-[#5E6C84] mt-4">
          No account?{' '}
          <Link to="/register" className="text-[#0052CC] hover:underline font-medium">Create one</Link>
        </p>
      </div>
    </div>
  )
}
