"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { OTPForm } from "@/components/auth/otp-form"
import { PasswordInput, validatePassword } from "@/components/auth/password-input"
import { useAuth } from "@/lib/auth-context"
import { Loader2, ArrowLeft, CheckCircle2, Copy, Check } from "lucide-react"

export default function ResetPasswordPage() {
  const router = useRouter()
  const { resetPassword, resendOTP, pendingEmail, setPendingEmail, getPendingOTP } = useAuth()
  const demoOTP = pendingEmail ? getPendingOTP(pendingEmail) : null
  const [otp, setOtp] = useState("")
  const [newPassword, setNewPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")
  const [isSuccess, setIsSuccess] = useState(false)

  useEffect(() => {
    if (!pendingEmail) {
      router.push("/forgot-password")
    }
  }, [pendingEmail, router])

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

    if (otp.length !== 6) {
      setError("Please enter the complete 6-digit code")
      return
    }

    const passwordValidation = validatePassword(newPassword)
    if (!passwordValidation.valid) {
      setError("Password does not meet requirements")
      return
    }

    if (newPassword !== confirmPassword) {
      setError("Passwords do not match")
      return
    }

    setIsLoading(true)

    try {
      const result = await resetPassword(pendingEmail!, otp, newPassword)
      if (result.success) {
        setIsSuccess(true)
        setTimeout(() => {
          setPendingEmail(null)
          router.push("/login")
        }, 2000)
      } else {
        setError(result.error || "Failed to reset password")
      }
    } finally {
      setIsLoading(false)
    }
  }

  const handleResend = async () => {
    if (!pendingEmail) return
    setError("")
    // Request a new reset code
    const result = await resendOTP(pendingEmail)
    if (!result.success) {
      setError(result.error || "Failed to resend code")
    }
  }

  if (!pendingEmail) {
    return null
  }

  if (isSuccess) {
    return (
      <div className="space-y-6 text-center">
        <div className="flex justify-center">
          <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center">
            <CheckCircle2 className="w-8 h-8 text-green-600" />
          </div>
        </div>
        <div className="space-y-2">
          <h1 className="text-2xl font-bold tracking-tight text-foreground">Password Reset!</h1>
          <p className="text-muted-foreground">Redirecting to login...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <Link
        href="/forgot-password"
        onClick={() => setPendingEmail(null)}
        className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
      >
        <ArrowLeft className="mr-2 h-4 w-4" />
        Back
      </Link>

      <div className="space-y-2 text-center">
        <h1 className="text-2xl font-bold tracking-tight text-foreground">Set new password</h1>
        <p className="text-muted-foreground">
          Enter the code sent to{" "}
          <span className="font-medium text-foreground">{pendingEmail}</span>
        </p>
      </div>

      {demoOTP && (
        <div className="rounded-xl border-2 border-primary/20 bg-primary/5 p-4">
          <p className="text-xs font-medium text-muted-foreground mb-2">Demo — your code (enter below or copy):</p>
          <div className="flex items-center justify-between gap-3">
            <span className="font-mono text-2xl font-bold tracking-[0.35em] text-foreground select-all">{demoOTP}</span>
            <CopyOTPButton otp={demoOTP} />
          </div>
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-2">
          <Label>Verification code</Label>
          <OTPForm
            value={otp}
            onChange={setOtp}
            onResend={handleResend}
            disabled={isLoading}
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="newPassword">New password</Label>
          <PasswordInput
            id="newPassword"
            placeholder="Create a new password"
            value={newPassword}
            onChange={(e) => setNewPassword(e.target.value)}
            showStrength
            required
            disabled={isLoading}
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="confirmPassword">Confirm new password</Label>
          <PasswordInput
            id="confirmPassword"
            placeholder="Confirm your new password"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            required
            disabled={isLoading}
          />
        </div>

        {error && (
          <div className="p-3 rounded-lg bg-destructive/10 border border-destructive/20">
            <p className="text-sm text-destructive">{error}</p>
          </div>
        )}

        <Button
          type="submit"
          className="w-full"
          size="lg"
          disabled={isLoading}
        >
          {isLoading ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Resetting password...
            </>
          ) : (
            "Reset password"
          )}
        </Button>
      </form>

    </div>
  )
}

function CopyOTPButton({ otp }: { otp: string }) {
  const [copied, setCopied] = useState(false)
  const copy = () => {
    navigator.clipboard.writeText(otp)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }
  return (
    <Button type="button" variant="outline" size="sm" className="shrink-0 gap-1.5" onClick={copy}>
      {copied ? <Check className="h-4 w-4 text-green-600" /> : <Copy className="h-4 w-4" />}
      {copied ? "Copied" : "Copy"}
    </Button>
  )
}
