import { useState, useEffect } from 'react'
import { useNavigate } from '@tanstack/react-router'
import { trpc } from '@/trpc/client'
import { Button } from '@/components/ui/button'
import { setAuthToken, isAuthenticated } from '@/services/auth'

export function LoginRoute() {
  const [name, setName] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const navigate = useNavigate()

  useEffect(() => {
    const checkAuth = async () => {
      if (await isAuthenticated()) {
        navigate({ to: '/user-home' as any })
      }
    }
    checkAuth()
  }, [navigate])

  const loginMutation = trpc.admin.staffUser.login.useMutation({
    onSuccess: async (data: any) => {
      await setAuthToken(data.token);
      navigate({ to: '/user-home' as any })
    },
    onError: (error: any) => {
      setError(error.message || 'Login failed')
    }
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    loginMutation.mutate({ name, password })
  }

  return (
    <div className="max-w-md mx-auto mt-20">
      <div className="bg-white rounded-lg shadow-md p-6">
        <h1 className="text-2xl font-bold text-center mb-6">Login</h1>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
              Staff Name
            </label>
            <input
              id="name"
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            />
          </div>

          <div>
            <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
              Password
            </label>
            <input
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            />
          </div>

          {error && (
            <div className="text-red-600 text-sm text-center">
              {error}
            </div>
          )}

          <Button
            type="submit"
            className="w-full"
            disabled={loginMutation.isPending}
          >
            {loginMutation.isPending ? 'Logging in...' : 'Login'}
          </Button>
        </form>

        <div className="mt-4 text-center">
          <button
            onClick={() => navigate({ to: '/' })}
            className="text-blue-600 hover:text-blue-800 text-sm"
          >
            Back to Home
          </button>
        </div>
      </div>
    </div>
  )
}