"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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { AnimatedCard } from "@/components/ui/animated-card"
import { Header } from "@/components/ui/header"
import { Footer } from "@/components/ui/footer"
import { Label } from "@/components/ui/label"
import { useToast } from "@/components/ui/toast"
import { DataAPI } from "@/lib/data-api"
import { 
  Mail, 
  ArrowLeft,
  Loader2
} from "lucide-react"
import Link from "next/link"
import { motion } from "framer-motion"

export default function ForgotPasswordPage() {
  const [email, setEmail] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")
  const router = useRouter()
  const toast = useToast()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!email) {
      setError("Please enter your email address")
      return
    }

    if (!email.includes('@')) {
      setError("Please enter a valid email address")
      return
    }

    setIsLoading(true)
    setError("")

    try {
      console.log('Forgot password - Requesting OTP for:', email)
      
      const response = await DataAPI.auth.forgotPassword(email.trim())

      console.log('Forgot password response:', response)

      if (response.success && response.data) {
        toast.success("Please check your email for the verification code.", {
          title: "OTP Sent!"
        })

        // Navigate to OTP verification page
        router.push(`/forgot-password/verify-otp?email=${encodeURIComponent(response.data.email)}&userId=${response.data.userId}`)
      } else {
        throw new Error(response.message || "Failed to send OTP")
      }
    } catch (error: any) {
      console.error("Forgot password error:", error)
      setError(error.message || "Failed to send OTP. Please try again.")
      toast.error(error.message || "Failed to send OTP. Please try again.", {
        title: "Error"
      })
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30 flex flex-col">
      <Header />

      <main className="flex-1 flex items-center justify-center px-4 py-12">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
          className="w-full max-w-md"
        >
          <AnimatedCard className="shadow-xl border-t-4 border-t-blue-500">
            <CardHeader className="space-y-4 text-center pb-6">
              <div className="mx-auto w-20 h-20 bg-gradient-to-br from-blue-100 to-blue-50 rounded-full flex items-center justify-center shadow-sm">
                <Mail className="w-10 h-10 text-blue-600" />
              </div>
              
              <div className="space-y-3">
                <CardTitle className="text-2xl font-bold text-gray-900 font-primary">
                  Forgot Password?
                </CardTitle>
                <p className="text-sm text-gray-600 font-body leading-relaxed">
                  No worries! Enter your email address and we'll send you a verification code to reset your password.
                </p>
              </div>
            </CardHeader>

            <CardContent className="space-y-6">
              <form onSubmit={handleSubmit} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="email" className="text-sm font-medium text-gray-700">
                    Email Address
                  </Label>
                  <Input
                    id="email"
                    type="email"
                    placeholder="your.email@example.com"
                    value={email}
                    onChange={(e) => {
                      setEmail(e.target.value)
                      setError("")
                    }}
                    disabled={isLoading}
                    className="h-11 font-body"
                    autoFocus
                  />
                  {error && (
                    <p className="text-sm text-red-600 font-body">{error}</p>
                  )}
                </div>

                <AnimatedButton
                  type="submit"
                  className="w-full h-12 bg-gradient-to-r from-blue-600 to-blue-500 hover:from-blue-700 hover:to-blue-600 text-white font-semibold shadow-lg hover:shadow-xl transition-all"
                  disabled={isLoading}
                >
                  {isLoading ? (
                    <>
                      <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                      Sending Code...
                    </>
                  ) : (
                    "Send Verification Code"
                  )}
                </AnimatedButton>
              </form>

              <div className="text-center">
                <Link 
                  href="/login"
                  className="inline-flex items-center text-sm text-gray-600 hover:text-gray-900 font-body transition-colors"
                >
                  <ArrowLeft className="w-4 h-4 mr-1" />
                  Back to Sign In
                </Link>
              </div>
            </CardContent>
          </AnimatedCard>
        </motion.div>
      </main>

      <Footer />
    </div>
  )
}
