"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";

export function NewsletterPopup() {
  const [open, setOpen] = useState(false);
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{ text: string; ok: boolean } | null>(null);

  useEffect(() => {
    // Disabled auto-show newsletter popup as requested by user
  }, []);

  const close = () => {
    window.sessionStorage.setItem("newsletter_seen", "true");
    setOpen(false);
  };

  const handleSubscribe = async () => {
    if (!email.trim()) {
      setMessage({ text: "ইমেইল প্রবেশ করুন।", ok: false });
      return;
    }

    setLoading(true);
    setMessage(null);
    try {
      const apiBase = process.env.NEXT_PUBLIC_API_URL ?? "http://127.0.0.1:8000/api/v1";
      const res = await fetch(`${apiBase}/newsletter/subscribe`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });

      const data = await res.json();
      if (res.ok) {
        setMessage({ text: data.message, ok: true });
        setEmail("");
        setTimeout(() => close(), 2000);
      } else {
        setMessage({ text: data.message || "সাবস্ক্রিপশন ব্যর্থ।", ok: false });
      }
    } catch {
      setMessage({ text: "নেটওয়ার্ক সমস্যা।", ok: false });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent className="max-w-md rounded-3xl">
        <DialogHeader>
          <DialogTitle className="text-2xl">15% Off Your First Order</DialogTitle>
          <DialogDescription>
            Join our private list for launches, styling edits, and limited drops.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-3">
          <Input 
            type="email" 
            placeholder="আপনার ইমেইল..." 
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleSubscribe()}
            disabled={loading}
          />
          {message && (
            <p className={`text-sm ${message.ok ? "text-green-600" : "text-red-600"}`}>
              {message.text}
            </p>
          )}
          <Button 
            className="w-full" 
            onClick={handleSubscribe}
            disabled={loading}
          >
            {loading ? "সাবস্ক্রাইব করছেন..." : "Unlock Offer"}
          </Button>
          <button
            type="button"
            onClick={close}
            className="w-full text-xs text-muted-foreground underline underline-offset-4"
          >
            না, ধন্যবাদ
          </button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
