"use client";

import React, { useState, useEffect, use } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import {
  FaUser,
  FaMapMarkerAlt,
  FaBox,
  FaWallet,
  FaChevronRight,
  FaCheckCircle,
  FaTruck,
  FaClock,
  FaDownload,
  FaHome
} from "react-icons/fa";
import { formatPrice } from "../../../../utils/currencyHelper";

type OrderItem = {
  sku_no: string;
  name: string;
  quantity: number;
  dealer_price: number;
  subtotal: number;
  image?: string;
  inward_id?: string;
  currency?: string;
  quantity_invoiced?: number;
  quantity_backordered?: number;
};

type InvoiceItem = {
  inward_id: string;
  sku_no: string;
  name: string;
  quantity: number;
  dealer_price: number;
  subtotal: number;
};

type Invoice = {
  invoice_id: string;
  items: InvoiceItem[];
  subtotal: number;
  tax_type: string;
  tax_rate: number;
  tax_amount: number;
  total_with_tax: number;
  created_at: string;
};

type OrderDetail = {
  order_id: string;
  status: string;
  total_amount?: number;
  total_price?: number;
  subtotal?: number;
  discount_applied?: number;
  coin_discount?: number;
  created_at?: string;
  order_date?: string;
  payment_type?: string;
  coupon_code?: string | null;
  coins_earned?: number;
  coins_redeemed?: number;
  dealer_coin_balance?: number;
  payment_status?: string;
  items: OrderItem[];
  invoices?: Invoice[];
  has_backorder?: boolean;
  status_history?: {
    status: string;
    created_at?: string;
    date?: string;
    comment?: string;
  }[];
  shipping_address?: {
    business_name: string;
    address_line: string;
    city: string;
    state: string;
    pincode: string;
  };
};

type UserProfile = {
  first_name: string;
  last_name: string;
  email: string;
  mobile_number: string;
};

