"use client"

import { useState } from "react"

export function NewsletterPopup() {
  const [email, setEmail] = useState("")
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<{title: string, desc: string, isError: boolean} | null>(null)

  const handleSubscribe = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!email) return

    setLoading(true)
    setResult(null)
    
    // Simulate API call
    setTimeout(() => {
      setLoading(false)
      
      if (email.includes("@") && email.includes(".")) {
        setResult({
          title: "Subscribed successfully!",
          desc: "Thank You.",
          isError: false
        })
        setEmail("")
      } else {
        setResult({
          title: "Subscription failed",
          desc: "Please enter a valid email address.",
          isError: true
        })
      }
      
      // Auto-hide the message and restore button after 1.5 seconds
      setTimeout(() => {
        setResult(null)
      }, 1500)
    }, 1000)
  }

  return (
    <div className="bg-card rounded-[16px] border border-border p-7 shadow-sm">
      <div className="relative mb-6 pb-3">
        <h3 className="text-[18px] font-bold text-foreground">Subscribe to Our Newsletter</h3>
        <div className="absolute bottom-0 left-0 w-full h-[2px] bg-primary/20" />
        <div className="absolute bottom-0 left-0 w-12 h-[2px] bg-primary" />
      </div>
      <p className="text-[14px] text-muted-foreground mb-5 leading-relaxed">
        Get the latest AI insights delivered to your inbox.
      </p>
      
      <form onSubmit={handleSubscribe} className="flex flex-col gap-3">
        <input 
          type="email" 
          placeholder="Your email address" 
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          className="w-full bg-transparent border border-input rounded-md px-4 py-3 text-[14px] focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
          required
        />
        
        {result ? (
          <div className={`p-3 rounded-md text-sm border ${result.isError ? "bg-destructive/10 text-destructive border-destructive/20" : "bg-primary/10 text-primary border-primary/20"}`}>
            <strong>{result.title}</strong>
            <p className="mt-1 opacity-90">{result.desc}</p>
          </div>
        ) : (
          <button 
            type="submit" 
            disabled={loading} 
            className="bg-primary hover:bg-primary/90 text-primary-foreground px-5 py-2.5 text-[14px] font-medium rounded-md transition-colors disabled:opacity-50"
          >
            {loading ? "Subscribing..." : "Subscribe"}
          </button>
        )}
      </form>
    </div>
  )
}
