"use client";

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

export default function CancelOrder() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);

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

  const loadOrders = async () => {
    try {
      setLoading(true);
      const response = await orderService.getOrders();
      const cancelledOrders = response.data.filter(
        order => order.status === 'cancelled'
      );
      setOrders(cancelledOrders);
    } catch (err) {
      console.error('Error loading orders:', err);
    } finally {
      setLoading(false);
    }
  };

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

  if (orders.length === 0) {
    return (
      <Card className="pl-[17px] pr-[17px] md:px-[22px] py-[26px] md:py-[30px] gap-[13px] md:gap-10 mt-9 sm:mt-12 lg:mt-20 text-center">
        <p className="text-gray-500">No cancelled orders</p>
      </Card>
    );
  }

  return (
    <Card className="pl-[17px] pr-[17px] md:px-[22px] py-[26px] md:py-[30px] gap-[13px] md:gap-10 mt-9 sm:mt-12 lg:mt-20">
      <h3 className="text-black text-[22px] sm:text-[30px] leading-[38px] font-bold mb-6">Cancelled Orders ({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-red-400 hover:shadow-md transition-all cursor-pointer">
              <div className="flex justify-between items-start">
                <div>
                  <p className="text-xs text-gray-500 mb-1">Order ID</p>
                  <p className="font-bold text-lg 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">Ref: <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('en-US', {
                      year: 'numeric',
                      month: 'long',
                      day: 'numeric'
                    })}
                  </p>
                </div>
                <div className="text-right">
                  <p className="text-xs text-gray-500 mb-1">Status</p>
                  <span className="inline-block px-3 py-1 rounded-full text-xs font-semibold bg-red-100 text-red-800">
                    Cancelled
                  </span>
                  <p className="text-xs text-blue-600 mt-2 font-medium">View Details →</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: 'cancel',
                  }}
                  variant="cancel"
                />
              ))}
              
              <Separator className="my-2" />
              
              <div className="text-right">
                <p className="text-sm font-semibold">Total: ${Number(order.total_amount).toFixed(2)}</p>
              </div>
            </div>
          </Link>
        ))}
      </div>
    </Card>
  );
}
