"use client";

import { useEffect, useState } from "react";
import { useSearchParams, useParams } from "next/navigation";
import { useTranslations } from "next-intl";
import Link from "next/link";
import Image from "next/image";
import { authenticatedFetch } from "@/lib/authenticated-fetch";
import BreadcrumbBalmy from "@/components/balmy/breadcrumb-balmy";
import PageWrapper from "@/components/page-wrapper";
import Loading from "@/components/loading";

interface OrderDetails {
    orderId: number;
    incrementId: string;
    customerName: string;
    email: string;
    total: string;
    status: string;
    itemCount: number;
}

/**
 * Order success page — Balmy brand design.
 * Split layout: thank you message on the left, Balmy logo on the right.
 */
export default function OrderSuccessPage() {
    const searchParams = useSearchParams();
    const { locale } = useParams() as { locale: string };
    const t = useTranslations("orderSuccess");

    const orderId = searchParams?.get("orderId") ?? null;
    const incrementId = searchParams?.get("incrementId") ?? null;

    const [orderDetails, setOrderDetails] = useState<OrderDetails | null>(null);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        if (!incrementId) {
            setIsLoading(false);
            return;
        }

        const fetchOrder = async () => {
            try {
                const res = await authenticatedFetch(
                    `/api/customer/orderdetails?incrementId=${incrementId}`
                );
                const data = await res.json();
                if (data.success !== false) {
                    setOrderDetails({
                        orderId: Number(orderId),
                        incrementId: incrementId || "",
                        customerName: `${data.customerDetails?.firstname || ""} ${data.customerDetails?.lastname || ""}`.trim(),
                        email: data.customerDetails?.email || data.email || "",
                        total: data.grandTotal?.formattedValue || data.totalsData?.find((t: any) => t.title === "Grand Total")?.formattedValue || "",
                        status: data.status || "pending",
                        itemCount: data.orderItems?.length || 0,
                    });
                }
            } catch (error) {
                console.error("[OrderSuccess] Failed to fetch order details:", error);
            } finally {
                setIsLoading(false);
            }
        };

        fetchOrder();
    }, [incrementId, orderId]);

    if (isLoading) {
        return <Loading fullScreen variant="spinner" size="xl" />;
    }

    const breadcrumbItems = [
        { label: t("home") || "الرئيسة", href: `/${locale}/home` },
        { label: t("thankYouBreadcrumb") || "شكرا لك" },
    ];

    return (
        <div className="min-h-screen bg-white" dir="rtl">
            <PageWrapper yPadding="py-6">
                {/* Breadcrumb */}
                <BreadcrumbBalmy items={breadcrumbItems} className="mb-6" />

                {/* Main split layout */}
                <div className="flex flex-col lg:flex-row items-center justify-center lg:gap-0 gap-14 py-12 lg:py-20 max-w-5xl mx-auto min-h-[55vh]">

                    {/* Right Side (start in RTL) — Balmy Logo & Tagline */}
                    <div className="flex-1 flex flex-col items-center justify-center lg:px-16 px-6">
                        <Image
                            src="/images/balmy-logo.png"
                            alt="Balmy"
                            width={300}
                            height={300}
                            className="w-48 md:w-60 lg:w-72 h-auto object-contain mb-8"
                            priority
                        />
                        <p className="text-xl md:text-2xl lg:text-[1.6rem] text-black font-cairo font-semibold text-center leading-relaxed">
                            وجهتك الأولى للعطور العالمية الأصلية
                        </p>
                    </div>

                    {/* Vertical Divider — subtle like the design */}
                    <div className="hidden lg:block w-px bg-gray-200 self-stretch my-6" />
                    {/* Horizontal Divider for mobile */}
                    <div className="lg:hidden w-48 h-px bg-gray-200 mx-auto" />

                    {/* Left Side (end in RTL) — Thank You Message */}
                    <div className="flex-1 flex flex-col items-center text-center lg:px-16 px-6">
                        <h1 className="text-4xl md:text-5xl lg:text-[3.2rem] font-bold text-black font-cairo mb-6 leading-tight">
                            !شكـــــرا لك
                        </h1>

                        <p className="text-lg md:text-xl text-gray-600 font-cairo mb-5">
                            نقـــدر وقتـــك واهتمـــامك
                        </p>

                        <p className="text-sm md:text-base text-gray-500 font-cairo mb-3 max-w-md leading-relaxed">
                            .تم استلام طلبك بنجاح، وسيقوم فريقنا بمراجعته والتواصل معك في أقرب وقت ممكن
                        </p>

                        <p className="text-sm text-gray-400 font-cairo mb-8">
                            إذا كان لديك أي استفسار إضافي، لا تتردد في التواصل معنا
                        </p>

                        {/* Action Buttons */}
                        <div className="flex flex-row gap-3">
                            {incrementId && (
                                <Link
                                    href={`/${locale}/user-profile/orders`}
                                    className="inline-flex items-center justify-center px-7 py-3 bg-black hover:bg-gray-800 text-white font-semibold font-cairo transition-colors text-sm"
                                >
                                    تتبع طلبك
                                </Link>
                            )}
                            <Link
                                href={`/${locale}/home`}
                                className="inline-flex items-center justify-center px-7 py-3 bg-white hover:bg-gray-50 text-black font-semibold font-cairo border border-black transition-colors text-sm"
                            >
                                مواصلة التسوق
                            </Link>
                        </div>
                    </div>
                </div>
            </PageWrapper>
        </div>
    );
}
