import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useAuthStore } from '@/store/authStore'
import { apiClientV2 } from '@/services/apiV2'
import { Lock, User, LayoutDashboard, AlertCircle, Loader2, Sparkles, Zap, Shield } from 'lucide-react'

export default function LoginPage() {
  const { t } = useTranslation()
  const navigate = useNavigate()
  const setUser = useAuthStore((state) => state.setUser)
  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 {
      // Use V2 API with external authentication
      const response = await apiClientV2.login({ username, password })

      // Store user info from V2 API response
      setUser({
        id: response.user.id,
        username: response.user.email,
        email: response.user.email,
        displayName: response.user.display_name
      })

      navigate('/upload')
    } catch (err: any) {
      const errorDetail = err.response?.data?.detail
      if (Array.isArray(errorDetail)) {
        setError(errorDetail.map((e: any) => e.msg || e.message || String(e)).join(', '))
      } else if (typeof errorDetail === 'string') {
        setError(errorDetail)
      } else {
        setError(t('auth.loginError'))
      }
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen relative overflow-hidden">
      {/* Full-screen Animated Background */}
      <div className="absolute inset-0 bg-gradient-to-br from-blue-600 via-purple-600 to-pink-500">
        {/* Animated overlay */}
        <div className="absolute inset-0 bg-gradient-to-tr from-blue-500/50 via-transparent to-purple-500/50 animate-pulse"></div>

        {/* Floating orbs */}
        <div className="absolute top-20 left-20 w-72 h-72 bg-white/10 rounded-full blur-3xl animate-float"></div>
        <div className="absolute bottom-20 right-20 w-96 h-96 bg-blue-400/20 rounded-full blur-3xl animate-float" style={{ animationDelay: '1s' }}></div>
        <div className="absolute top-1/2 left-1/2 w-64 h-64 bg-purple-400/10 rounded-full blur-3xl animate-float" style={{ animationDelay: '0.5s' }}></div>

        {/* Grid pattern */}
        <div className="absolute inset-0 opacity-10">
          <div className="absolute inset-0" style={{ backgroundImage: 'linear-gradient(rgba(255,255,255,.05) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.05) 1px, transparent 1px)', backgroundSize: '50px 50px' }}></div>
        </div>
      </div>

      {/* Content Container */}
      <div className="relative z-10 min-h-screen flex items-center justify-center p-4">
        <div className="w-full max-w-6xl flex flex-col lg:flex-row gap-8 items-center">

          {/* Left Side - Branding */}
          <div className="flex-1 text-white text-center lg:text-left animate-fade-in">
            {/* Logo */}
            <div className="flex items-center justify-center lg:justify-start gap-4 mb-8">
              <div className="w-16 h-16 bg-white/20 backdrop-blur-md rounded-2xl flex items-center justify-center shadow-2xl animate-float">
                <LayoutDashboard className="w-10 h-10" />
              </div>
              <div>
                <h1 className="text-4xl font-bold tracking-tight">Tool_OCR</h1>
                <p className="text-white/80 text-sm mt-1">智能 OCR 處理平台</p>
              </div>
            </div>

            {/* Features - Only show on larger screens */}
            <div className="hidden lg:block space-y-6 mb-12 animate-slide-in-left" style={{ animationDelay: '0.1s' }}>
              <h2 className="text-3xl font-bold mb-8">為什麼選擇我們？</h2>

              <div className="space-y-4">
                <div className="flex items-start gap-4 group hover:translate-x-2 transition-transform">
                  <div className="w-12 h-12 bg-gradient-to-br from-white/20 to-white/10 backdrop-blur-sm rounded-xl flex items-center justify-center flex-shrink-0 group-hover:scale-110 transition-transform">
                    <Sparkles className="w-6 h-6" />
                  </div>
                  <div>
                    <h3 className="font-bold text-xl mb-1">高精度識別</h3>
                    <p className="text-white/70">AI 驅動的 OCR 引擎，識別準確率高達 99%</p>
                  </div>
                </div>

                <div className="flex items-start gap-4 group hover:translate-x-2 transition-transform">
                  <div className="w-12 h-12 bg-gradient-to-br from-white/20 to-white/10 backdrop-blur-sm rounded-xl flex items-center justify-center flex-shrink-0 group-hover:scale-110 transition-transform">
                    <Zap className="w-6 h-6" />
                  </div>
                  <div>
                    <h3 className="font-bold text-xl mb-1">閃電般快速</h3>
                    <p className="text-white/70">批量處理數百份文件，大幅提升工作效率</p>
                  </div>
                </div>

                <div className="flex items-start gap-4 group hover:translate-x-2 transition-transform">
                  <div className="w-12 h-12 bg-gradient-to-br from-white/20 to-white/10 backdrop-blur-sm rounded-xl flex items-center justify-center flex-shrink-0 group-hover:scale-110 transition-transform">
                    <Shield className="w-6 h-6" />
                  </div>
                  <div>
                    <h3 className="font-bold text-xl mb-1">安全可靠</h3>
                    <p className="text-white/70">企業級加密，確保您的資料絕對安全</p>
                  </div>
                </div>
              </div>
            </div>

            {/* Stats */}
            <div className="hidden lg:grid grid-cols-3 gap-4 animate-slide-in-left" style={{ animationDelay: '0.2s' }}>
              <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 hover:bg-white/20 hover:scale-105 transition-all cursor-pointer border border-white/20">
                <div className="text-4xl font-bold mb-2">99%</div>
                <div className="text-white/70 text-sm">準確率</div>
              </div>
              <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 hover:bg-white/20 hover:scale-105 transition-all cursor-pointer border border-white/20">
                <div className="text-4xl font-bold mb-2">10+</div>
                <div className="text-white/70 text-sm">支援格式</div>
              </div>
              <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 hover:bg-white/20 hover:scale-105 transition-all cursor-pointer border border-white/20">
                <div className="text-4xl font-bold mb-2">24/7</div>
                <div className="text-white/70 text-sm">全天候</div>
              </div>
            </div>
          </div>

          {/* Right Side - Login Form */}
          <div className="w-full lg:w-auto lg:min-w-[480px] animate-scale-in">
            <div className="bg-white/95 backdrop-blur-xl rounded-3xl p-8 md:p-10 shadow-2xl border border-white/20">
              <div className="mb-8">
                <h2 className="text-3xl font-bold text-gray-900 mb-2">歡迎回來</h2>
                <p className="text-gray-600">登入以開始使用 OCR 服務</p>
              </div>

              <form onSubmit={handleSubmit} className="space-y-6">
                {/* Username */}
                <div className="space-y-2 animate-slide-in-right" style={{ animationDelay: '0.1s' }}>
                  <label htmlFor="username" className="block text-sm font-semibold text-gray-700">
                    使用者名稱
                  </label>
                  <div className="relative group">
                    <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                      <User className="h-5 w-5 text-gray-400 group-focus-within:text-blue-600 transition-colors" />
                    </div>
                    <input
                      id="username"
                      type="text"
                      value={username}
                      onChange={(e) => setUsername(e.target.value)}
                      className="w-full pl-11 pr-4 py-3 bg-gray-50 border-2 border-gray-200 rounded-xl
                        text-gray-900 placeholder-gray-400
                        focus:outline-none focus:ring-4 focus:ring-blue-500/20 focus:border-blue-500
                        hover:border-gray-300
                        transition-all duration-200"
                      placeholder="輸入您的用戶名"
                      required
                    />
                  </div>
                </div>

                {/* Password */}
                <div className="space-y-2 animate-slide-in-right" style={{ animationDelay: '0.2s' }}>
                  <label htmlFor="password" className="block text-sm font-semibold text-gray-700">
                    密碼
                  </label>
                  <div className="relative group">
                    <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                      <Lock className="h-5 w-5 text-gray-400 group-focus-within:text-blue-600 transition-colors" />
                    </div>
                    <input
                      id="password"
                      type="password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="w-full pl-11 pr-4 py-3 bg-gray-50 border-2 border-gray-200 rounded-xl
                        text-gray-900 placeholder-gray-400
                        focus:outline-none focus:ring-4 focus:ring-blue-500/20 focus:border-blue-500
                        hover:border-gray-300
                        transition-all duration-200"
                      placeholder="輸入您的密碼"
                      required
                    />
                  </div>
                </div>

                {/* Error */}
                {error && (
                  <div className="flex items-start gap-3 p-4 bg-red-50 border-2 border-red-200 rounded-xl animate-scale-in">
                    <AlertCircle className="h-5 w-5 text-red-600 flex-shrink-0 mt-0.5" />
                    <p className="text-sm text-red-600 font-medium">{error}</p>
                  </div>
                )}

                {/* Submit Button */}
                <button
                  type="submit"
                  disabled={loading}
                  className="w-full py-4 px-6 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-xl font-bold text-lg
                    shadow-lg shadow-blue-500/50 hover:shadow-xl hover:shadow-blue-500/60 hover:scale-[1.02]
                    focus:outline-none focus:ring-4 focus:ring-blue-500/50
                    disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100
                    transition-all duration-200
                    relative overflow-hidden group
                    animate-slide-in-right"
                  style={{ animationDelay: '0.3s' }}
                >
                  <div className="absolute inset-0 bg-gradient-to-r from-blue-700 to-purple-700 opacity-0 group-hover:opacity-100 transition-opacity"></div>
                  <span className="relative flex items-center justify-center gap-2">
                    {loading ? (
                      <>
                        <Loader2 className="w-6 h-6 animate-spin" />
                        <span>登入中...</span>
                      </>
                    ) : (
                      <span>立即登入</span>
                    )}
                  </span>
                </button>
              </form>

              {/* Footer */}
              <div className="mt-8 text-center animate-fade-in" style={{ animationDelay: '0.4s' }}>
                <p className="text-xs text-gray-500">
                  Powered by <span className="font-bold text-gray-700">AI Technology</span>
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
