"use client";

import { useState, useEffect } from "react";

export default function AdminProductsPage() {
    const [products, setProducts] = useState<any[]>([]);
    const [isCreating, setIsCreating] = useState(false);
    const [name, setName] = useState("");
    const [description, setDescription] = useState("");
    const [price, setPrice] = useState("");
    const [imageUrl, setImageUrl] = useState("");
    const [isSubscription, setIsSubscription] = useState(false);
    const [squarePlanId, setSquarePlanId] = useState("");
    const [isActive, setIsActive] = useState(true);

    // Custom Fields Builder
    const [customFields, setCustomFields] = useState<any[]>([]);

    useEffect(() => {
        fetch("/api/admin/products")
            .then(res => res.ok ? res.json() : [])
            .then(data => setProducts(Array.isArray(data) ? data : []))
            .catch(() => setProducts([]));
    }, []);

    const handleCreate = async (e: React.FormEvent) => {
        e.preventDefault();
        const res = await fetch("/api/admin/products", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                name,
                description,
                price: parseFloat(price),
                imageUrl,
                isSubscription,
                squarePlanId: isSubscription ? squarePlanId : null,
                customFields
            })
        });
        if (res.ok) {
            const newProduct = await res.json();
            setProducts([newProduct, ...products]);
            setIsCreating(false);
            setName(""); setDescription(""); setPrice(""); setImageUrl(""); setIsSubscription(false); setSquarePlanId(""); setIsActive(true); setCustomFields([]);
        }
    };

    const addCustomField = () => {
        setCustomFields([...customFields, { name: "", type: "TEXT", options: "", required: true }]);
    };

    const updateCustomField = (index: number, key: string, value: any) => {
        const updated = [...customFields];
        updated[index][key] = value;
        setCustomFields(updated);
    };

    const removeCustomField = (index: number) => {
        setCustomFields(customFields.filter((_, i) => i !== index));
    };

    const handleToggleActive = async (id: string, currentStatus: boolean) => {
        const res = await fetch(`/api/admin/products/${id}`, {
            method: "PATCH",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ isActive: !currentStatus })
        });
        if (res.ok) {
            setProducts(products.map(p => p.id === id ? { ...p, isActive: !currentStatus } : p));
        }
    };

    const handleDelete = async (id: string) => {
        if (!confirm("Are you sure you want to delete this product?")) return;
        const res = await fetch(`/api/admin/products/${id}`, { method: "DELETE" });
        if (res.ok) setProducts(products.filter(p => p.id !== id));
    };

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

    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 className="animate-fade-in" style={{ fontSize: "2.5rem" }}>Manage Products</h1>
                {!isCreating && (
                    <button onClick={() => setIsCreating(true)} className="btn-primary" style={{ padding: "0.5rem 1rem", fontSize: "0.9rem" }}>+ New Product</button>
                )}
            </div>

            {isCreating && (
                <div className="glass-panel animate-fade-in" style={{ padding: "2rem", marginBottom: "3rem" }}>
                    <h2 style={{ fontSize: "1.5rem", marginBottom: "1.5rem" }}>Create New Product</h2>
                    <form onSubmit={handleCreate} style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
                        <div>
                            <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: 500 }}>Name *</label>
                            <input required type="text" style={inputStyle} value={name} onChange={e => setName(e.target.value)} />
                        </div>
                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1.5rem" }}>
                            <div>
                                <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: 500 }}>Price ($) *</label>
                                <input required type="number" step="0.01" style={inputStyle} value={price} onChange={e => setPrice(e.target.value)} />
                            </div>
                            <div>
                                <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: 500 }}>Image URL</label>
                                <input type="url" style={inputStyle} value={imageUrl} onChange={e => setImageUrl(e.target.value)} />
                            </div>
                        </div>
                        <div>
                            <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: 500 }}>Description</label>
                            <textarea rows={3} style={inputStyle} value={description} onChange={e => setDescription(e.target.value)}></textarea>
                        </div>

                        <div style={{ padding: "1.5rem", background: "rgba(16, 185, 129, 0.05)", border: "1px solid rgba(16, 185, 129, 0.2)", borderRadius: "12px", marginTop: "1rem" }}>
                            <div style={{ display: "flex", alignItems: "center", gap: "1rem", marginBottom: isSubscription ? "1rem" : 0 }}>
                                <input type="checkbox" id="isSub" checked={isSubscription} onChange={e => setIsSubscription(e.target.checked)} style={{ width: "20px", height: "20px", accentColor: "#10b981" }} />
                                <label htmlFor="isSub" style={{ fontWeight: 600, fontSize: "1.1rem", cursor: "pointer" }}>Is this a Recurring Subscription? (e.g. PTO Membership)</label>
                            </div>
                            {isSubscription && (
                                <div className="animate-fade-in">
                                    <label style={{ display: "block", marginBottom: "0.5rem", color: "var(--text-muted)", fontSize: "0.95rem" }}>Square Catalog Plan ID *</label>
                                    <input required={isSubscription} type="text" style={{ ...inputStyle, borderColor: "#10b981", background: "transparent" }} placeholder="e.g. WX7..." value={squarePlanId} onChange={e => setSquarePlanId(e.target.value)} />
                                    <p style={{ fontSize: "0.85rem", color: "var(--text-muted)", marginTop: "0.5rem" }}>You must create a Subscription Plan in your Square Dashboard first, then paste the Plan ID here. When parents purchase this product, they will be auto-enrolled in that specific plan.</p>
                                </div>
                            )}
                        </div>

                        {/* Custom Fields Builder */}
                        <div style={{ padding: "1.5rem", border: "1px solid var(--border)", borderRadius: "12px", background: "rgba(0,0,0,0.02)" }}>
                            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "1rem" }}>
                                <h3 style={{ fontSize: "1.2rem", margin: 0 }}>Custom Information Fields</h3>
                                <button type="button" onClick={addCustomField} className="btn-primary" style={{ padding: "0.4rem 0.8rem", fontSize: "0.85rem" }}>+ Add Field</button>
                            </div>
                            <p style={{ fontSize: "0.9rem", color: "var(--text-muted)", marginBottom: "1.5rem" }}>Require parents to provide specific info (e.g. Student Name, T-Shirt Size) when buying this product.</p>

                            {customFields.length === 0 ? (
                                <div style={{ textAlign: "center", color: "var(--text-muted)", fontSize: "0.9rem", padding: "1rem" }}>No custom fields added.</div>
                            ) : (
                                <div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
                                    {customFields.map((cf, index) => (
                                        <div key={index} style={{ display: "grid", gridTemplateColumns: "1fr 1fr 2fr auto", gap: "1rem", alignItems: "end", background: "var(--background)", padding: "1rem", borderRadius: "8px", border: "1px solid var(--border)" }}>
                                            <div>
                                                <label style={{ fontSize: "0.8rem", fontWeight: 600, display: "block", marginBottom: "0.25rem" }}>Field Name</label>
                                                <input type="text" placeholder="e.g. Student Name" style={{ ...inputStyle, padding: "0.5rem" }} value={cf.name} onChange={e => updateCustomField(index, "name", e.target.value)} required />
                                            </div>
                                            <div>
                                                <label style={{ fontSize: "0.8rem", fontWeight: 600, display: "block", marginBottom: "0.25rem" }}>Input Type</label>
                                                <select style={{ ...inputStyle, padding: "0.5rem" }} value={cf.type} onChange={e => updateCustomField(index, "type", e.target.value)}>
                                                    <option value="TEXT">Text Answer</option>
                                                    <option value="SELECT">Dropdown Options</option>
                                                </select>
                                            </div>
                                            <div>
                                                {cf.type === "SELECT" && (
                                                    <div>
                                                        <label style={{ fontSize: "0.8rem", fontWeight: 600, display: "block", marginBottom: "0.25rem" }}>Options (Comma separated)</label>
                                                        <input type="text" placeholder="e.g. S, M, L, XL" style={{ ...inputStyle, padding: "0.5rem" }} value={cf.options} onChange={e => updateCustomField(index, "options", e.target.value)} required={cf.type === "SELECT"} />
                                                    </div>
                                                )}
                                            </div>
                                            <button type="button" onClick={() => removeCustomField(index)} style={{ padding: "0.5rem", background: "rgba(239, 68, 68, 0.1)", color: "#ef4444", border: "none", borderRadius: "8px", cursor: "pointer", height: "36px" }}>X</button>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>

                        <div style={{ display: "flex", gap: "1rem", justifyContent: "flex-end", marginTop: "1rem" }}>
                            <button type="button" onClick={() => setIsCreating(false)} style={{ padding: "0.75rem 1.5rem", borderRadius: "8px", background: "transparent", border: "1px solid var(--border)", color: "var(--text)", cursor: "pointer", fontWeight: 600 }}>Cancel</button>
                            <button type="submit" className="btn-primary" style={{ padding: "0.75rem 1.5rem" }}>Create Product</button>
                        </div>
                    </form>
                </div>
            )}

            <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "1.5rem" }}>
                {!Array.isArray(products) || products.length === 0 ? (
                    <div style={{ textAlign: "center", padding: "4rem", color: "var(--text-muted)", border: "1px dashed var(--border)", borderRadius: "12px" }}>
                        No products created yet.
                    </div>
                ) : products.map(product => (
                    <div key={product.id} className="glass-panel" style={{ padding: "1.5rem", display: "flex", gap: "2rem", alignItems: "center" }}>
                        <div style={{ fontSize: "2.5rem", background: product.isSubscription ? "rgba(16, 185, 129, 0.1)" : "rgba(29,78,216,0.05)", padding: "1rem", borderRadius: "12px" }}>
                            {product.isSubscription ? "🔁" : "👕"}
                        </div>
                        <div style={{ flex: 1 }}>
                            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "start" }}>
                                <div>
                                    <div style={{ display: "flex", alignItems: "center", gap: "1rem", marginBottom: "0.5rem" }}>
                                        <h3 style={{ fontSize: "1.25rem", fontWeight: 700, margin: 0 }}>{product.name}</h3>
                                        {product.isSubscription && <span style={{ fontSize: "0.75rem", background: "rgba(16, 185, 129, 0.1)", color: "#10b981", padding: "0.2rem 0.5rem", borderRadius: "99px", fontWeight: 700 }}>SUBSCRIPTION</span>}
                                    </div>
                                    <div style={{ color: "var(--text-muted)", fontSize: "0.9rem", marginBottom: "0.5rem" }}>${product.price.toFixed(2)}</div>
                                    {product.isSubscription && (
                                        <div style={{ fontSize: "0.85rem", color: "var(--text-muted)", marginBottom: "0.5rem" }}>Plan ID: <code style={{ background: "rgba(0,0,0,0.1)", padding: "0.1rem 0.3rem", borderRadius: "4px" }}>{product.squarePlanId}</code></div>
                                    )}
                                </div>
                                <div style={{ display: "flex", gap: "0.5rem" }}>
                                    <button onClick={() => handleToggleActive(product.id, product.isActive)} style={{ background: product.isActive ? "rgba(16, 185, 129, 0.1)" : "rgba(107, 114, 128, 0.1)", color: product.isActive ? "#10b981" : "#6b7280", border: "none", padding: "0.4rem 0.8rem", borderRadius: "6px", cursor: "pointer", fontSize: "0.85rem", fontWeight: 600 }}>
                                        {product.isActive ? "Active" : "Hidden"}
                                    </button>
                                    <button onClick={() => handleDelete(product.id)} style={{ background: "rgba(239, 68, 68, 0.1)", color: "#ef4444", border: "none", padding: "0.4rem 0.8rem", borderRadius: "6px", cursor: "pointer", fontSize: "0.85rem", fontWeight: 600 }}>Delete</button>
                                </div>
                            </div>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}
