"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { OTPForm } from "@/components/auth/otp-form"
import { useVendorAuth } from "@/lib/vendor-auth-context"
import { Loader2, ArrowLeft, CheckCircle2, Copy, Check } from "lucide-react"

export default function VendorVerifyPage() {
  const router = useRouter()
  const { vendorVerifyOTP, vendorResendOTP, pendingEmail, setPendingEmail, getPendingOTP, isLoading: authLoading } = useVendorAuth()
  const demoOTP = pendingEmail ? getPendingOTP(pendingEmail) : null
  const [otp, setOtp] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")
  const [isSuccess, setIsSuccess] = useState(false)

  useEffect(() => {
    if (!authLoading && !pendingEmail) {
      router.push("/vendor-signup")
    }
  }, [pendingEmail, router, authLoading])

  const handleVerify = async () => {
    if (!pendingEmail || otp.length !== 6) {
      setError("Please enter the complete 6-digit code")
      return
    }
    setError("")
    setIsLoading(true)
    try {
      const result = await vendorVerifyOTP(pendingEmail, otp)
      if (result.success) {
        setIsSuccess(true)
        setTimeout(() => router.push("/vendor-signup/onboarding"), 1200)
      } else {
        setError(result.error ?? "Verification failed")
        setOtp("")
      }
    } finally {
      setIsLoading(false)
    }
  }

  const handleResend = async () => {
    if (!pendingEmail) return
    setError("")
    const result = await vendorResendOTP(pendingEmail)
    if (!result.success) setError(result.error ?? "Failed to resend")
  }

  useEffect(() => {
    if (otp.length === 6 && !isLoading && !isSuccess && pendingEmail) {
      handleVerify()
    }
  }, [otp])

  if (authLoading || !pendingEmail) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    )
  }

  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>
        <h1 className="text-2xl font-bold tracking-tight text-foreground">Email verified</h1>
        <p className="text-muted-foreground">Redirecting to onboarding...</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <Link
        href="/vendor-signup"
        onClick={() => setPendingEmail(null)}
        className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground"
      >
        <ArrowLeft className="mr-2 h-4 w-4" />
        Back to sign up
      </Link>
      <div className="space-y-2 text-center">
        <h1 className="text-2xl font-bold tracking-tight text-foreground">Verify your email</h1>
        <p className="text-muted-foreground">
          We sent a 6-digit code to <span className="font-medium text-foreground">{pendingEmail}</span>
        </p>
      </div>
      <OTPForm value={otp} onChange={setOtp} onResend={handleResend} error={error} disabled={isLoading} />

      {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>
      )}

      <Button onClick={handleVerify} className="w-full" size="lg" disabled={otp.length !== 6 || isLoading}>
        {isLoading ? (
          <>
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            Verifying...
          </>
        ) : (
          "Verify and continue"
        )}
      </Button>
    </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>
  )
}
