import { useState } from 'react'
import { Navigate } from 'react-router-dom'
import { Mail, Lock, Eye, EyeOff, Zap } from 'lucide-react'
import { loginWithEmail, loginWithGoogle } from '@/firebase/auth'
import useAuthStore from '@/context/authStore'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import toast from 'react-hot-toast'

// Google G icon SVG
function GoogleIcon() {
 return (
 <svg width="18" height="18" viewBox="0 0 48 48" fill="none">
 <path d="M44.5 20H24v8.5h11.7C34.3 33.5 29.7 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3 0 5.7 1.1 7.8 2.9l6-6C34.5 6.5 29.5 4 24 4 12.95 4 4 12.95 4 24s8.95 20 20 20c11 0 19.7-8 19.7-20 0-1.3-.1-2.7-.2-4z" fill="#FFC107"/>
 <path d="M6.3 14.7l7 5.1C15.1 16 19.2 13 24 13c3 0 5.7 1.1 7.8 2.9l6-6C34.5 6.5 29.5 4 24 4 16.3 4 9.7 8.4 6.3 14.7z" fill="#FF3D00"/>
 <path d="M24 44c5.4 0 10.3-1.9 14.1-5.1l-6.5-5.5C29.7 35 27 36 24 36c-5.7 0-10.3-3.5-11.7-8.5l-7 5.4C8.7 39.5 15.8 44 24 44z" fill="#4CAF50"/>
 <path d="M44.5 20H24v8.5h11.7c-.8 2.5-2.4 4.6-4.5 6l6.5 5.5C41.6 36.7 44.5 30.8 44.5 24c0-1.3-.1-2.7-.2-4z" fill="#1976D2"/>
 </svg>
 )
}

export default function LoginPage() {
 const { user, customUid } = useAuthStore()
 const [form, setForm] = useState({ email: '', password: '' })
 const [showPass, setShowPass] = useState(false)
 const [loading, setLoading] = useState(false)
 const [googleLoading, setGoogleLoading] = useState(false)
 const [error, setError] = useState('')

 if (user || customUid) return <Navigate to="/" replace />

 const handleSubmit = async (e) => {
  e.preventDefault()
  setError('')
  setLoading(true)
  try {
    const { generateAuthKey } = await import('@/services/superAdminService')
    const { db, getDoc, doc } = await import('@/firebase/firestore')
    
    // Calculate secure hash of credentials
    const authKey = await generateAuthKey(form.email, form.password)
    
    // Look up Auth Key in database
    const authRef = doc(db, 'auth_keys', authKey)
    const authSnap = await getDoc(authRef)

    if (authSnap.exists()) {
      const authData = authSnap.data()
      await useAuthStore.getState().customLogin(authData.uid, authData.companyId, authData.role)
      toast.success('Welcome back!')
    } else {
      setError('Login failed. Please check your credentials.')
    }
  } catch (err) {
    console.error('Login error:', err)
    setError('Login failed. Please check your credentials. Error: ' + err.message)
  } finally {
    setLoading(false)
  }
 }

  const handleGoogle = async () => {
   setError('')
   setGoogleLoading(true)
   try {
     const result = await loginWithGoogle()
     const userEmail = result.user?.email
     
     // Allowing any Google user to manage their company
     toast.success(userEmail === 'ayushkssk@gmail.com' ? 'Welcome Super Admin!' : 'Welcome to IT4B BillBook!')
   } catch (err) {
     if (err.code !== 'auth/popup-closed-by-user') {
       setError('Google sign-in failed. Please try again.')
     }
   } finally {
     setGoogleLoading(false)
   }
  }

 return (
 <div className="min-h-screen bg-gradient-dark flex items-center justify-center p-4">
 {/* Background decoration */}
 <div className="absolute inset-0 overflow-hidden pointer-events-none">
 <div className="absolute -top-40 -right-40 w-96 h-96 bg-primary-600/20 rounded-full blur-3xl" />
 <div className="absolute -bottom-40 -left-40 w-96 h-96 bg-accent-600/20 rounded-full blur-3xl" />
 </div>

 <div className="relative w-full max-w-sm animate-slide-up">
 {/* Card */}
 <div className="rounded-2xl border border-surface-700 bg-surface-900/80 backdrop-blur-xl shadow-card-dark p-8">
 {/* Logo */}
 <div className="flex flex-col items-center mb-8">
 <div className="w-14 h-14 rounded-2xl bg-gradient-brand flex items-center justify-center shadow-glow mb-4">
 <Zap size={28} className="text-white" />
 </div>
 <h1 className="text-2xl font-bold text-surface-50">IT4B BillBook</h1>
 <p className="text-sm text-surface-400 mt-1">Innovation Technologies for Business</p>
 </div>

 {/* Google Sign-In */}
 <button
 type="button"
 onClick={handleGoogle}
 disabled={googleLoading || loading}
 className="w-full flex items-center justify-center gap-3 min-h-[44px] rounded-xl border border-surface-700
 bg-surface-800 hover:bg-surface-700 active:scale-[0.98] transition-all text-sm font-medium
 text-surface-200 hover:text-surface-50 disabled:opacity-50 disabled:cursor-not-allowed shadow-sm"
 >
 {googleLoading ? (
 <div className="w-4 h-4 border-2 border-surface-400 border-t-white rounded-full animate-spin" />
 ) : (
 <GoogleIcon />
 )}
 {googleLoading ? 'Signing in…' : 'Continue with Google'}
 </button>

 {/* Divider */}
 <div className="flex items-center gap-3 my-5">
 <div className="flex-1 h-px bg-surface-800" />
 <span className="text-xs text-surface-500 font-medium">or sign in with email</span>
 <div className="flex-1 h-px bg-surface-800" />
 </div>

 {/* Email / Password form */}
 <form onSubmit={handleSubmit} className="space-y-4">
 <Input
 type="email"
 label="Email Address"
 placeholder="admin@it4b.in"
 icon={<Mail size={16} />}
 value={form.email}
 onChange={e => setForm(f => ({ ...f, email: e.target.value }))}
 required
 />

 <div className="flex flex-col gap-1.5">
 <label className="text-sm font-medium text-surface-300">Password</label>
 <div className="relative">
 <span className="absolute left-3 top-1/2 -translate-y-1/2 text-surface-400 pointer-events-none">
 <Lock size={16} />
 </span>
 <input
 type={showPass ? 'text' : 'password'}
 className="w-full rounded-xl border border-surface-700 bg-surface-900 text-surface-100
 placeholder-surface-500 focus:outline-none focus:ring-2 focus:ring-primary-500
 focus:border-transparent min-h-[44px] pl-10 pr-10 py-2.5 text-sm
 hover:border-surface-600 transition-all"
 placeholder="••••••••"
 value={form.password}
 onChange={e => setForm(f => ({ ...f, password: e.target.value }))}
 required
 />
 <button
 type="button"
 className="absolute right-3 top-1/2 -translate-y-1/2 text-surface-400 hover:text-surface-200 transition-colors"
 onClick={() => setShowPass(s => !s)}
 >
 {showPass ? <EyeOff size={16} /> : <Eye size={16} />}
 </button>
 </div>
 </div>

 {error && (
 <div className="rounded-xl bg-red-500/10 border border-red-500/30 px-4 py-3 text-sm text-red-400 animate-fade-in">
 {error}
 </div>
 )}

 <Button type="submit" className="w-full mt-2" loading={loading} size="lg">
 {loading ? 'Signing in...' : 'Sign In'}
 </Button>
 </form>

 </div>
 </div>
 </div>
 )
}
