"use client";

import { useEffect, useState } from "react";

export default function AdminPurchasesPage() {
    const [orders, setOrders] = useState<any[]>([]);
    const [products, setProducts] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);

    // Filters
    const [dateFilter, setDateFilter] = useState("all");
    const [statusFilter, setStatusFilter] = useState("all");
    const [productFilter, setProductFilter] = useState("all");
    const [searchQuery, setSearchQuery] = useState("");

    useEffect(() => {
        Promise.all([
            fetch("/api/admin/purchases").then(res => res.ok ? res.json() : []),
            fetch("/api/admin/products").then(res => res.ok ? res.json() : [])
        ])
            .then(([ordersData, productsData]) => {
                setOrders(Array.isArray(ordersData) ? ordersData : []);
                setProducts(Array.isArray(productsData) ? productsData : []);
                setLoading(false);
            })
            .catch(() => {
                setOrders([]);
                setLoading(false);
            });
    }, []);

    const filteredOrders = Array.isArray(orders) ? orders.filter(order => {
        if (statusFilter !== "all" && order.status !== statusFilter) return false;

        if (productFilter !== "all") {
            const hasProduct = order.items.some((item: any) => item.productId === productFilter);
            if (!hasProduct) return false;
        }

        if (dateFilter !== "all") {
            const orderDate = new Date(order.createdAt);
            const now = new Date();
            const daysDiff = (now.getTime() - orderDate.getTime()) / (1000 * 3600 * 24);

            if (dateFilter === "7days" && daysDiff > 7) return false;
            if (dateFilter === "30days" && daysDiff > 30) return false;
            if (dateFilter === "thisYear" && orderDate.getFullYear() !== now.getFullYear()) return false;
        }

        if (searchQuery.trim()) {
            const query = searchQuery.toLowerCase();
            const matchesName = order.customerName.toLowerCase().includes(query);
            const matchesEmail = order.customerEmail.toLowerCase().includes(query);
            const matchesId = order.id.toLowerCase().includes(query);

            const matchesItems = order.items.some((item: any) => {
                const pName = (item.product?.name || "").toLowerCase();
                const jsonStr = (item.customData || "").toLowerCase();
                return pName.includes(query) || jsonStr.includes(query);
            });

            if (!matchesName && !matchesEmail && !matchesId && !matchesItems) return false;
        }

        return true;
    }) : [];

    const exportCSV = () => {
        // Build CSV Header
        const headers = ["Order ID", "Date", "Customer Name", "Customer Email", "Total Amount", "Status", "Square Order ID", "Item Names", "Item Details"];

        const rows = filteredOrders.map(order => {
            const date = new Date(order.createdAt).toISOString().split('T')[0];
            const itemNames = order.items.map((i: any) => `${i.quantity}x ${i.product?.name || 'Unknown'}`).join(" | ");

            // Extract custom data
            const customDetails = order.items.map((i: any) => {
                if (!i.customData) return "";
                try {
                    const data = JSON.parse(i.customData);
                    return Object.entries(data).map(([k, v]) => `${k}: ${v}`).join(", ");
                } catch (e) {
                    return "";
                }
            }).filter(Boolean).join(" | ");

            return [
                order.id, date, order.customerName, order.customerEmail,
                order.totalAmount.toFixed(2), order.status, order.squareOrderId || "N/A",
                `"${itemNames}"`, `"${customDetails}"`
            ].join(",");
        });

        const csvContent = [headers.join(","), ...rows].join("\n");
        const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.setAttribute("href", url);
        link.setAttribute("download", `sfmspto_purchases_${new Date().toISOString().split('T')[0]}.csv`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    const selectStyle = { padding: "0.5rem", borderRadius: "8px", border: "1px solid var(--border)", background: "var(--surface)", color: "var(--foreground)", fontSize: "0.9rem", minWidth: "150px" };
    const inputStyle = { padding: "0.5rem 1rem", borderRadius: "8px", border: "1px solid var(--primary)", background: "var(--surface)", color: "var(--foreground)", fontSize: "0.95rem", minWidth: "250px" };

    if (loading) {
        return <div className="container" style={{ padding: "4rem 1.5rem", textAlign: "center" }}>Loading orders...</div>;
    }

    return (
        <div className="container" style={{ padding: "4rem 1.5rem" }}>
            <a href="/admin" style={{ color: "var(--primary)", display: "inline-block", marginBottom: "2rem", fontWeight: 600 }}>&larr; Back to Dashboard</a>

            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: "2rem", flexWrap: "wrap", gap: "1.5rem" }}>
                <h1 className="animate-fade-in" style={{ fontSize: "2.5rem", margin: 0 }}>Recent Purchases</h1>

                <div style={{ display: "flex", gap: "1rem", alignItems: "center", flexWrap: "wrap" }}>
                    <div style={{ display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                        <label style={{ fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600 }}>Search Purchases</label>
                        <input type="text" placeholder="Name, item, custom data..." value={searchQuery} onChange={e => setSearchQuery(e.target.value)} style={inputStyle} />
                    </div>
                    <div style={{ display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                        <label style={{ fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600 }}>Filter by Date</label>
                        <select style={selectStyle} value={dateFilter} onChange={e => setDateFilter(e.target.value)}>
                            <option value="all">All Time</option>
                            <option value="7days">Last 7 Days</option>
                            <option value="30days">Last 30 Days</option>
                            <option value="thisYear">This Year</option>
                        </select>
                    </div>

                    <div style={{ display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                        <label style={{ fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600 }}>Filter by Product</label>
                        <select style={selectStyle} value={productFilter} onChange={e => setProductFilter(e.target.value)}>
                            <option value="all">All Products</option>
                            {products.map(p => (
                                <option key={p.id} value={p.id}>{p.name}</option>
                            ))}
                        </select>
                    </div>

                    <div style={{ display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                        <label style={{ fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600 }}>Filter by Status</label>
                        <select style={selectStyle} value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
                            <option value="all">All Statuses</option>
                            <option value="PAID">PAID</option>
                            <option value="PENDING">PENDING</option>
                            <option value="FULFILLED">FULFILLED</option>
                        </select>
                    </div>

                    <button onClick={exportCSV} className="btn-primary" style={{ height: "40px", marginTop: "1.25rem", display: "flex", alignItems: "center", gap: "0.5rem" }}>
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
                        Export CSV
                    </button>
                </div>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
                {filteredOrders.map(order => (
                    <div key={order.id} className="glass-panel" style={{ padding: "2rem" }}>
                        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "1.5rem", borderBottom: "1px solid var(--border)", paddingBottom: "1rem" }}>
                            <div>
                                <h3 style={{ fontSize: "1.2rem", fontWeight: 700 }}>Order #{order.id.slice(-6).toUpperCase()}</h3>
                                <div style={{ color: "var(--text-muted)", fontSize: "0.9rem" }}>{new Date(order.createdAt).toLocaleString()}</div>
                            </div>
                            <div style={{ textAlign: "right" }}>
                                <div style={{ fontSize: "1.2rem", fontWeight: 700, color: "var(--primary)" }}>${order.totalAmount.toFixed(2)}</div>
                                <div style={{ display: "inline-block", padding: "0.2rem 0.6rem", background: order.status === "PAID" ? "rgba(16, 185, 129, 0.1)" : "rgba(245, 158, 11, 0.1)", color: order.status === "PAID" ? "#10b981" : "#f59e0b", borderRadius: "9999px", fontSize: "0.8rem", fontWeight: 700, marginTop: "0.5rem" }}>
                                    {order.status}
                                </div>
                            </div>
                        </div>

                        <div style={{ marginBottom: "1.5rem" }}>
                            <strong style={{ display: "block", marginBottom: "0.25rem" }}>Customer</strong>
                            <div style={{ color: "var(--text-muted)" }}>{order.customerName} ({order.customerEmail})</div>
                        </div>

                        <div>
                            <strong style={{ display: "block", marginBottom: "0.5rem" }}>Items</strong>
                            <div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
                                {order.items.map((item: any) => (
                                    <div key={item.id} style={{ background: "var(--surface)", padding: "1rem", borderRadius: "8px", border: "1px solid var(--border)" }}>
                                        <div style={{ display: "flex", justifyContent: "space-between", fontWeight: 600 }}>
                                            <span>{item.quantity}x {item.product?.name || 'Unknown Product'}</span>
                                            <span>${(item.price * item.quantity).toFixed(2)}</span>
                                        </div>
                                        {item.customData && (
                                            <div style={{ fontSize: "0.85rem", color: "var(--text-muted)", marginTop: "0.5rem" }}>
                                                {Object.entries(JSON.parse(item.customData)).map(([k, v]) => (
                                                    <div key={k}><span style={{ opacity: 0.7 }}>{k}:</span> {v as string}</div>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                ))}

                {filteredOrders.length === 0 && (
                    <div style={{ padding: "3rem", textAlign: "center", color: "var(--text-muted)", border: "1px dashed var(--border)", borderRadius: "16px" }}>
                        No purchases match your filters.
                    </div>
                )}
            </div>
        </div>
    );
}
