"use client";

import React, { useEffect, useState } from "react";
import { Card } from "@/components/ui/card";
import OrderProductCard from "./OrderProductCard";
import { OrderStatus } from "./OrderStatus";
import { Separator } from "../ui/separator";
import { TypographyH3, TypographyH4 } from "../ui/typography";
import Image from "next/image";
import Link from "next/link";
import { orderService, Order } from "@/services/orderService";
import { Loader2 } from "lucide-react";

type HelpLink = {
  href: string;
  icon: string;
  alt: string;
  label: string;
};

export default function AllOrder() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadOrders();
  }, []);

  const loadOrders = async () => {
    try {
      setLoading(true);
      const response = await orderService.getOrders();
      setOrders(response.data || []);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load orders');
      console.error('Error loading orders:', err);
    } finally {
      setLoading(false);
    }
  };

  const helpLinks: HelpLink[] = [
    {
      href: "/order-issues",
      icon: "/assets/icons/info-circle.svg",
      alt: "info-circle",
      label: "مشاكل الطلب",
    },
    {
      href: "/delivery-info",
      icon: "/assets/icons/truck-time.svg",
      alt: "truck-time",
      label: "معلومات التوصيل",
    },
    {
      href: "/returns",
      icon: "/assets/icons/box-remove.svg",
      alt: "box-remove",
      label: "الإرجاع",
    },
  ];

  const latestOrder = orders[0];

  if (loading) {
    return (
      <div className="mt-6 md:mt-11 flex justify-center items-center py-20">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="mt-6 md:mt-11">
        <Card className="p-8 text-center">
          <p className="text-red-500">{error}</p>
        </Card>
      </div>
    );
  }

  if (orders.length === 0) {
    return (
      <div className="mt-6 md:mt-11">
        <Card className="p-8 text-center">
          <p className="text-gray-500">لم يتم العثور على طلبات</p>
          <Link href="/" className="text-primary hover:underline mt-2 inline-block">
            ابدأ التسوق
          </Link>
        </Card>
      </div>
    );
  }

  return (
    <div className="mt-6 md:mt-11">
      {latestOrder && (
        <>
          {/* Order ID Header */}
          <Card className="mb-6 p-6 bg-gradient-to-r from-blue-50 to-indigo-50 border-2 border-blue-200">
            <div className="flex justify-between items-center flex-wrap gap-4">
              <div className="text-left">
                <p className="text-sm text-gray-600 mb-1">حالة الطلب</p>
                <span className={`inline-block px-4 py-2 rounded-full text-sm font-semibold ${
                  latestOrder.status === 'delivered' ? 'bg-green-100 text-green-800' :
                  latestOrder.status === 'shipped' ? 'bg-blue-100 text-blue-800' :
                  latestOrder.status === 'processing' ? 'bg-yellow-100 text-yellow-800' :
                  latestOrder.status === 'cancelled' ? 'bg-red-100 text-red-800' :
                  'bg-gray-100 text-gray-800'
                }`}>
                  {orderService.getStatusDisplay(latestOrder.status)}
                </span>
                <p className="text-sm text-gray-500 mt-2">
                  الدفع: {latestOrder.payment_method === 'card' ? 'بطاقة' : 'الدفع عند الاستلام'}
                </p>
              </div>
              <div>
                <p className="text-sm text-gray-600 mb-1">رقم الطلب</p>
                <h2 className="text-2xl md:text-3xl font-bold text-gray-900">
                  #{latestOrder.order_number}
                </h2>
                
                {/* Reference Number Box */}
                <div className="bg-white border-2 border-blue-300 rounded-lg p-3 mt-3">
                  <p className="text-xs text-gray-600 mb-1">الرقم المرجعي</p>
                  <p className="font-mono font-bold text-blue-600 text-base">{latestOrder.reference_number}</p>
                </div>
                
                <p className="text-sm text-gray-500 mt-3">
                  تم الطلب في {new Date(latestOrder.created_at).toLocaleString('ar-SA-u-ca-gregory', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: true
                  })}
                </p>
              </div>
            </div>
          </Card>

          <OrderStatus 
            currentStatus={
              latestOrder.status === 'delivered' ? 'delivered' :
              latestOrder.status === 'shipped' ? 'shipped' :
              latestOrder.status === 'processing' ? 'shipped' :
              'ordered'
            }
            orderNumber={latestOrder.reference_number}
            orderDate={new Date(latestOrder.created_at).toLocaleString('ar-SA-u-ca-gregory', {
              year: 'numeric',
              month: 'short',
              day: 'numeric'
            })}
            estimatedDelivery={new Date(new Date(latestOrder.created_at).getTime() + 5 * 24 * 60 * 60 * 1000).toLocaleDateString('ar-SA-u-ca-gregory', {
              year: 'numeric',
              month: 'short',
              day: 'numeric'
            })}
            createdAt={latestOrder.created_at}
          />
        </>
      )}
      
      <Card className="pl-[17px] pr-[21px] md:px-[22px] py-[26px] md:py-[30px] gap-0">
        <div className="space-y-[13px] md:space-y-10 mb-9 sm:mb-8">
          <h3 className="text-black text-[22px] sm:text-[30px] leading-[38px] font-bold">
            جميع الطلبات ({orders.length})
          </h3>

          <div className="space-y-[17px] sm:space-y-7 lg:space-y-10">
            {orders.map((order) => (
              <Link key={order.reference_number} href={`/order/${order.reference_number}`}>
                <div className="space-y-4 p-4 bg-gray-50 rounded-lg border border-gray-200 hover:border-blue-400 hover:shadow-md transition-all cursor-pointer">
                  <div className="flex justify-between items-start">
                    <div className="text-left">
                      <p className="text-xs text-gray-500 mb-1">الحالة</p>
                      <span className={`inline-block px-3 py-1 rounded-full text-xs font-semibold ${
                        order.status === 'delivered' ? 'bg-green-100 text-green-800' :
                        order.status === 'shipped' ? 'bg-blue-100 text-blue-800' :
                        order.status === 'processing' ? 'bg-yellow-100 text-yellow-800' :
                        order.status === 'cancelled' ? 'bg-red-100 text-red-800' :
                        'bg-gray-100 text-gray-800'
                      }`}>
                        {orderService.getStatusDisplay(order.status)}
                      </span>
                      <p className="text-xs text-blue-600 mt-2 font-medium">عرض التفاصيل ←</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500 mb-1">رقم الطلب</p>
                      <p className="font-bold text-lg md:text-xl text-blue-600">#{order.order_number}</p>
                      
                      {/* Reference Number */}
                      <div className="bg-white border border-blue-200 rounded px-2 py-1 mt-2 inline-block">
                        <p className="text-xs text-gray-500">رقم مرجعي: <span className="font-mono font-semibold text-blue-600">{order.reference_number}</span></p>
                      </div>
                      
                      <p className="text-sm text-gray-500 mt-2">
                        {new Date(order.created_at).toLocaleDateString('ar-SA-u-ca-gregory', {
                          year: 'numeric',
                          month: 'long',
                          day: 'numeric'
                        })}
                      </p>
                    </div>
                  </div>

                  {order.items.map((item) => (
                    <OrderProductCard 
                      key={item.id} 
                      item={{
                        id: item.id.toString(),
                        title: item.product_variant.product.name,
                        image: item.product_variant.product.image_url || '/api/placeholder/300/300',
                        price: item.price,
                        qty: item.quantity,
                        rating: 4.5,
                        attributes: [
                          `Size: ${item.product_variant.size}`,
                          `Color: ${item.product_variant.color}`
                        ],
                        status: order.status as "present" | "previous" | "cancel",
                      }} 
                    />
                  ))}
                  
                  <Separator className="my-4" />
                  
                  <div className="text-left">
                    <p className="text-sm font-semibold">الإجمالي: ${Number(order.total_amount).toFixed(2)}</p>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        </div>

        {latestOrder && (
          <>
            <Separator className="bg-[#D0D5DD]" />

            <div className="flex items-start gap-8 sm:gap-[50px] md:mt-8 my-6 md:mb-14">
              {/* Delivery */}
              <div className="max-w-[524px] w-full">
                <TypographyH3 className="text-[16px] sm:text-[20px] leading-[30px] font-bold mb-0.5 sm:mb-1.5">
                  عنوان التوصيل
                </TypographyH3>
                <div>
                  <span className="text-[#667085] text-[12px] sm:text-[14px] leading-5 font-normal mb-1.5">
                    {latestOrder.shipping_address.first_name} {latestOrder.shipping_address.last_name}
                  </span>
                  <TypographyH3 className="max-w-[215px] text-[14px] sm:text-[20px] leading-[22px] sm:leading-7 font-medium">
                    {latestOrder.shipping_address.street}, {latestOrder.shipping_address.city}, {latestOrder.shipping_address.state} {latestOrder.shipping_address.zip_code}
                  </TypographyH3>
                  {latestOrder.shipping_address.phone && (
                    <p className="text-sm text-gray-500 mt-1">{latestOrder.shipping_address.phone}</p>
                  )}
                </div>
              </div>

              {/* Payment */}
              <div className="max-w-[524px] w-full">
                <TypographyH3 className="text-[16px] sm:text-[20px] leading-[30px] font-bold mb-1.5">
                  طريقة الدفع
                </TypographyH3>
                <div className="flex items-center gap-[11px]">
                  <h4 className="text-[#667085] text-[14px] leading-5 inter font-normal">
                    {latestOrder.payment_method === 'card' ? 'بطاقة ائتمان' : 'الدفع عند الاستلام'}
                  </h4>
                  {latestOrder.payment_method === 'card' && (
                    <Image
                      src="/assets/icons/visa.svg"
                      alt="payment"
                      width={34}
                      height={24}
                    />
                  )}
                </div>
                <p className="text-sm text-gray-500 mt-1">
                  الحالة: {latestOrder.payment_status === 'paid' ? 'مدفوع' : 'قيد الانتظار'}
                </p>
              </div>
            </div>

            <Separator className="bg-[#D0D5DD]" />

            <div className="flex items-start gap-3 sm:gap-[50px] mt-6 sm:mt-8">
              <div className="max-w-[558px] w-full space-y-1.5 sm:space-y-3">
                <TypographyH3 className="text-[14px] sm:text-[20px] leading-[30px] font-medium inter">
                  ملخص الطلب
                </TypographyH3>
                <div className="space-y-1.5 sm:space-y-3">
                  <div className="flex items-center justify-between">
                    <TypographyH3 className="text-[12px] sm:text-[20px] leading-[30px] font-medium">
                      المجموع الفرعي
                    </TypographyH3>
                    <TypographyH3 className="text-[10px] sm:text-[20px] leading-[30px] font-medium">
                      ${(Number(latestOrder.total_amount) + Number(latestOrder.discount_amount)).toFixed(2)}
                    </TypographyH3>
                  </div>
                  {Number(latestOrder.discount_amount) > 0 && (
                    <div className="flex items-center justify-between">
                      <TypographyH4>الخصم</TypographyH4>
                      <TypographyH4 className="text-[10px] sm:text-[18px]">
                        -${Number(latestOrder.discount_amount).toFixed(2)}
                      </TypographyH4>
                    </div>
                  )}
                  <div className="flex items-center justify-between">
                    <TypographyH4>التوصيل</TypographyH4>
                    <TypographyH4 className="text-[10px] sm:text-[18px]">$0.00</TypographyH4>
                  </div>
                  <Separator />
                  <div className="sm:mt-[3px] flex items-center justify-between font-semibold text-base">
                    <TypographyH3 className="text-[12px] sm:text-[20px] leading-[30px] font-medium">
                      الإجمالي
                    </TypographyH3>
                    <TypographyH3 className="text-[10px] sm:text-[20px] leading-[30px] font-bold">
                      ${Number(latestOrder.total_amount).toFixed(2)}
                    </TypographyH3>
                  </div>
                </div>
              </div>

              <div className="max-w-[125px] sm:max-w-[558px] w-full space-y-1.5 sm:space-y-3">
                <TypographyH3 className="text-[14px] sm:text-[20px] leading-[30px] font-medium inter">
                  تحتاج مساعدة؟
                </TypographyH3>
                <div className="space-y-1.5 sm:space-y-3">
                  {helpLinks.map((item: HelpLink) => (
                    <Link
                      href={item.href}
                      className="flex items-center gap-[5px] text-[10px] sm:text-[18px]"
                      key={item.label}
                    >
                      <Image
                        src={item.icon}
                        alt={item.alt}
                        width={17}
                        height={17}
                        className="sm:w-[17px] w-[13px]"
                      />
                      <TypographyH4>{item.label}</TypographyH4>
                      <svg
                        width="25"
                        height="25"
                        className="sm:w-[25px] w-[13px]"
                        viewBox="0 0 25 25"
                        fill="none"
                        xmlns="http://www.w3.org/2000/svg"
                      >
                        <path
                          d="M15.9022 14.2196C15.8071 14.1244 15.747 13.9942 15.747 13.844L15.747 8.29435L10.1973 8.29435C9.90684 8.29435 9.66643 8.05393 9.66643 7.76343C9.66643 7.47292 9.90684 7.23251 10.1973 7.23251L16.2779 7.23251C16.5684 7.23251 16.8088 7.47292 16.8088 7.76343L16.8088 13.844C16.8088 14.1345 16.5684 14.3749 16.2779 14.3749C16.1326 14.3799 15.9974 14.3148 15.9022 14.2196Z"
                          fill="black"
                        />
                        <path
                          d="M7.38744 16.6538C7.18209 16.4485 7.18209 16.1079 7.38744 15.9025L15.817 7.47294C16.0224 7.26758 16.363 7.26758 16.5683 7.47294C16.7737 7.6783 16.7737 8.01889 16.5683 8.22424L8.13874 16.6538C7.93339 16.8592 7.5928 16.8592 7.38744 16.6538Z"
                          fill="black"
                        />
                      </svg>
                    </Link>
                  ))}
                </div>
              </div>
            </div>
          </>
        )}
      </Card>
    </div>
  );
}