export default function ProfileOrderDetailPage({ params }: { params: Promise<{ order_id: string }> }) {
  const unwrappedParams = use(params);
  const [order, setOrder] = useState<OrderDetail | null>(null);
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const router = useRouter();
  const orderId = unwrappedParams.order_id;

  useEffect(() => {
    const token = localStorage.getItem("access_token");
    if (!token) {
      router.push("/login");
      return;
    }

    const fetchData = async () => {
      try {
        // Fetch Profile
        const profileRes = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/users/me`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (profileRes.status === 401) {
          localStorage.removeItem("access_token");
          router.push("/login");
          return;
        }
        if (profileRes.ok) {
          setProfile(await profileRes.json());
        }

        // Fetch Order Details
        const orderRes = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-orders/${orderId}`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (orderRes.ok) {
          const data = await orderRes.json();
          setOrder(data.order || data);
        }
      } catch (err) {
        console.error("Failed to fetch order details:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [orderId, router]);

  const handleDownloadPO = async () => {
    const token = localStorage.getItem("access_token");
    if (!token) {
      alert("You must be logged in to download the PO.");
      return;
    }

    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-orders/${orderId}/po`, {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        alert(`Failed to download PO: ${err.detail || "Server error"}`);
        return;
      }

      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `PO_${orderId}.pdf`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove();
    } catch (err) {
      console.error("Error downloading PO", err);
      alert("Something went wrong while downloading the PO.");
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </div>
    );
  }

  if (!order || !profile) {
    return (
      <div className="min-h-screen bg-[#FAF9F6] flex flex-col items-center justify-center">
        <h2 className="text-2xl font-bold text-gray-900 mb-4">Order not found</h2>
        <Link href="/profile/order" className="text-primary font-bold hover:underline">
          Back to Orders
        </Link>
      </div>
    );
  }

  const initials = `${profile.first_name?.[0] || ""}${profile.last_name?.[0] || ""}`.toUpperCase();
  const price = order.total_amount ?? order.total_price ?? 0;
  const dateString = order.created_at ?? order.order_date ?? null;
  const items = Array.isArray(order.items) ? order.items : [];

  const getStatusIcon = (status: string) => {
    const s = (status || "").toLowerCase();
    if (s.includes("delivered") || s.includes("completed")) return <FaCheckCircle className="text-emerald-500 text-sm" />;
    if (s.includes("shipped") || s.includes("dispatch")) return <FaTruck className="text-blue-500 text-sm" />;
    return <FaClock className="text-[#FF9900] text-sm" />;
  };

  const getStatusColor = (status: string) => {
    const s = (status || "").toLowerCase();
    if (s.includes("delivered") || s.includes("completed")) return "bg-emerald-50/70 text-emerald-800 border-emerald-300";
    if (s.includes("shipped") || s.includes("dispatch")) return "bg-blue-50/70 text-blue-850 border-blue-300";
    return "bg-amber-50/70 text-[#C26200] border-amber-300";
  };

  const formatDate = (dateStr?: string | null) => {
    if (!dateStr) return "N/A";
    try {
      return new Date(dateStr).toLocaleDateString("en-US", {
        day: "numeric",
        month: "long",
        year: "numeric",
      });
    } catch {
      return dateStr;
    }
  };

  // Math variables for order summary layout matching the screenshot reference
  const taxableValue = price * 0.85; // 85% of total
  const taxesValue = price * 0.15; // 15% GST

  return (
    <div className="bg-[#FAF9F6] min-h-screen py-10">
      <div className="max-w-6xl mx-auto px-4 sm:px-6">

        {/* Breadcrumb matching first screenshot */}
        <div className="flex items-center gap-2 text-xs font-semibold text-gray-400 mb-8 select-none">
          <Link href="/" className="hover:text-primary transition-colors flex items-center gap-1">
            <FaHome className="text-[11px] mb-0.5" /> Home
          </Link>
          <FaChevronRight className="text-[8px]" />
          <Link href="/profile" className="hover:text-primary transition-colors">My Account</Link>
          <FaChevronRight className="text-[8px]" />
          <Link href="/profile/order" className="hover:text-primary transition-colors">My Orders</Link>
          <FaChevronRight className="text-[8px]" />
          <span className="text-gray-600">Order Summary</span>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8 items-start">

          {/* Shared Sidebar */}
          <div className="col-span-1 flex flex-col gap-6 lg:sticky lg:top-28">
            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-8 flex flex-col items-center text-center">
              <div 
                style={{ backgroundColor: "#1e293b", color: "#ffffff" }}
                className="w-20 h-20 rounded-full flex items-center justify-center text-2xl font-black mb-4 shadow-md relative shrink-0"
              >
                {initials}
                <div className="absolute bottom-0 right-0 w-5 h-5 rounded-full bg-emerald-500 border-2 border-white flex items-center justify-center text-[10px] text-white">✓</div>
              </div>
              <div className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1 select-none">Welcome Back,</div>
              <h2 className="text-xl font-extrabold text-gray-800 leading-tight">{profile.first_name}</h2>
            </div>

            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6 flex flex-col gap-6">
              <div>
                <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-3 px-2">My Account</h3>
                <nav className="flex flex-col gap-1.5">
                  <Link href="/profile/order" className="flex items-center justify-between px-3 py-2.5 rounded-xl bg-primary-light text-primary text-xs font-bold transition-colors">
                    <span className="flex items-center gap-2.5"><FaBox /> MY ORDERS</span>
                    <FaChevronRight className="text-[8px]" />
                  </Link>
                  <Link href="/profile" className="flex items-center justify-between px-3 py-2.5 rounded-xl hover:bg-gray-50 text-xs font-bold text-gray-600 hover:text-gray-900 transition-colors">
                    <span className="flex items-center gap-2.5"><FaUser className="text-gray-400" /> MY PROFILE</span>
                    <FaChevronRight className="text-[8px] text-gray-400" />
                  </Link>
                </nav>
              </div>

              <div className="border-t border-gray-100"></div>

              <div>
                <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-3 px-2">Reward Coins</h3>
                <nav className="flex flex-col gap-1.5">
                  <Link href="/profile/wallet" className="flex items-center justify-between px-3 py-2.5 rounded-xl hover:bg-gray-50 text-xs font-bold text-gray-600 hover:text-gray-900 transition-colors">
                    <span className="flex items-center gap-2.5">🪙 MY COINS</span>
                    <FaChevronRight className="text-[8px] text-gray-400" />
                  </Link>
                </nav>
              </div>
            </div>
          </div>

          {/* Right Column: Order Details Layout */}
          <div className="col-span-1 lg:col-span-3 flex flex-col gap-6">

            {/* Title & PO Download */}
            <div className="flex justify-between items-center select-none gap-3 flex-wrap">
              <h2 className="text-2xl font-black text-gray-900 tracking-tight">Order Details</h2>
              <div className="flex items-center gap-2">
                <button
                  onClick={handleDownloadPO}
                  className="px-5 py-2.5 bg-slate-900 hover:bg-slate-800 text-white font-extrabold text-[11px] tracking-wider uppercase rounded-xl transition-all shadow-md active:scale-95 flex items-center gap-1.5"
                >
                  <FaDownload className="text-[10px]" /> Download PO
                </button>
              </div>
            </div>

            {/* BANNED Announcement/Info Header Row matching exactly the screenshot style */}
            <div className="bg-white rounded-2xl border border-gray-200/80 p-5 shadow-[0_2px_15px_rgba(0,0,0,0.01)] flex items-center justify-between gap-4">
              <div className="text-xs font-semibold text-gray-500">
                Ordered on <span className="text-gray-800 font-bold">{formatDate(dateString)}</span> <span className="mx-3 text-gray-300">|</span> Order# <span className="font-extrabold text-gray-900 uppercase">{order.order_id}</span>
              </div>
              <div className={`px-4 py-2 border rounded-full text-xs font-black uppercase tracking-wider flex items-center gap-2 select-none shrink-0 ${getStatusColor(order.status)}`}>
                {getStatusIcon(order.status)}
                {order.status || "Pending"}
              </div>
            </div>

            {/* Status History / Timeline Section */}
            <div className="bg-white rounded-[2rem] border border-gray-200/80 p-6 sm:p-8 shadow-[0_4px_25px_rgba(0,0,0,0.02)] flex flex-col gap-6">
              <h3 className="text-sm font-black text-gray-800 uppercase tracking-widest select-none">
                Order Status Timeline
              </h3>
              {order.status_history && order.status_history.length > 0 ? (
                <div className="relative border-l-2 border-gray-100 ml-3 pl-6 space-y-6">
                  {order.status_history.map((hist, index) => (
                    <div key={index} className="relative">
                      <span className="absolute -left-[31px] top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-emerald-500 ring-4 ring-white">
                        <span className="h-1.5 w-1.5 rounded-full bg-white" />
                      </span>
                      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-1 select-none">
                        <span className="text-xs font-extrabold text-gray-800 uppercase tracking-wide">
                          {hist.status}
                        </span>
                        <span className="text-[10px] font-bold text-gray-400">
                          {formatDate(hist.created_at || hist.date)}
                        </span>
                      </div>
                      {hist.comment && (
                        <p className="text-xs text-gray-500 font-semibold mt-1">
                          {hist.comment}
                        </p>
                      )}
                    </div>
                  ))}
                </div>
              ) : (
                <div className="relative border-l-2 border-gray-100 ml-3 pl-6 space-y-6">
                  <div className="relative">
                    <span className="absolute -left-[31px] top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-emerald-500 ring-4 ring-white">
                      <span className="h-1.5 w-1.5 rounded-full bg-white" />
                    </span>
                    <div className="flex flex-col select-none">
                      <span className="text-xs font-extrabold text-gray-800 uppercase tracking-wide">
                        {order.status || "Pending"}
                      </span>
                      <span className="text-[10px] font-bold text-gray-400">
                        {formatDate(dateString)}
                      </span>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* 3-Column Shipping, Payment, and Summary Card (Matches First Screenshot style) */}
            <div className="bg-white rounded-[2rem] border border-gray-200/80 p-6 sm:p-8 shadow-[0_4px_25px_rgba(0,0,0,0.02)] grid grid-cols-1 md:grid-cols-3 gap-8 items-stretch divide-y md:divide-y-0 md:divide-x divide-gray-100">

              {/* Shipping Address Column */}
              <div className="flex flex-col gap-3 pb-6 md:pb-0">
                <h3 className="text-sm font-black text-gray-800 uppercase tracking-widest">
                  Shipping Address
                </h3>
                {order.shipping_address ? (
                  <div className="text-xs font-semibold text-gray-500 leading-relaxed flex flex-col gap-1 mt-1">
                    <span className="font-extrabold text-gray-850">{order.shipping_address.business_name}</span>
                    <span>{order.shipping_address.address_line}</span>
                    <span>{order.shipping_address.city}, {order.shipping_address.state} {order.shipping_address.pincode}</span>
                    <span>India</span>
                    <span className="mt-4 text-[10px] text-gray-400">Phone: {profile.mobile_number || ""}</span>
                  </div>
                ) : (
                  <p className="text-xs text-gray-400 italic">Address unavailable</p>
                )}
              </div>

              {/* Payment Method Column */}
              <div className="flex flex-col gap-3 pt-6 md:pt-0 md:pl-8">
                <h3 className="text-sm font-black text-gray-800 uppercase tracking-widest">
                  Payment Method
                </h3>
                <div className="flex items-center gap-2 mt-2">
                  <span className="text-[9px] font-black tracking-widest uppercase border border-gray-200 bg-gray-50/50 text-gray-500 px-2 py-0.5 rounded">
                    {order.payment_type === "credit" ? "Credit" : "Online"}
                  </span>
                  <span className="text-xs font-extrabold text-gray-800">
                    {order.payment_type === "credit" ? "B2B Credit Limit" : "Razorpay"}
                  </span>
                </div>
                {order.payment_status && (
                  <div className="flex items-center gap-1.5 mt-2">
                    <span className="text-[10px] text-gray-400 font-bold uppercase">Payment Status:</span>
                    <span className={`text-[9px] font-black tracking-widest uppercase px-2.5 py-0.5 rounded border ${
                      order.payment_status === "Paid"
                        ? "bg-emerald-50 text-emerald-800 border-emerald-255"
                        : "bg-amber-50 text-amber-800 border-amber-300"
                    }`}>
                      {order.payment_status}
                    </span>
                  </div>
                )}
                <span className="text-[10px] text-gray-400 font-bold uppercase tracking-wider mt-4">
                  Account: CNRB
                </span>
              </div>

              {/* Order Summary Column */}
              <div className="flex flex-col gap-3 pt-6 md:pt-0 md:pl-8">
                <h3 className="text-sm font-black text-gray-800 uppercase tracking-widest">
                  Order Summary
                </h3>
                <div className="flex flex-col gap-2.5 text-xs font-semibold text-gray-500 mt-1">
                  <div className="flex justify-between items-center">
                    <span>Subtotal:</span>
                    <span>{formatPrice(order.subtotal ?? price, order.items?.[0]?.currency)}</span>
                  </div>

                  {(order.discount_applied ?? 0) > 0 && (
                    <div className="flex justify-between items-center text-emerald-600 font-bold">
                      <span>Coupon {order.coupon_code ? `(${order.coupon_code})` : ""}:</span>
                      <span>−{formatPrice(order.discount_applied, order.items?.[0]?.currency)}</span>
                    </div>
                  )}

                  {(order.coin_discount ?? 0) > 0 && (
                    <div className="flex justify-between items-center text-amber-600 font-bold">
                      <span>🪙 Coins Redeemed:</span>
                      <span>−{formatPrice(order.coin_discount, order.items?.[0]?.currency)}</span>
                    </div>
                  )}

                  <div className="flex justify-between items-center">
                    <span>Shipping:</span>
                    <span>{formatPrice(0, order.items?.[0]?.currency)}</span>
                  </div>

                  <div className="border-t border-gray-200 my-1.5" />

                  <div className="flex justify-between items-baseline text-sm font-extrabold text-gray-800">
                    <span className="text-gray-900 font-extrabold">Total:</span>
                    <span className="text-base font-black text-gray-900">{formatPrice(price, order.items?.[0]?.currency)}</span>
                  </div>

                  {/* Coins summary */}
                  {((order.coins_earned ?? 0) > 0 || (order.coins_redeemed ?? 0) > 0) && (
                    <div className="mt-2 pt-2 border-t border-gray-100 flex flex-col gap-1.5">
                      {(order.coins_earned ?? 0) > 0 && (
                        <div className="flex justify-between items-center text-amber-600 font-bold">
                          <span>🪙 Coins Earned:</span>
                          <span>+{order.coins_earned?.toLocaleString("en-IN")}</span>
                        </div>
                      )}
                      {(order.coins_redeemed ?? 0) > 0 && (
                        <div className="flex justify-between items-center text-violet-600 font-bold">
                          <span>🪙 Coins Used:</span>
                          <span>−{order.coins_redeemed?.toLocaleString("en-IN")}</span>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </div>

            </div>

            {/* Items List Card (Matches Second Screenshot style beautifully) */}
            <div className="bg-white rounded-[2rem] border border-gray-200/80 p-6 sm:p-8 shadow-[0_4px_25px_rgba(0,0,0,0.02)] flex flex-col gap-4">
              {items.length === 0 ? (
                <div className="text-xs text-gray-400 italic py-6 text-center">
                  No items listed in this order
                </div>
              ) : (
                items.map((item, idx) => (
                  <div key={idx} className="bg-white border-2 border-black p-5 flex gap-5 transition-all">
                    {/* Image */}
                    <div className="w-24 h-24 shrink-0 bg-white rounded-xl flex items-center justify-center overflow-hidden border border-gray-200 p-1">
                      <img 
                        src={item.image || "https://static.wixstatic.com/media/703249_3a76a53b765e46d4b3a5e4c3ec6ddd7e~mv2.png/v1/fill/w_1362,h_1002,al_c,q_90,usm_0.66_1.00_0.01,enc_avif,quality_auto/Full%20Face%20Helmet.png"} 
                        alt={item.name} 
                        className="w-full h-full object-contain mix-blend-multiply"
                      />
                    </div>

                    {/* Details */}
                    <div className="flex-grow flex flex-col justify-between py-1">
                      <div className="flex justify-between items-start gap-4">
                        <div>
                          <h4 className="text-[13px] font-black text-gray-900 leading-tight uppercase tracking-tight">{item.name}</h4>
                          <div className="text-[11px] font-bold text-gray-400 uppercase tracking-widest mt-1.5">
                            SKU: {item.sku_no}
                          </div>
                        </div>
                        <span className="text-[15px] font-black text-gray-900 shrink-0 tabular-nums">{formatPrice(item.subtotal, item.currency)}</span>
                      </div>

                      <div className="flex items-center justify-between mt-2 flex-wrap gap-2">
                        <div className="flex items-center gap-6 mt-1">
                          <div>
                            <span className="text-gray-400 text-[10px] font-bold uppercase tracking-wider block mb-0.5">PRICE</span>
                            <span className="font-black text-gray-900 text-[14px]">{formatPrice(item.dealer_price, item.currency)}</span>
                          </div>
                          <div className="h-6 w-[1.5px] bg-gray-200 self-end mb-1"></div>
                          <div>
                            <span className="text-gray-400 text-[10px] font-bold uppercase tracking-wider block mb-0.5">QTY</span>
                            <span className="font-black text-gray-900 text-[14px] tabular-nums">{item.quantity}</span>
                          </div>
                          {order.has_backorder && (
                            <>
                              <div className="h-6 w-[1.5px] bg-gray-200 self-end mb-1"></div>
                              {item.quantity_invoiced !== undefined && (
                                <div>
                                  <span className="text-gray-400 text-[10px] font-bold uppercase tracking-wider block mb-0.5">INVOICED</span>
                                  <span className="font-black text-blue-600 text-[14px]">{item.quantity_invoiced}</span>
                                </div>
                              )}
                              {item.quantity_backordered !== undefined && item.quantity_backordered > 0 && (
                                <>
                                  <div className="h-6 w-[1.5px] bg-gray-200 self-end mb-1"></div>
                                  <div>
                                    <span className="text-gray-400 text-[10px] font-bold uppercase tracking-wider block mb-0.5">BACKORDERED</span>
                                    <span className="font-black text-amber-600 text-[14px]">{item.quantity_backordered}</span>
                                  </div>
                                </>
                              )}
                            </>
                          )}
                        </div>
                        <button
                          onClick={() => router.push("/")}
                          className="px-5 py-1.5 bg-[#FFC633] hover:bg-[#E0AB1F] text-gray-900 font-extrabold text-[10px] uppercase tracking-wider transition-all rounded-full shadow-sm active:scale-95 border border-[#E0AB1F]"
                        >
                          Buy it again
                        </button>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>

            {/* Invoices List Card */}
            {order.invoices && order.invoices.length > 0 && (
              <div className="bg-white rounded-[2rem] border border-gray-200/80 p-6 sm:p-8 shadow-[0_4px_25px_rgba(0,0,0,0.02)] flex flex-col gap-6">
                <h3 className="text-sm font-black text-gray-800 uppercase tracking-widest select-none">
                  Invoices Issued
                </h3>
                <div className="flex flex-col gap-4">
                  {order.invoices.map((inv, idx) => (
                    <div key={idx} className="border border-gray-150/80 rounded-2xl p-5 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 hover:shadow-md transition-shadow">
                      <div>
                        <span className="text-[10px] font-black text-gray-400 uppercase tracking-widest block mb-1">
                          Invoice ID
                        </span>
                        <span className="text-sm font-black text-gray-900 block mb-2">
                          {inv.invoice_id}
                        </span>
                        <div className="flex items-center gap-4 text-xs text-gray-500 font-semibold">
                          <span>Date: {formatDate(inv.created_at)}</span>
                          <span>Tax: {inv.tax_type} ({inv.tax_rate}%)</span>
                        </div>
                      </div>
                      <div className="flex items-center gap-6 self-stretch sm:self-auto justify-between border-t sm:border-0 pt-4 sm:pt-0">
                        <div className="text-right">
                          <span className="text-[10px] font-black text-gray-400 uppercase tracking-widest block mb-0.5">
                            Total Payable
                          </span>
                          <span className="text-lg font-black text-emerald-700">
                            {formatPrice(inv.total_with_tax, order.items?.[0]?.currency)}
                          </span>
                        </div>
                        <button
                          onClick={async () => {
                            const token = localStorage.getItem("access_token");
                            if (!token) {
                              alert("You must be logged in to download the invoice.");
                              return;
                            }
                            try {
                              const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-orders/${order.order_id}/invoices/${inv.invoice_id}/pdf`, {
                                headers: { Authorization: `Bearer ${token}` }
                              });
                              if (!res.ok) {
                                alert("Failed to download invoice PDF.");
                                return;
                              }
                              const blob = await res.blob();
                              const url = window.URL.createObjectURL(blob);
                              const a = document.createElement("a");
                              a.href = url;
                              a.download = `Invoice_${inv.invoice_id}.pdf`;
                              document.body.appendChild(a);
                              a.click();
                              window.URL.revokeObjectURL(url);
                              a.remove();
                            } catch (err) {
                              console.error(err);
                              alert("Failed to download invoice PDF.");
                            }
                          }}
                          className="px-4 py-2 border border-slate-900 text-slate-900 hover:bg-slate-900 hover:text-white font-extrabold text-[10px] tracking-wider uppercase rounded-xl transition-all shadow-sm active:scale-95 flex items-center gap-1.5"
                        >
                          <FaDownload className="text-[9px]" /> Download PDF
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

          </div>
        </div>
      </div>
    </div>
  );
}
