"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Phone, ShieldAlert, Copy, Check, Loader2 } from "lucide-react"
import { formatPhoneNumberIntl } from "react-phone-number-input"
import { copyToClipboard } from "@/lib/utils"
import Link from "next/link"

interface PhoneRevealButtonProps {
  phone: string
  productId: string
  sellerId: string
  referralCode?: string | null
  className?: string
  isAuthenticated?: boolean
  returnUrl?: string
}

export function PhoneRevealButton({
  phone,
  productId,
  sellerId,
  referralCode,
  className,
  isAuthenticated = false,
  returnUrl = "/shop",
}: PhoneRevealButtonProps) {
  const [warningOpen, setWarningOpen] = useState(false)
  const [registerOpen, setRegisterOpen] = useState(false)
  const [revealed, setRevealed] = useState(false)
  const [logging, setLogging] = useState(false)
  const [copied, setCopied] = useState(false)

  const formattedPhone = (() => {
    try {
      return formatPhoneNumberIntl(phone)
    } catch {
      return phone
    }
  })()

  const logEvent = async (type: string) => {
    try {
      await fetch("/api/contact-events", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          productId,
          sellerId,
          type,
          referralCode: referralCode || undefined,
        }),
      })
    } catch {
      // Analytics must never block the user from seeing the phone number.
    }
  }

  const handleConfirm = async () => {
    setWarningOpen(false)
    setLogging(true)
    await logEvent("PHONE_REVEAL")
    setLogging(false)
    setRevealed(true)
  }

  const handleCall = async () => {
    await logEvent("CALL_CLICK")
  }

  const handleCopy = async () => {
    const ok = await copyToClipboard(phone)
    if (ok) {
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    }
  }

  if (revealed) {
    return (
      <div className={`reveal-phone-in ${className || ""}`}>
        <div className="flex items-center justify-between gap-3 rounded-xl border border-purple-200 bg-purple-50 p-4">
          <div className="flex items-center gap-3 min-w-0">
            <Phone className="h-5 w-5 text-purple-600 shrink-0" />
            <a
              href={`tel:${phone}`}
              onClick={handleCall}
              className="text-lg font-bold text-gray-900 hover:text-purple-600 transition-colors truncate"
            >
              {formattedPhone}
            </a>
          </div>
          <Button
            variant="ghost"
            size="icon"
            onClick={handleCopy}
            className="shrink-0"
            aria-label="Copy phone number"
          >
            {copied ? (
              <Check className="h-4 w-4 text-purple-600" />
            ) : (
              <Copy className="h-4 w-4" />
            )}
          </Button>
        </div>
        <a href={`tel:${phone}`} onClick={handleCall} className="mt-3 block">
          <Button className="w-full bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 text-white py-6 text-lg">
            <Phone className="mr-2 h-5 w-5" />
            Call Seller Now
          </Button>
        </a>
      </div>
    )
  }

  return (
    <>
      <Button
        onClick={() => (isAuthenticated ? setWarningOpen(true) : setRegisterOpen(true))}
        className={
          className ||
          "w-full bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 text-white shadow-lg text-lg py-6"
        }
      >
        <Phone className="mr-2 h-5 w-5" />
        Show Phone Number
      </Button>

      <Dialog open={registerOpen} onOpenChange={setRegisterOpen}>
        <DialogContent className="sm:max-w-[460px] w-[95vw]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-purple-600">
              <Phone className="h-5 w-5" />
              Register to View Phone Number
            </DialogTitle>
            <DialogDescription className="space-y-3 pt-2 text-sm">
              <p>To protect sellers from spam and scams, only registered members can view the seller's phone number.</p>
              <p>Create a free account to continue, you'll be returned to this product right after.</p>
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="flex-col sm:flex-row gap-2">
            <Button
              variant="outline"
              onClick={() => setRegisterOpen(false)}
              className="w-full sm:w-auto"
            >
              Cancel
            </Button>
            <Link
              href={`/register?next=${encodeURIComponent(returnUrl)}`}
              className="w-full sm:w-auto"
            >
              <Button className="w-full bg-purple-600 hover:bg-purple-700 text-white">
                Create Account
              </Button>
            </Link>
          </DialogFooter>
          <p className="text-center text-sm text-gray-500 pt-1">
            Already have an account?{" "}
            <Link href={`/login?next=${encodeURIComponent(returnUrl)}`} className="text-purple-600 underline">
              Sign in
            </Link>
          </p>
        </DialogContent>
      </Dialog>

      <Dialog open={warningOpen} onOpenChange={setWarningOpen}>
        <DialogContent className="sm:max-w-[460px] w-[95vw]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-amber-600">
              <ShieldAlert className="h-5 w-5" />
              Safety First
            </DialogTitle>
            <DialogDescription className="space-y-3 pt-2 text-sm">
              <p>Please follow these safety rules before contacting the seller:</p>
              <ul className="list-disc pl-5 space-y-1.5 text-gray-700">
                <li>Do not pay online or transfer money in advance.</li>
                <li>Meet the seller in a safe, public place.</li>
                <li>Inspect the item physically and confirm it is exactly as described.</li>
                <li>Never share your PIN, OTP, or bank card details.</li>
              </ul>
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="flex-col sm:flex-row gap-2">
            <Button
              variant="outline"
              onClick={() => setWarningOpen(false)}
              className="w-full sm:w-auto"
            >
              Cancel
            </Button>
            <Button
              onClick={handleConfirm}
              disabled={logging}
              className="w-full sm:w-auto bg-purple-600"
            >
              {logging && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              I Understand, Show Number
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
