"use client";

import * as React from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import {
    Breadcrumb,
    BreadcrumbList,
    BreadcrumbItem,
    BreadcrumbSeparator as BcSeparator,
    BreadcrumbLink,
} from "@/components/ui/breadcrumb";
import { cn } from "@/lib/utils";
import { TypographyH3, TypographySmall } from "@/components/ui/typography";
import Image from "next/image";

type OrderStatusType = "ordered" | "shipped" | "delivered";

interface StatusStep {
    id: OrderStatusType;
    label: string;
}

const statusSteps: StatusStep[] = [
    { id: "ordered", label: "تم تأكيد الطلب" },
    { id: "shipped", label: "تم الشحن" },
    // { id: "out-for-delivery", label: "Out For Delivery" },
    { id: "delivered", label: "تم التسليم" },
];

interface OrderStatusProps {
    currentStatus: OrderStatusType;
    orderNumber?: string;
    orderDate?: string;
    estimatedDelivery?: string;
    onExportInvoice?: () => void;
    createdAt?: string;
}

const OrderStatus: React.FC<OrderStatusProps> = ({
    currentStatus = "ordered",
    orderNumber = "N/A",
    orderDate,
    estimatedDelivery,
    onExportInvoice,
    createdAt,
}) => {
    const currentIndex = statusSteps.findIndex(
        (step) => step.id === currentStatus
    );

    // Calculate dates based on createdAt
    const getStepDates = (): [string, string, string] => {
        if (!createdAt) {
            return ["", "", ""];
        }
        
        const created = new Date(createdAt);
        const shipped = new Date(created);
        shipped.setDate(shipped.getDate() + 1); // +1 day for shipping
        
        const delivered = new Date(created);
        delivered.setDate(delivered.getDate() + 5); // +5 days max for delivery
        
        const formatDate = (date: Date) => {
            return date.toLocaleDateString('ar-SA-u-ca-gregory', {
                weekday: 'short',
                month: 'short',
                day: 'numeric',
            });
        };

        return [
            formatDate(created),
            formatDate(shipped),
            formatDate(delivered),
        ];
    };

    const stepDates = getStepDates();

    const getMobileDate = (index: number) => {
        return stepDates[index];
    };

    return (
        <Card className="mb-9 md:mb-12">
            <CardContent className="pt-9 pb-8 sm:py-[33px] px-6 sm:px-[22px]">
                <div className="space-y-3 sm:space-y-8">
                    <Breadcrumb className="flex">
                        <BreadcrumbList>
                            <BreadcrumbItem>
                                <BreadcrumbLink href="#">Home</BreadcrumbLink>
                            </BreadcrumbItem>
                            <BcSeparator />
                            <BreadcrumbItem>
                                <BreadcrumbLink href="#">Orders</BreadcrumbLink>
                            </BreadcrumbItem>
                            <BcSeparator />
                            <BreadcrumbItem>
                                <BreadcrumbLink href="#">ID {orderNumber}</BreadcrumbLink>
                            </BreadcrumbItem>
                        </BreadcrumbList>
                    </Breadcrumb>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:py-[3.35px]">
                        <div className="space-y-2">
                            <TypographyH3 className="text-black text-[20px] sm:text-[22px] md:text-[30px] leading-[38px] font-bold">
                                رقم الطلب: {orderNumber}
                            </TypographyH3>
                            <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 inline-block">
                                <p className="text-xs text-gray-600 mb-1">Reference Number (Ref)</p>
                                <p className="font-mono font-bold text-blue-600 text-lg">{orderNumber}</p>
                            </div>
                        </div>

                        <div className="hidden justify-end md:flex items-center gap-3.5">
                            <Button
                                variant="outline"
                                onClick={onExportInvoice}
                                className="h-10 rounded-lg border-[#D0D5DD] gap-2 inter text-[#667085] hover:text-[#667085] text-sm leading-5 font-semibold flex-row-reverse"
                            >
                                الفاتورة
                                <Image
                                    src="/assets/icons/invoice.svg"
                                    alt="invoice"
                                    width={17}
                                    height={17}
                                />
                            </Button>
                            {/* <Button className="h-10 rounded-lg gap-2 text-white text-sm leading-5 inter font-semibold">
                                تتبع الطلب
                                <Image
                                    src="/assets/icons/location.svg"
                                    alt="location"
                                    width={17}
                                    height={17}
                                />
                            </Button> */}
                        </div>
                    </div>

                    <div className="flex sm:items-center sm:flex-row flex-col gap-3 sm:gap-[17px]">
                        <TypographyH3 className="text-[#667085] text-sm  leading-5 font-normal inter">
                            تاريخ الطلب: <span className="font-semibold inter text-base leading-6 text-[#1D2939]">{orderDate || 'N/A'}</span>
                        </TypographyH3>

                        <div className="sm:block hidden h-5 w-px bg-[#D0D5DD]" />

                        <Badge
                            variant="secondary"
                            className="gap-2.5 p-0 hover:bg-transparent w-fit items-start rounded-full text-[#12B76A] bg-transparent"
                        >
                            <Image
                                src="/assets/icons/truck-tick.svg"
                                alt="truck-tick"
                                width={20}
                                height={20}
                            />
                            <span className="font-semibold text-[16px] leading-6">
                                تاريخ التوصيل المتوقع: {estimatedDelivery || 'TBD'}
                            </span>
                        </Badge>
                    </div>

                    <Separator className="bg-[#D0D5DD] sm:block hidden" />

                    {/* track order */}
                    <div className="relative w-full mt-9 sm:mt-0">
                        <div className="relative mx-auto w-full max-w-full">
                            {/* Horizontal Track + Progress Fill for desktop */}
                            <div className="absolute hidden md:block left-[12.5%] top-1/2 -translate-y-1/2 h-[4.67px] bg-[#D0D5DD] rounded-full w-[75%]" />
                            <div
                                className="absolute hidden md:block left-[12.5%] top-1/2 -translate-y-1/2 h-[4.67px] bg-black rounded-full transition-all duration-500"
                                style={{
                                    width: `${(currentIndex / (statusSteps.length - 1)) * 75}%`,
                                }}
                            />

                            {/* Vertical Track + Progress Fill for mobile */}
                            <div className="absolute md:hidden -top-px left-[8.7px] h-full w-[4.67px] bg-[#D0D5DD] rounded-full" />
                            <div
                                className="absolute md:hidden top-0 left-[8.7px] h-0 w-[4.67px] bg-black rounded-full transition-all duration-500"
                                style={{
                                    height: `${(currentIndex / (statusSteps.length - 1)) * 100}%`,
                                }}
                            />

                            {/* Steps */}
                            <ol
                                className="relative flex flex-col md:grid md:grid-cols-3 gap-[81px] md:gap-0"
                                aria-label="Order progress"
                            >
                                {statusSteps.map((step, index) => {
                                    const isCompleted = index < currentIndex;
                                    const isActive = index === currentIndex;

                                    const dotClass = isActive || isCompleted
                                        ? "bg-black w-[22px] h-[22px]"
                                        : "bg-[#D0D5DD] w-[22px] h-[22px]";

                                    const labelClass =
                                        isActive || isCompleted
                                            ? "text-black font-semibold inter"
                                            : "text-[#7B7B7B] font-medium inter";

                                    const dateClass =
                                        isActive || isCompleted
                                            ? "text-black font-normal"
                                            : "text-[#98A2B3] font-normal";

                                    return (
                                        <li
                                            key={step.id}
                                            className="flex md:flex-col md:items-center"
                                            aria-current={isActive ? "step" : undefined}
                                            role="listitem"
                                        >
                                            {/* Mobile layout: dot + combined label/date */}
                                            <div className="flex items-start gap-4 md:hidden">
                                                <span className={cn("rounded-full shrink-0", dotClass)} />
                                                <div className="flex items-center gap-3">
                                                    <span className={cn("text-base leading-6", labelClass)}>
                                                        {step.label}
                                                    </span>
                                                    <span className={cn("text-[16px] leading-6", dateClass)}>
                                                        {getMobileDate(index)}
                                                    </span>
                                                </div>
                                            </div>

                                            {/* Desktop layout: label + dot + date */}
                                            <div className="hidden md:flex md:flex-col md:items-center md:gap-3">
                                                {/* Label */}
                                                <span className={cn("mb-3 text-[14px] md:text-[16px] lg:text-[18px] leading-5 md:leading-6 lg:leading-7 font-medium text-center", labelClass)}>
                                                    {step.label}
                                                </span>

                                                {/* Dots */}
                                                <div className="relative w-full h-8 flex items-center justify-center">
                                                    <span className={cn("rounded-full", dotClass)} />
                                                </div>

                                                {/* Date */}
                                                <TypographySmall className={cn("mt-3 text-[12px] md:text-[14px] lg:text-[16px] leading-4 md:leading-5 lg:leading-6 text-center", dateClass)}>
                                                    {stepDates[index]}
                                                </TypographySmall>
                                            </div>
                                        </li>
                                    );
                                })}
                            </ol>
                        </div>
                    </div>
                </div>
            </CardContent>
        </Card>
    );
};

export { OrderStatus, type OrderStatusType };