"use client";

import React from "react";
import { OrderStatus, OrderStatusStep } from "@/types/tracking.types";
import {
    ClipboardCheck,
    PackageCheck,
    Truck,
    MapPin,
    Home,
} from "lucide-react";

export type TrackingStep = {
    label: string;
    date: string;
    status: "completed" | "pending";
    icon: React.ReactNode;
};

interface TrackingTimelineProps {
    steps?: TrackingStep[];
    statusHistory?: OrderStatusStep[];
    className?: string;
}

/** Map OrderStatus → Lucide icon */
const statusIconMap: Record<OrderStatus, React.ReactNode> = {
    received: <ClipboardCheck className="w-5 h-5" />,
    processing: <PackageCheck className="w-5 h-5" />,
    shipped: <Truck className="w-5 h-5" />,
    in_transit: <MapPin className="w-5 h-5" />,
    delivered: <Home className="w-5 h-5" />,
};

/** Get icon by status or label text (handles Markatty-specific labels) */
function getIconForStep(status: string, label: string): React.ReactNode {
    // Try exact status match first
    if (statusIconMap[status as OrderStatus]) {
        return statusIconMap[status as OrderStatus];
    }
    // Match by Arabic label keywords
    const lower = label.toLowerCase();
    if (lower.includes("إنشاء الطلب") || lower.includes("استلام")) {
        return <ClipboardCheck className="w-5 h-5" />;
    }
    if (lower.includes("فاتورة") || lower.includes("تجهيز")) {
        return <PackageCheck className="w-5 h-5" />;
    }
    if (lower.includes("شحن") || lower.includes("shipped")) {
        return <Truck className="w-5 h-5" />;
    }
    if (lower.includes("طريق") || lower.includes("transit")) {
        return <MapPin className="w-5 h-5" />;
    }
    if (lower.includes("تسليم") || lower.includes("deliver")) {
        return <Home className="w-5 h-5" />;
    }
    // Default fallback
    return <ClipboardCheck className="w-5 h-5" />;
}

const fallbackSteps: TrackingStep[] = [
    {
        label: "تم التسليـــم",
        date: "MAY 30.2026",
        status: "pending",
        icon: <Home className="w-5 h-5" />,
    },
    {
        label: "في الطـــريق",
        date: "MAY 30.2026",
        status: "pending",
        icon: <MapPin className="w-5 h-5" />,
    },
    {
        label: "تم الشحـــن",
        date: "MAY 30.2026",
        status: "completed",
        icon: <Truck className="w-5 h-5" />,
    },
    {
        label: "قيد التجهيـــز",
        date: "MAY 30.2026",
        status: "completed",
        icon: <PackageCheck className="w-5 h-5" />,
    },
    {
        label: "تم استلام الطلب",
        date: "MAY 30.2026",
        status: "completed",
        icon: <ClipboardCheck className="w-5 h-5" />,
    },
];

function mapStatusHistoryToSteps(statusHistory: OrderStatusStep[]): TrackingStep[] {
    return statusHistory.map((step) => ({
        label: step.label,
        date: step.timestamp ?? "",
        status: step.completed ? "completed" : "pending",
        icon: getIconForStep(step.status, step.label),
    }));
}

/**
 * Order tracking stepper — horizontal timeline with Lucide icons.
 * Green completed steps, gray pending steps, animated progress bar.
 */
export default function TrackingTimeline({ steps, statusHistory, className }: TrackingTimelineProps) {
    const normalizedSteps =
        steps && steps.length > 0
            ? steps
            : statusHistory && statusHistory.length > 0
                ? mapStatusHistoryToSteps(statusHistory)
                : fallbackSteps;

    // Calculate progress percentage based on completed steps
    const completedCount = normalizedSteps.filter(s => s.status === "completed").length;
    const totalSteps = normalizedSteps.length;
    const progressPercentage = totalSteps > 1 ? ((completedCount) / totalSteps) * 100 : 0;

    return (
        <div className={`w-full py-4 sm:py-6 md:py-8 mb-4 sm:mb-6 md:mb-8 ${className ?? ""}`}>
            <div className="px-2 sm:px-4">
                <div className="relative flex items-start justify-between min-w-[500px] sm:min-w-0">
                    {/* Background connecting line */}
                    <div
                        className="absolute h-1 sm:h-[6px] bg-gray-300 rounded-full"
                        style={{
                            left: 'calc(10% + 16px)',
                            right: 'calc(10% + 16px)',
                            transform: 'translateY(-50%)',
                            top: '20px'
                        }}
                    />

                    {/* Progress overlay — green line */}
                    <div
                        className="absolute h-1 sm:h-[6px] bg-[#2E8B57] rounded-full transition-all duration-700 ease-in-out"
                        style={{
                            right: 'calc(10% + 16px)',
                            width: `calc((80% - 32px) * ${progressPercentage / 100})`,
                            transform: 'translateY(-50%)',
                            top: '20px'
                        }}
                    />

                    {/* Steps */}
                    {normalizedSteps.map((step, index) => {
                        const isCompleted = step.status === "completed";

                        return (
                            <div
                                key={`${step.label}-${index}`}
                                className="relative flex flex-1 flex-col items-center z-10"
                            >
                                {/* Step Icon Container */}
                                <div
                                    className={`
                                        relative flex h-10 w-10 sm:h-12 sm:w-12 items-center justify-center rounded-xl sm:rounded-2xl
                                        transition-all duration-500 ease-in-out
                                        ${isCompleted
                                            ? "bg-[#2E8B57] shadow-md"
                                            : "bg-gray-100 border-2 border-gray-300"
                                        }
                                    `}
                                >
                                    <span
                                        className={`
                                            transition-colors duration-300
                                            ${isCompleted ? "text-white" : "text-gray-400"}
                                        `}
                                    >
                                        {step.icon}
                                    </span>

                                    {/* Pulse animation for the current active step */}
                                    {index > 0 &&
                                        normalizedSteps[index - 1]?.status === "completed" &&
                                        step.status === "pending" && (
                                            <div className="absolute inset-0 rounded-xl sm:rounded-2xl border-2 border-[#2E8B57] animate-ping opacity-30" />
                                        )}
                                </div>

                                {/* Step Label */}
                                <p
                                    className={`
                                        mt-2 sm:mt-4 text-[10px] sm:text-xs md:text-sm font-medium text-center whitespace-nowrap
                                        transition-colors duration-300
                                        ${isCompleted ? "text-gray-800" : "text-gray-400"}
                                    `}
                                >
                                    {step.label}
                                </p>

                                {/* Step Date */}
                                <p
                                    className={`
                                        mt-0.5 sm:mt-1 text-[8px] sm:text-[10px] md:text-xs font-medium
                                        transition-colors duration-300
                                        ${isCompleted ? "text-gray-600" : "text-gray-400"}
                                    `}
                                >
                                    {step.date}
                                </p>
                            </div>
                        );
                    })}
                </div>
            </div>
        </div>
    );
}

export function TrackingTimelineExample() {
    return <TrackingTimeline steps={fallbackSteps} />;
}
