"use client";

import { useCart } from "@/components/CartContext";
import { useState } from "react";
import { PaymentForm, CreditCard } from "react-square-web-payments-sdk";
import { useRouter } from "next/navigation";

export default function CheckoutPage() {
    const { items, total, clearCart } = useCart();
    const [customerName, setCustomerName] = useState("");
    const [customerEmail, setCustomerEmail] = useState("");
    const [status, setStatus] = useState<"idle" | "loading" | "success" | "error">("idle");
    const [errorMessage, setErrorMessage] = useState("");
    const [completedOrder, setCompletedOrder] = useState<{ id: string; items: typeof items; total: number } | null>(null);
    const router = useRouter();

    if (items.length === 0 && status !== "success") {
        return (
            <div className="container" style={{ padding: "4rem 1.5rem", textAlign: "center", maxWidth: "600px" }}>
                <h1 style={{ fontSize: "2.5rem", marginBottom: "1rem" }}>Your Cart is Empty</h1>
                <p style={{ color: "var(--text-muted)", marginBottom: "2rem" }}>Looks like you haven't added any swag to your cart yet.</p>
                <a href="/shop" className="btn-primary">Browse Shop</a>
            </div>
        );
    }

    if (status === "success" && completedOrder) {
        return (
            <div className="container" style={{ padding: "4rem 1.5rem", maxWidth: "600px" }}>
                <div className="glass-panel animate-fade-in" style={{ padding: "3rem" }}>
                    <div style={{ textAlign: "center", marginBottom: "2rem" }}>
                        <div style={{ fontSize: "4rem", marginBottom: "1rem" }}>🛍</div>
                        <h1 style={{ fontSize: "2rem", marginBottom: "0.5rem", color: "#10b981" }}>Payment Successful!</h1>
                        <p style={{ color: "var(--text-muted)" }}>
                            Thank you, {customerName}. A receipt has been emailed to {customerEmail}.
                        </p>
                    </div>

                    <div style={{ display: "flex", flexDirection: "column", gap: "1rem", marginBottom: "1.5rem" }}>
                        {completedOrder.items.map(item => (
                            <div key={item.id} style={{ display: "flex", justifyContent: "space-between", paddingBottom: "1rem", borderBottom: "1px solid var(--border)" }}>
                                <div>
                                    <div style={{ fontWeight: 600 }}>{item.quantity}x {item.name}</div>
                                    <div style={{ fontSize: "0.85rem", color: "var(--text-muted)", marginTop: "0.25rem" }}>
                                        {Object.entries(item.customData).map(([k, v]) => `${v}`).join(', ')}
                                    </div>
                                </div>
                                <div style={{ fontWeight: 600 }}>${(item.price * item.quantity).toFixed(2)}</div>
                            </div>
                        ))}
                    </div>

                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: "1.25rem", fontWeight: 700, marginBottom: "2rem" }}>
                        <span>Total</span>
                        <span style={{ color: "var(--primary)" }}>${completedOrder.total.toFixed(2)}</span>
                    </div>

                    <div style={{ display: "flex", gap: "1rem", justifyContent: "center", flexWrap: "wrap" }}>
                        <a href={`/order/${completedOrder.id}`} className="btn-primary">View Receipt</a>
                        <a href="/shop" className="btn-primary">Continue Shopping</a>
                    </div>
                </div>
            </div>
        );
    }

    const handlePayment = async (token: string) => {
        setStatus("loading");
        setErrorMessage("");

        try {
            const res = await fetch("/api/checkout", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    sourceId: token,
                    items,
                    totalAmount: total,
                    customerName,
                    customerEmail
                })
            });

            const data = await res.json();
            if (!res.ok) throw new Error(data.error || "Payment failed");

            setCompletedOrder({ id: data.orderId, items, total });
            setStatus("success");
            clearCart();
        } catch (err: any) {
            console.error(err);
            setStatus("error");
            setErrorMessage(err.message);
        }
    };

    const appId = process.env.NEXT_PUBLIC_SQUARE_APP_ID || "sandbox-sq0idb-...";
    const locationId = process.env.NEXT_PUBLIC_SQUARE_LOCATION_ID || "L...";

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

    return (
        <div className="container" style={{ padding: "4rem 1.5rem", maxWidth: "1000px" }}>
            <h1 className="animate-fade-in" style={{ fontSize: "3rem", marginBottom: "2rem" }}>Checkout</h1>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 400px", gap: "3rem", alignItems: "start" }} className="checkout-grid">
                <div className="glass-panel animate-fade-in" style={{ padding: "2rem" }}>
                    <h2 style={{ fontSize: "1.5rem", marginBottom: "1.5rem" }}>Order Summary</h2>
                    <div style={{ display: "flex", flexDirection: "column", gap: "1rem", marginBottom: "2rem" }}>
                        {items.map(item => (
                            <div key={item.id} style={{ display: "flex", justifyContent: "space-between", paddingBottom: "1rem", borderBottom: "1px solid var(--border)" }}>
                                <div>
                                    <div style={{ fontWeight: 600 }}>{item.quantity}x {item.name}</div>
                                    <div style={{ fontSize: "0.85rem", color: "var(--text-muted)", marginTop: "0.25rem" }}>
                                        {Object.entries(item.customData).map(([k, v]) => `${v}`).join(', ')}
                                    </div>
                                </div>
                                <div style={{ fontWeight: 600 }}>${(item.price * item.quantity).toFixed(2)}</div>
                            </div>
                        ))}
                    </div>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: "1.25rem", fontWeight: 700 }}>
                        <span>Total</span>
                        <span style={{ color: "var(--primary)" }}>${total.toFixed(2)}</span>
                    </div>
                </div>

                <div className="glass-panel animate-fade-in" style={{ padding: "2rem", animationDelay: "0.1s" }}>
                    <h2 style={{ fontSize: "1.5rem", marginBottom: "1.5rem" }}>Payment Details</h2>

                    <div style={{ display: "flex", flexDirection: "column", gap: "1rem", marginBottom: "2rem" }}>
                        <div>
                            <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: 500 }}>Full Name</label>
                            <input required type="text" style={inputStyle} value={customerName} onChange={e => setCustomerName(e.target.value)} />
                        </div>
                        <div>
                            <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: 500 }}>Email Address</label>
                            <input required type="email" style={inputStyle} value={customerEmail} onChange={e => setCustomerEmail(e.target.value)} />
                        </div>
                    </div>

                    {errorMessage && (
                        <div style={{ padding: "1rem", background: "rgba(239, 68, 68, 0.1)", color: "#ef4444", borderRadius: "8px", marginBottom: "1.5rem", fontSize: "0.9rem" }}>
                            {errorMessage}
                        </div>
                    )}

                    {customerName && customerEmail ? (
                        <div style={{ position: "relative" }}>
                            {status === "loading" && (
                                <div style={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0, background: "rgba(255,255,255,0.7)", zIndex: 10, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700, borderRadius: "8px" }}>
                                    Processing...
                                </div>
                            )}
                            <PaymentForm
                                applicationId={appId}
                                locationId={locationId}
                                cardTokenizeResponseReceived={async (token) => {
                                    if (token.status === "OK" && token.token) {
                                        await handlePayment(token.token);
                                    } else {
                                        setStatus("error");
                                        setErrorMessage((token as any).errors?.[0]?.message || "Payment invalid");
                                    }
                                }}
                            >
                                <CreditCard />
                            </PaymentForm>
                        </div>
                    ) : (
                        <div style={{ padding: "1.5rem", background: "var(--background)", borderRadius: "8px", textAlign: "center", color: "var(--text-muted)", fontSize: "0.9rem" }}>
                            Please enter your name and email to proceed with payment.
                        </div>
                    )}
                </div>
            </div>

            <style dangerouslySetInnerHTML={{
                __html: `
        @media (max-width: 768px) {
          .checkout-grid { grid-template-columns: 1fr !important; }
        }
      `}} />
        </div>
    );
}
