"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import { authenticatedFetch } from "@/lib/authenticated-fetch";
import { useTranslations } from "next-intl";
import {
    CalendarDays,
    Package,
    Eye,
    AlertCircle,
    Clock,
    ShoppingBag,
    RotateCcw,
} from "lucide-react";

interface OrderItem {
    id: number;
    incrementId: string | number;
    status: string;
    date: string;
    total: string;
    itemCount: number;
}

const PENDING_STATUSES = ["pending", "processing", "pending_payment", "holded"];

export default function PendingOrdersPage() {
    const { locale } = useParams() as { locale: string };
    const t = useTranslations("profile");
    const [orders, setOrders] = useState<OrderItem[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        const fetchOrders = async () => {
            try {
                const res = await authenticatedFetch("/api/customer/orderlist");
                const data = await res.json();

                let allOrders: OrderItem[] = [];

                if (data.orderList && Array.isArray(data.orderList)) {
                    allOrders = data.orderList.map((order: any) => ({
                        id: order.id,
                        incrementId: order.order_id || order.increment_id || order.id,
                        status: order.status || order.state || "pending",
                        date: order.date || order.created_at || "",
                        total: order.grand_total_formatted || order.order_total_formatted || `${order.order_total || order.grand_total || 0} SAR`,
                        itemCount: order.item_count || order.total_item_count || 0,
                    }));
                } else if (Array.isArray(data)) {
                    allOrders = data.map((order: any) => ({
                        id: order.id,
                        incrementId: order.increment_id || order.incrementId || order.id,
                        status: order.status || "pending",
                        date: order.created_at || order.date || "",
                        total: order.grand_total_formatted || order.order_total_formatted || `${order.grand_total || order.order_total || 0} SAR`,
                        itemCount: order.total_item_count || 0,
                    }));
                }

                // Filter to only pending/processing orders
                setOrders(allOrders.filter((o) => PENDING_STATUSES.includes(o.status.toLowerCase())));
            } catch (err) {
                console.error("[PendingOrdersPage] Failed to fetch orders:", err);
                setError(t("orders-load-error"));
            } finally {
                setIsLoading(false);
            }
        };

        fetchOrders();
    }, [t]);

    const formatDate = (dateStr: string) => {
        if (!dateStr) return "";
        try {
            return new Date(dateStr).toLocaleDateString(locale === "ar" ? "ar-EG" : "en-US", {
                year: "numeric",
                month: "long",
                day: "numeric",
            });
        } catch {
            return dateStr;
        }
    };

    return (
        <div className="bg-white dark:bg-surface-dark rounded-xl border border-gray-100 dark:border-gray-700 min-h-[400px]">
            {/* Header */}
            <div className="px-6 py-5 border-b border-gray-100 dark:border-gray-700">
                <div className="flex items-center justify-between">
                    <h2 className="text-xl font-bold font-cairo dark:text-white">
                        {t("pending-orders")}
                    </h2>
                    {orders.length > 0 && (
                        <span className="text-xs font-medium text-gray-400 font-cairo">
                            {t("orders-count", { count: orders.length })}
                        </span>
                    )}
                </div>
            </div>

            <div className="p-6">
                {isLoading ? (
                    <div className="space-y-4">
                        {[1, 2, 3].map((i) => (
                            <div key={i} className="animate-pulse">
                                <div className="flex items-center justify-between p-5 rounded-xl border border-gray-100">
                                    <div className="space-y-3 flex-1">
                                        <div className="flex items-center gap-3">
                                            <div className="h-4 w-20 bg-gray-200 rounded" />
                                            <div className="h-5 w-24 bg-gray-100 rounded-full" />
                                        </div>
                                        <div className="flex gap-4">
                                            <div className="h-3 w-28 bg-gray-100 rounded" />
                                            <div className="h-3 w-16 bg-gray-100 rounded" />
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-4">
                                        <div className="h-5 w-24 bg-gray-200 rounded" />
                                        <div className="h-9 w-20 bg-gray-100 rounded-lg" />
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                ) : error ? (
                    <div className="flex flex-col items-center justify-center py-16 gap-4">
                        <div className="w-14 h-14 rounded-full bg-red-50 flex items-center justify-center">
                            <AlertCircle className="w-7 h-7 text-red-400" />
                        </div>
                        <p className="text-gray-600 dark:text-gray-400 font-cairo">{error}</p>
                        <button
                            onClick={() => window.location.reload()}
                            className="inline-flex items-center gap-2 px-5 py-2 text-sm font-medium text-black border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors font-cairo"
                        >
                            <RotateCcw className="w-3.5 h-3.5" />
                            {t("retry")}
                        </button>
                    </div>
                ) : orders.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-16 gap-5">
                        <div className="w-20 h-20 rounded-full bg-amber-50 flex items-center justify-center">
                            <Clock className="w-10 h-10 text-amber-300" strokeWidth={1} />
                        </div>
                        <div className="text-center">
                            <p className="text-gray-800 dark:text-gray-200 font-semibold font-cairo text-lg mb-1">
                                {t("no-pending-orders") || t("orders-empty-title")}
                            </p>
                            <p className="text-gray-400 text-sm font-cairo">
                                {t("no-pending-orders-subtitle") || t("orders-empty-subtitle")}
                            </p>
                        </div>
                        <Link
                            href={`/${locale}/home`}
                            className="mt-2 inline-flex items-center gap-2 px-6 py-2.5 bg-black text-white text-sm font-semibold font-cairo rounded-lg hover:bg-gray-800 transition-colors"
                        >
                            <ShoppingBag className="w-4 h-4" />
                            {t("shop-now")}
                        </Link>
                    </div>
                ) : (
                    <div className="space-y-3">
                        {orders.map((order) => (
                            <div
                                key={order.id}
                                className="group relative rounded-xl border border-amber-100 dark:border-gray-700 p-5 hover:border-amber-200 hover:shadow-sm transition-all duration-200 bg-amber-50/30"
                            >
                                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-3 mb-2.5">
                                            <span className="text-sm font-bold text-gray-900 dark:text-white font-cairo">
                                                {t("order-number", { id: order.incrementId })}
                                            </span>
                                            <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-amber-50 text-amber-700">
                                                <span className="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse" />
                                                {t(`status-${order.status.toLowerCase()}`) || order.status}
                                            </span>
                                        </div>
                                        <div className="flex items-center gap-4 text-xs text-gray-400 dark:text-gray-500 font-cairo">
                                            <span className="inline-flex items-center gap-1.5">
                                                <CalendarDays className="w-3.5 h-3.5" />
                                                {formatDate(order.date)}
                                            </span>
                                            {order.itemCount > 0 && (
                                                <span className="inline-flex items-center gap-1.5">
                                                    <Package className="w-3.5 h-3.5" />
                                                    {t("items-count", { count: order.itemCount })}
                                                </span>
                                            )}
                                        </div>
                                    </div>

                                    <div className="flex items-center gap-5">
                                        <div className="text-left">
                                            <p className="text-xs text-gray-400 font-cairo mb-0.5">
                                                {t("total")}
                                            </p>
                                            <p
                                                className="text-base font-bold text-gray-900 dark:text-white font-cairo"
                                                dangerouslySetInnerHTML={{ __html: String(order.total) }}
                                            />
                                        </div>
                                        <Link
                                            href={`/${locale}/track-order?id=${order.id}&incrementId=${order.incrementId}`}
                                            className="inline-flex items-center gap-2 px-5 py-2.5 text-sm font-semibold bg-black text-white rounded-lg hover:bg-gray-800 transition-all duration-200 font-cairo"
                                        >
                                            <Eye className="w-4 h-4" />
                                            {t("track-order")}
                                        </Link>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}
