"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";

export default function AdminPopupsPage() {
    const [popups, setPopups] = useState<any[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [isEditing, setIsEditing] = useState(false);

    // Form State
    const [id, setId] = useState<string | null>(null);
    const [title, setTitle] = useState("");
    const [message, setMessage] = useState("");
    const [imageUrl, setImageUrl] = useState("");
    const [ctaText, setCtaText] = useState("");
    const [ctaLink, setCtaLink] = useState("");
    const [excludePaths, setExcludePaths] = useState("");
    const [startDate, setStartDate] = useState("");
    const [endDate, setEndDate] = useState("");
    const [maxDisplays, setMaxDisplays] = useState("3");
    const [isUnlimited, setIsUnlimited] = useState(false);
    const [isActive, setIsActive] = useState(true);

    const router = useRouter();

    useEffect(() => {
        fetchPopups();
    }, []);

    const fetchPopups = async () => {
        setIsLoading(true);
        try {
            const res = await fetch("/api/admin/popups");
            if (res.ok) {
                const data = await res.json();
                setPopups(data);
            }
        } catch (error) {
            console.error("Failed to fetch popups:", error);
        } finally {
            setIsLoading(false);
        }
    };

    const handleEdit = (popup: any) => {
        setId(popup.id);
        setTitle(popup.title);
        setMessage(popup.message);
        setImageUrl(popup.imageUrl || "");
        setCtaText(popup.ctaText || "");
        setCtaLink(popup.ctaLink || "");
        setExcludePaths(popup.excludePaths || "");
        setStartDate(popup.startDate ? new Date(popup.startDate).toISOString().slice(0, 10) : "");
        setEndDate(popup.endDate ? new Date(popup.endDate).toISOString().slice(0, 10) : "");
        setIsUnlimited(popup.maxDisplaysPerUser === 0);
        setMaxDisplays(popup.maxDisplaysPerUser === 0 ? "3" : popup.maxDisplaysPerUser.toString());
        setIsActive(popup.isActive);
        setIsEditing(true);
    };

    const handleCreateNew = () => {
        setId(null);
        setTitle("");
        setMessage("");
        setImageUrl("");
        setCtaText("");
        setCtaLink("");
        setExcludePaths("");
        setStartDate("");
        setEndDate("");
        setMaxDisplays("3");
        setIsUnlimited(false);
        setIsActive(true);
        setIsEditing(true);
    };

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

        const payload = {
            title, message, imageUrl, ctaText, ctaLink,
            excludePaths: excludePaths.trim() || null,
            startDate: startDate || null,
            endDate: endDate || null,
            maxDisplaysPerUser: isUnlimited ? 0 : parseInt(maxDisplays),
            isActive
        };

        try {
            const url = id ? `/api/admin/popups/${id}` : "/api/admin/popups";
            const method = id ? "PUT" : "POST";

            const res = await fetch(url, {
                method,
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(payload)
            });

            if (res.ok) {
                setIsEditing(false);
                fetchPopups();
            } else {
                alert("Failed to save popup.");
            }
        } catch (err) {
            console.error(err);
        }
    };

    const handleDelete = async (deleteId: string) => {
        if (!confirm("Are you sure you want to delete this popup?")) return;

        try {
            const res = await fetch(`/api/admin/popups/${deleteId}`, { method: "DELETE" });
            if (res.ok) {
                fetchPopups();
            }
        } catch (err) {
            console.error(err);
        }
    };

    const inputStyle = {
        width: "100%", padding: "0.5rem", borderRadius: "8px",
        border: "1px solid var(--border)", background: "var(--background)",
        color: "var(--foreground)", fontFamily: "inherit"
    };

    return (
        <div className="container" style={{ padding: "4rem 1.5rem" }}>
            <div style={{ marginBottom: "2rem" }}>
                <a href="/admin" style={{ display: "inline-flex", alignItems: "center", gap: "0.5rem", color: "var(--text-muted)", textDecoration: "none", fontWeight: 600, transition: "color 0.2s" }} onMouseOver={e => e.currentTarget.style.color = "var(--primary)"} onMouseOut={e => e.currentTarget.style.color = "var(--text-muted)"}>
                    &larr; Back to Dashboard
                </a>
            </div>

            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "2rem" }}>
                <h1 style={{ fontSize: "2.5rem" }}>Promotional Popups</h1>
                <button onClick={handleCreateNew} className="btn-primary">
                    + New Popup
                </button>
            </div>

            {isEditing && (
                <div className="glass-panel" style={{ padding: "2rem", marginBottom: "3rem" }}>
                    <h2 style={{ marginBottom: "1.5rem" }}>{id ? "Edit Popup" : "Create New Popup"}</h2>
                    <form onSubmit={handleSubmit} style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1.5rem" }}>
                        <div style={{ gridColumn: "1 / -1" }}>
                            <label style={{ display: "block", marginBottom: "0.5rem" }}>Title *</label>
                            <input required type="text" style={inputStyle} value={title} onChange={e => setTitle(e.target.value)} />
                        </div>
                        <div style={{ gridColumn: "1 / -1" }}>
                            <label style={{ display: "block", marginBottom: "0.5rem" }}>Message *</label>
                            <textarea required rows={3} style={inputStyle} value={message} onChange={e => setMessage(e.target.value)} />
                        </div>
                        <div style={{ gridColumn: "1 / -1" }}>
                            <label style={{ display: "block", marginBottom: "0.5rem" }}>Image URL (Optional)</label>
                            <input type="text" style={inputStyle} value={imageUrl} onChange={e => setImageUrl(e.target.value)} placeholder="/school.jpg or https://" />
                        </div>
                        <div>
                            <label style={{ display: "block", marginBottom: "0.5rem" }}>CTA Button Text (Optional)</label>
                            <input type="text" style={inputStyle} value={ctaText} onChange={e => setCtaText(e.target.value)} placeholder="e.g. Shop Now" />
                        </div>
                        <div>
                            <label style={{ display: "block", marginBottom: "0.5rem" }}>CTA Button Link (Optional)</label>
                            <input type="text" style={inputStyle} value={ctaLink} onChange={e => setCtaLink(e.target.value)} placeholder="e.g. /shop" />
                        </div>
                        <div style={{ gridColumn: "1 / -1" }}>
                            <label style={{ display: "block", marginBottom: "0.5rem" }}>Hide On Pages (Optional)</label>
                            <input type="text" style={inputStyle} value={excludePaths} onChange={e => setExcludePaths(e.target.value)} placeholder="e.g. /rock-your-locker, /faq" />
                            <small style={{ color: "var(--text-muted)" }}>Comma-separated paths where this popup should never show.</small>
                        </div>
                        <div>
                            <label style={{ display: "block", marginBottom: "0.5rem" }}>Start Date (Optional)</label>
                            <input type="date" style={inputStyle} value={startDate} onChange={e => setStartDate(e.target.value)} />
                        </div>
                        <div>
                            <label style={{ display: "block", marginBottom: "0.5rem" }}>End Date (Optional)</label>
                            <input type="date" style={inputStyle} value={endDate} onChange={e => setEndDate(e.target.value)} />
                        </div>
                        <div>
                            <label style={{ display: "block", marginBottom: "0.5rem" }}>Max Displays Per User</label>
                            <input type="number" min="1" disabled={isUnlimited} style={{ ...inputStyle, opacity: isUnlimited ? 0.5 : 1 }} value={maxDisplays} onChange={e => setMaxDisplays(e.target.value)} />
                            <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginTop: "0.5rem" }}>
                                <input type="checkbox" id="isUnlimited" checked={isUnlimited} onChange={e => setIsUnlimited(e.target.checked)} />
                                <label htmlFor="isUnlimited" style={{ fontSize: "0.9rem" }}>Unlimited</label>
                            </div>
                            <small style={{ color: "var(--text-muted)" }}>Prevents spamming the same user.</small>
                        </div>
                        <div style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}>
                            <input type="checkbox" id="isActive" checked={isActive} onChange={e => setIsActive(e.target.checked)} />
                            <label htmlFor="isActive" style={{ fontWeight: 600 }}>Active (Will deactivate other popups)</label>
                        </div>

                        <div style={{ gridColumn: "1 / -1", display: "flex", gap: "1rem", marginTop: "1rem" }}>
                            <button type="submit" className="btn-primary">Save Popup</button>
                            <button type="button" onClick={() => setIsEditing(false)} style={{ padding: "0.75rem 1.5rem", borderRadius: "8px", border: "1px solid var(--border)", background: "transparent", cursor: "pointer" }}>Cancel</button>
                        </div>
                    </form>
                </div>
            )}

            <div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
                {isLoading ? (
                    <p>Loading...</p>
                ) : popups.length === 0 ? (
                    <div className="glass-panel" style={{ padding: "3rem", textAlign: "center", color: "var(--text-muted)" }}>
                        No promotional popups found. Create one to engage parents on the homepage!
                    </div>
                ) : (
                    popups.map(popup => (
                        <div key={popup.id} className="glass-panel" style={{ padding: "1.5rem", display: "flex", justifyContent: "space-between", alignItems: "center", borderLeft: popup.isActive ? "4px solid #10b981" : "4px solid transparent" }}>
                            <div>
                                <div style={{ display: "flex", alignItems: "center", gap: "1rem", marginBottom: "0.5rem" }}>
                                    <h3 style={{ fontSize: "1.25rem", margin: 0 }}>{popup.title}</h3>
                                    {popup.isActive && (
                                        <span style={{ fontSize: "0.75rem", padding: "0.2rem 0.5rem", background: "rgba(16, 185, 129, 0.1)", color: "#10b981", borderRadius: "9999px", fontWeight: 700 }}>ACTIVE</span>
                                    )}
                                </div>
                                <p style={{ color: "var(--text-muted)", fontSize: "0.9rem", margin: 0, maxWidth: "600px", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{popup.message}</p>
                            </div>
                            <div style={{ display: "flex", gap: "0.5rem" }}>
                                <button onClick={() => handleEdit(popup)} style={{ padding: "0.5rem 1rem", borderRadius: "8px", border: "1px solid var(--border)", background: "var(--surface)", cursor: "pointer", fontSize: "0.9rem" }}>
                                    Edit
                                </button>
                                <button onClick={() => handleDelete(popup.id)} style={{ padding: "0.5rem 1rem", borderRadius: "8px", border: "1px solid rgba(239, 68, 68, 0.3)", background: "rgba(239, 68, 68, 0.05)", color: "#ef4444", cursor: "pointer", fontSize: "0.9rem" }}>
                                    Delete
                                </button>
                            </div>
                        </div>
                    ))
                )}
            </div>
        </div>
    );
}
