"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { AnimatedButton } from "@/components/ui/animated-button"
import { Input } from "@/components/ui/input"
import { AnimatedInput } from "@/components/ui/animated-input"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { AnimatedCard } from "@/components/ui/animated-card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
import { Checkbox } from "@/components/ui/checkbox"
import { Eye, EyeOff, Mail, Phone, ArrowLeft, Loader2, AlertCircle } from "lucide-react"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { useToast } from "@/components/ui/toast"
import { useAuth } from "@/hooks/use-auth"
import { DataAPI } from "@/lib/data-api"
import Image from "next/image"
import Link from "next/link"

export default function LoginPage() {
  const router = useRouter()
  const toast = useToast()
  const { login: authLogin, refreshAuth } = useAuth()
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")
  const [formData, setFormData] = useState({
    email: "",
    password: "",
    rememberMe: false
  })

  const handleInputChange = (field: string, value: string | boolean) => {
    setFormData((prev) => ({ ...prev, [field]: value }))
    // Clear error when user starts typing
    if (error) {
      setError("")
    }
  }

  const validateForm = () => {
    if (!formData.email.trim()) {
      setError("Email is required")
      return false
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      setError("Please enter a valid email address")
      return false
    }
    if (!formData.password) {
      setError("Password is required")
      return false
    }
    return true
  }

  const handleLogin = async () => {
    if (!validateForm() || isLoading) {
      return
    }

    setIsLoading(true)
    setError("")

    try {
      console.log('Login page - Attempting login with:', formData.email)
      
      // Use authLogin from useAuth hook to update context
      const response = await authLogin(
        formData.email.trim(),
        formData.password,
        formData.rememberMe
      )

      console.log('Login page - Auth login response:', response)

      if (response) {
        const { user, redirectUrl, nextStep } = response

        // Debug logging
        console.log('Login page - User data extracted:', user)
        console.log('Login page - User firstName:', user?.firstName)
        console.log('Login page - Redirect URL:', redirectUrl)
        console.log('Login page - Next step:', nextStep)

        // Safe access to user properties
        const userName = user?.firstName || user?.email?.split('@')[0] || 'User'

        toast.success(`Welcome back, ${userName}!`, {
          title: "Login Successful!"
        })

        console.log('Login page - Preparing redirect...')
        
        // Handle different user states and redirect accordingly
        if (redirectUrl) {
          console.log('Redirecting to:', redirectUrl)
          
          // For OTP verification, use multiple approaches for reliability
          if (redirectUrl.includes('verify-otp')) {
            console.log('Using multiple redirect approaches for OTP verification')
            
            // Try router.push first
            try {
              router.push(redirectUrl)
              console.log('Router.push attempted for:', redirectUrl)
              
              // Fallback to window.location after a short delay if router.push doesn't work
              setTimeout(() => {
                if (window.location.pathname === '/login') {
                  console.log('Router.push failed, using window.location.href')
                  window.location.href = redirectUrl
                }
              }, 1000)
            } catch (routerError) {
              console.error('Router.push failed:', routerError)
              console.log('Falling back to window.location.href')
              window.location.href = redirectUrl
            }
            return
          } else {
            // Use router.push for other redirects
            router.push(redirectUrl)
          }
        } else if (user?.role) {
          // Fallback redirect based on role
          let fallbackUrl = '/'
          switch (user.role) {
            case 'facility_owner':
              fallbackUrl = '/facility-owner/dashboard'
              break
            case 'family':
              fallbackUrl = '/dashboard'
              break
            case 'admin':
            case 'super_admin':
              fallbackUrl = '/admin/dashboard'
              break
          }
          console.log('Fallback redirect to:', fallbackUrl)
          router.push(fallbackUrl)
        } else {
          console.error('User role not found in response:', user)
          router.push('/')
        }

        // Refresh auth state after redirect is initiated
        setTimeout(async () => {
          try {
            await refreshAuth()
            console.log('Auth state refreshed after redirect')
          } catch (error) {
            console.error('Failed to refresh auth state:', error)
          }
        }, 100)
      } else {
        console.error("Login failed - Invalid response data:", response)
        throw new Error("Login failed - Invalid response data")
      }
    } catch (error: any) {
      console.error("Login error:", error)
      setError(error.message || "Login failed. Please try again.")
      toast.error(error.message || "Please check your credentials and try again.", {
        title: "Login Failed"
      })
    } finally {
      // Only set loading to false if we're not redirecting
      if (!window.location.href.includes('verify-otp')) {
        setIsLoading(false)
      }
    }
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !isLoading) {
      handleLogin()
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50">
      {/* Header */}
      <header className="border-b border-slate-200 bg-white/80 backdrop-blur-sm">
        <div className="container mx-auto px-6 py-6">
          <div className="flex items-center justify-between">
            <Link href="/" className="flex items-center space-x-4 group">
              <ArrowLeft className="h-5 w-5 text-slate-400 group-hover:text-slate-600 transition-colors" />
              <Image
                src="/images/geezer-guide-logo.png"
                alt="Geezer Guide"
                width={220}
                height={110}
                className="h-14 w-auto drop-shadow-sm"
              />
            </Link>
          </div>
        </div>
      </header>

      <div className="container mx-auto px-6 py-16">
        <div className="max-w-lg mx-auto">
          <div className="text-center mb-12">
            <div className="inline-flex items-center justify-center w-16 h-16 bg-blue-100 rounded-full mb-6">
              <svg className="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
              </svg>
            </div>
            <h1 className="font-heading text-4xl md:text-5xl text-slate-800 mb-4 font-bold">
              Welcome Back
            </h1>
            <p className="font-body text-lg text-slate-600 leading-relaxed max-w-md mx-auto">
              Sign in to your account to continue your journey with us
            </p>
          </div>

          <AnimatedCard className="shadow-2xl border-0 bg-white/90 backdrop-blur-sm">
            <CardHeader className="pb-8 pt-10">
              <CardTitle className="font-heading text-3xl text-center text-slate-800 mb-2">Sign In</CardTitle>
              <p className="text-center text-slate-500 text-sm">Enter your credentials to access your account</p>
            </CardHeader>
            <CardContent className="space-y-8 px-10 pb-10">
              {error && (
                <Alert variant="destructive" className="border-red-200 bg-red-50">
                  <AlertCircle className="h-5 w-5" />
                  <AlertDescription className="text-red-700">{error}</AlertDescription>
                </Alert>
              )}

              <div className="space-y-6">
                <div className="space-y-3">
                  <Label htmlFor="email" className="font-body text-base font-medium text-slate-700">Email Address</Label>
                  <div className="relative group">
                    <Mail className="absolute left-4 top-1/2 transform -translate-y-1/2 h-5 w-5 text-slate-500 group-focus-within:text-blue-500 transition-colors z-10 pointer-events-none" />
                    <AnimatedInput
                      id="email"
                      type="email"
                      placeholder="Enter your email address"
                      value={formData.email}
                      onChange={(e) => handleInputChange("email", e.target.value)}
                      onKeyPress={handleKeyPress}
                      className="pl-12 pr-4 h-14 text-base border-slate-200 focus:border-blue-500 focus:ring-blue-500/20 rounded-xl bg-slate-50 focus:bg-white transition-all duration-200 relative"
                      disabled={isLoading}
                    />
                  </div>
                </div>

                <div className="space-y-3">
                  <Label htmlFor="password" className="font-body text-base font-medium text-slate-700">Password</Label>
                  <div className="relative group">
                    <AnimatedInput
                      id="password"
                      type={showPassword ? "text" : "password"}
                      placeholder="Enter your password"
                      value={formData.password}
                      onChange={(e) => handleInputChange("password", e.target.value)}
                      onKeyPress={handleKeyPress}
                      className="pr-12 pl-4 h-14 text-base border-slate-200 focus:border-blue-500 focus:ring-blue-500/20 rounded-xl bg-slate-50 focus:bg-white transition-all duration-200"
                      disabled={isLoading}
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-4 top-1/2 transform -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors"
                      disabled={isLoading}
                    >
                      {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                    </button>
                  </div>
                </div>

                <div className="flex items-center justify-between pt-2">
                  <div className="flex items-center space-x-3">
                    <Checkbox
                      id="rememberMe"
                      checked={formData.rememberMe}
                      onCheckedChange={(checked) => handleInputChange("rememberMe", checked as boolean)}
                      disabled={isLoading}
                      className="border-slate-300 data-[state=checked]:bg-blue-600 data-[state=checked]:border-blue-600"
                    />
                    <Label htmlFor="rememberMe" className="font-body text-base cursor-pointer text-slate-600">
                      Remember me
                    </Label>
                  </div>
                  <Link 
                    href="/forgot-password" 
                    className="font-body text-base text-blue-600 hover:text-blue-700 hover:underline transition-colors"
                  >
                    Forgot password?
                  </Link>
                </div>

                <AnimatedButton
                  onClick={(e) => {
                    e.preventDefault()
                    handleLogin()
                  }}
                  disabled={isLoading}
                  className="w-full h-14 text-lg bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 font-body font-semibold rounded-xl shadow-lg hover:shadow-xl transition-all duration-200 border-0"
                  loading={isLoading}
                  loadingText="Signing in..."
                >
                  {isLoading ? (
                    <>
                      <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                      Signing in...
                    </>
                  ) : (
                    "Sign In"
                  )}
                </AnimatedButton>
              </div>

              <Separator className="my-8" />

              <div className="text-center">
                <p className="font-body text-base text-slate-600 leading-relaxed">
                  Don't have an account?{" "}
                  <Link href="/register" className="text-blue-600 hover:text-blue-700 hover:underline font-semibold transition-colors duration-200">
                    Sign up here
                  </Link>
                </p>
              </div>
            </CardContent>
          </AnimatedCard>

          <div className="text-center mt-10">
            <div className="inline-flex items-center space-x-2 text-slate-500 text-sm">
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span>Need help? Email us at{" "}
                <a href="mailto:support@geezerguide.com" className="text-blue-600 hover:text-blue-700 hover:underline transition-colors duration-200 font-medium">
                  support@geezerguide.com
                </a>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}