import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../utils/hooks'
import Button from '../components/common/Button'
import Input from '../components/common/Input'
import Card from '../components/common/Card'
import { showToast } from '../utils/toast'
import { authAPI } from '../api/endpoints'

const Login = () => {
  const navigate = useNavigate()
  const { login } = useAuth()
  const [isLoading, setIsLoading] = useState(false)
  const [formData, setFormData] = useState({
    email: 'admin@example.com',
    password: 'admin123',
  })
  const [errors, setErrors] = useState({})

  const validateForm = () => {
    const newErrors = {}
    if (!formData.email) newErrors.email = 'Email is required'
    if (!formData.password) newErrors.password = 'Password is required'
    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async (e) => {
    e.preventDefault()

    if (!validateForm()) return

    setIsLoading(true)

    try {
      const response = await authAPI.login(formData.email, formData.password)
      const { accessToken, refreshToken, ...userData } = response.data.data

      login(userData, accessToken, refreshToken)
      showToast.success('Login successful!')
      navigate('/dashboard')
    } catch (error) {
      const message =
        error.response?.data?.message || 'Login failed. Please try again.'
      showToast.error(message)
    } finally {
      setIsLoading(false)
    }
  }

  const handleDemoLogin = async () => {
    setFormData({
      email: 'admin@numerology.com',
      password: 'admin123',
    })
    // Trigger login after setting the form data
    setTimeout(handleSubmit, 0)
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-4" style={{ background: 'linear-gradient(135deg, #0F4A5C 0%, #1A6878 40%, #2AA8B8 100%)' }}>
      {/* Background decorative circles */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute -top-32 -left-32 w-96 h-96 bg-[#F5A623]/10 rounded-full blur-3xl" />
        <div className="absolute -bottom-32 -right-32 w-96 h-96 bg-white/5 rounded-full blur-3xl" />
      </div>

      <div className="relative w-full max-w-md">
        {/* Logo area */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-[#F5A623] shadow-xl mb-4">
            <span className="text-3xl font-black text-white">N</span>
          </div>
          <h1 className="text-3xl font-bold text-white mb-1">
            Numerology Master Program - Dashboard
          </h1>
          {/*<p className="text-[#B2E0E8] text-sm">
            Admin Dashboard Management
          </p>*/}
        </div>

        <div className="bg-white dark:bg-slate-900 rounded-2xl shadow-2xl border border-[#B2E0E8]/30 p-8">
          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-5">
            <Input
              label="Email Address"
              type="email"
              placeholder="admin@example.com"
              value={formData.email}
              onChange={(e) =>
                setFormData({ ...formData, email: e.target.value })
              }
              error={errors.email}
              disabled={isLoading}
            />

            <Input
              label="Password"
              type="password"
              placeholder="••••••••"
              value={formData.password}
              onChange={(e) =>
                setFormData({ ...formData, password: e.target.value })
              }
              error={errors.password}
              disabled={isLoading}
            />

            <Button
              type="submit"
              className="w-full mt-2"
              isLoading={isLoading}
            >
              Sign In
            </Button>
          </form>

          {/* Demo Button */}
          <div className="mt-4">
            <div className="relative flex items-center my-4">
              <div className="flex-1 border-t border-gray-200 dark:border-slate-700" />
              <span className="px-3 text-xs text-gray-400 bg-white dark:bg-slate-900">or</span>
              <div className="flex-1 border-t border-gray-200 dark:border-slate-700" />
            </div>
            <Button
              onClick={handleDemoLogin}
              variant="outline"
              className="w-full"
              disabled={isLoading}
            >
              🔑 Use Demo Credentials
            </Button>
          </div>

          {/* Footer */}
          <p className="text-center text-xs text-gray-400 mt-5">
            Demo credentials are pre-filled. Click login to proceed.
          </p>
        </div>
      </div>
    </div>
  )
}

export default Login
