"use client"

import { useState, useEffect, Suspense } from "react"
import { useRouter, useSearchParams } 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 {
  Key,
  Eye,
  EyeOff,
  CheckCircle,
  Loader2,
  Shield,
  Check,
  X
} from "lucide-react"
import Link from "next/link"
import { motion } from "framer-motion"

function ResetPasswordContent() {
  const [formData, setFormData] = useState({
    password: "",
    confirmPassword: ""
  })
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [status, setStatus] = useState<'idle' | 'success' | 'error' | 'invalid'>('idle')
  const [errors, setErrors] = useState<{ [key: string]: string }>({})
  const router = useRouter()
  const searchParams = useSearchParams()
  const toast = useToast()

  const email = searchParams?.get('email') || ''
  const resetToken = searchParams?.get('token') || ''

  // Check if token is valid on component mount
  useEffect(() => {
    if (!resetToken || !email) {
      setStatus('invalid')
    }
  }, [resetToken, email])

  const validatePassword = (password: string) => {
    const errors = []
    if (password.length < 8) errors.push("At least 8 characters")
    if (!/[A-Z]/.test(password)) errors.push("One uppercase letter")
    if (!/[a-z]/.test(password)) errors.push("One lowercase letter")
    if (!/[0-9]/.test(password)) errors.push("One number")
    return errors
  }

  const passwordRequirements = [
    { text: "At least 8 characters", met: formData.password.length >= 8 },
    { text: "One uppercase letter", met: /[A-Z]/.test(formData.password) },
    { text: "One lowercase letter", met: /[a-z]/.test(formData.password) },
    { text: "One number", met: /[0-9]/.test(formData.password) },
  ]

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }))
    setErrors(prev => ({ ...prev, [field]: "" }))
    setStatus('idle')
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    // Validate password
    const passwordErrors = validatePassword(formData.password)
    if (passwordErrors.length > 0) {
      setErrors({ password: passwordErrors.join(", ") })
      return
    }

    // Validate password confirmation
    if (formData.password !== formData.confirmPassword) {
      setErrors({ confirmPassword: "Passwords do not match" })
      return
    }

    setIsLoading(true)
    setErrors({})

    try {
      console.log('Resetting password for:', email)

      const response = await DataAPI.auth.resetPassword(email, resetToken, formData.password)

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

      if (response.success) {
        setStatus('success')
        toast.success("Your password has been successfully reset.", {
          title: "Password Reset!"
        })

        // Redirect to login after 2 seconds
        setTimeout(() => {
          router.push('/login')
        }, 2000)
      } else {
        throw new Error(response.message || "Failed to reset password")
      }
    } catch (error: any) {
      console.error("Reset password error:", error)
      setStatus('error')
      setErrors({ general: error.message || "Failed to reset password. Please try again." })
      toast.error(error.message || "Failed to reset password. Please try again.", {
        title: "Error"
      })
    } finally {
      setIsLoading(false)
    }
  }

  if (status === 'invalid') {
    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">
          <Card className="w-full max-w-md">
            <CardContent className="text-center py-12 space-y-4">
              <div className="mx-auto w-16 h-16 bg-red-100 rounded-full flex items-center justify-center">
                <X className="w-8 h-8 text-red-600" />
              </div>
              <h2 className="text-xl font-bold text-gray-900">Invalid Reset Link</h2>
              <p className="text-gray-600">This password reset link is invalid or has expired.</p>
              <Link href="/forgot-password">
                <Button className="mt-4">Request New Link</Button>
              </Link>
            </CardContent>
          </Card>
        </main>
        <Footer />
      </div>
    )
  }

  if (status === 'success') {
    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">
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.5 }}
            className="w-full max-w-md"
          >
            <Card className="shadow-xl">
              <CardContent className="text-center py-12 space-y-6">
                <div className="mx-auto w-20 h-20 bg-green-100 rounded-full flex items-center justify-center">
                  <CheckCircle className="w-12 h-12 text-green-600" />
                </div>

                <div className="space-y-2">
                  <h2 className="text-2xl font-bold text-gray-900 font-primary">
                    Password Reset Successful!
                  </h2>
                  <p className="text-gray-600 font-body">
                    Your password has been successfully reset.
                  </p>
                  <p className="text-sm text-gray-500 font-body">
                    Redirecting you to login...
                  </p>
                </div>

                <Link href="/login">
                  <AnimatedButton className="bg-blue-600 hover:bg-blue-700 text-white">
                    Go to Login
                  </AnimatedButton>
                </Link>
              </CardContent>
            </Card>
          </motion.div>
        </main>
        <Footer />
      </div>
    )
  }

  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">
                <Key className="w-10 h-10 text-blue-600" />
              </div>

              <div className="space-y-2">
                <CardTitle className="text-2xl font-bold text-gray-900 font-primary">
                  Create New Password
                </CardTitle>
                <p className="text-sm text-gray-600 font-body">
                  Your password must be strong and secure
                </p>
              </div>
            </CardHeader>

            <CardContent className="space-y-6">
              <form onSubmit={handleSubmit} className="space-y-5">
                {/* New Password */}
                <div className="space-y-2">
                  <Label htmlFor="password" className="text-sm font-medium text-gray-700">
                    New Password
                  </Label>
                  <div className="relative">
                    <Input
                      id="password"
                      type={showPassword ? "text" : "password"}
                      placeholder="Enter new password"
                      value={formData.password}
                      onChange={(e) => handleInputChange("password", e.target.value)}
                      disabled={isLoading}
                      className="h-11 pr-10 font-body"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                    >
                      {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                    </button>
                  </div>
                  {errors.password && (
                    <p className="text-sm text-red-600 font-body">{errors.password}</p>
                  )}
                </div>

                {/* Password Requirements */}
                {formData.password && (
                  <div className="bg-slate-50 rounded-lg p-4 space-y-2">
                    <p className="text-xs font-medium text-gray-700 font-body flex items-center gap-2">
                      <Shield className="w-4 h-4" />
                      Password Requirements
                    </p>
                    <div className="space-y-1">
                      {passwordRequirements.map((req, index) => (
                        <div key={index} className="flex items-center gap-2 text-xs font-body">
                          {req.met ? (
                            <Check className="w-3 h-3 text-green-600" />
                          ) : (
                            <X className="w-3 h-3 text-gray-400" />
                          )}
                          <span className={req.met ? "text-green-600" : "text-gray-600"}>
                            {req.text}
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Confirm Password */}
                <div className="space-y-2">
                  <Label htmlFor="confirmPassword" className="text-sm font-medium text-gray-700">
                    Confirm Password
                  </Label>
                  <div className="relative">
                    <Input
                      id="confirmPassword"
                      type={showConfirmPassword ? "text" : "password"}
                      placeholder="Re-enter new password"
                      value={formData.confirmPassword}
                      onChange={(e) => handleInputChange("confirmPassword", e.target.value)}
                      disabled={isLoading}
                      className="h-11 pr-10 font-body"
                    />
                    <button
                      type="button"
                      onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                    >
                      {showConfirmPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                    </button>
                  </div>
                  {errors.confirmPassword && (
                    <p className="text-sm text-red-600 font-body">{errors.confirmPassword}</p>
                  )}
                </div>

                {/* General Error */}
                {errors.general && (
                  <div className="bg-red-50 border border-red-200 rounded-lg p-3">
                    <p className="text-sm text-red-600 font-body">{errors.general}</p>
                  </div>
                )}

                {/* Submit Button */}
                <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 || !formData.password || !formData.confirmPassword}
                >
                  {isLoading ? (
                    <>
                      <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                      Resetting Password...
                    </>
                  ) : (
                    "Reset Password"
                  )}
                </AnimatedButton>
              </form>

              <div className="text-center">
                <Link
                  href="/login"
                  className="text-sm text-gray-600 hover:text-gray-900 font-body transition-colors"
                >
                  Back to Sign In
                </Link>
              </div>
            </CardContent>
          </AnimatedCard>
        </motion.div>
      </main>

      <Footer />
    </div>
  )
}

export default function ResetPasswordPage() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <ResetPasswordContent />
    </Suspense>
  )
}
