"use client";

import React, { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { TypographyH3, TypographyH4 } from "@/components/ui/typography";
import { OrderStatus } from "@/components/OrderComponent/OrderStatus";
import OrderProductCard from "@/components/OrderComponent/OrderProductCard";
import { orderService, Order } from "@/services/orderService";
import { Loader2, ArrowLeft } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import SearchCTA from "@/components/SearchCTA";

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

export default function OrderDetailPage() {
  const params = useParams();
  const router = useRouter();
  const orderRef = params?.id as string; // we use the dynamic param 'id' to carry the reference
  
  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadOrder = async () => {
      if (!orderRef) return;
      
      try {
        setLoading(true);
        const response = await orderService.getOrderByReference(orderRef);
        setOrder(response.data);
        setError(null);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load order');
        console.error('Error loading order:', err);
      } finally {
        setLoading(false);
      }
    };

    loadOrder();
  }, [orderRef]);

  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 exportInvoice = () => {
    if (!order) return;

    // Create invoice HTML content
    const invoiceHTML = `
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>فاتورة #${order.order_number}</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; padding: 40px; background: #f5f5f5; }
    .invoice { max-width: 800px; margin: 0 auto; background: white; padding: 40px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
    .header { border-bottom: 3px solid #2563eb; padding-bottom: 20px; margin-bottom: 30px; }
    .header h1 { color: #1e40af; font-size: 32px; margin-bottom: 10px; }
    .header .subtitle { color: #64748b; font-size: 14px; }
    .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-bottom: 30px; }
    .info-box { background: #f8fafc; padding: 15px; border-radius: 8px; border-right: 4px solid #3b82f6; }
    .info-box h3 { color: #1e40af; font-size: 14px; margin-bottom: 8px; font-weight: 600; }
    .info-box p { color: #475569; font-size: 13px; line-height: 1.6; }
    .reference-box { background: #dbeafe; border: 2px solid #3b82f6; padding: 15px; border-radius: 8px; margin: 20px 0; text-align: center; }
    .reference-box .ref-label { color: #1e40af; font-size: 12px; margin-bottom: 5px; }
    .reference-box .ref-number { color: #1e40af; font-size: 24px; font-weight: bold; font-family: monospace; }
    table { width: 100%; border-collapse: collapse; margin: 20px 0; }
    thead { background: #f1f5f9; }
    th { padding: 12px; text-align: right; font-weight: 600; color: #1e293b; border-bottom: 2px solid #cbd5e1; }
    td { padding: 12px; text-align: right; border-bottom: 1px solid #e2e8f0; color: #475569; }
    tbody tr:hover { background: #f8fafc; }
    .totals { margin-top: 30px; border-top: 2px solid #e2e8f0; padding-top: 20px; }
    .totals-row { display: flex; justify-content: space-between; padding: 8px 0; font-size: 14px; }
    .totals-row.total { font-size: 18px; font-weight: bold; color: #1e40af; border-top: 2px solid #3b82f6; margin-top: 10px; padding-top: 15px; }
    .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #e2e8f0; text-align: center; color: #64748b; font-size: 12px; }
    .status-badge { display: inline-block; padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
    .status-paid { background: #dcfce7; color: #166534; }
    .status-pending { background: #fef3c7; color: #92400e; }
    @media print {
      body { padding: 0; background: white; }
      .invoice { box-shadow: none; }
      @page { margin: 20mm; }
    }
  </style>
</head>
<body>
  <div class="invoice">
    <div class="header">
      <h1>فاتورة</h1>
      <p class="subtitle">رقم الطلب: #${order.order_number}</p>
      <p class="subtitle">تاريخ الإصدار: ${new Date(order.created_at).toLocaleDateString('ar-SA-u-ca-gregory', { year: 'numeric', month: 'long', day: 'numeric' })}</p>
    </div>

    <div class="reference-box">
      <div class="ref-label">الرقم المرجعي</div>
      <div class="ref-number">${order.reference_number}</div>
    </div>

    <div class="info-grid">
      <div class="info-box">
        <h3>معلومات العميل</h3>
        <p><strong>${order.shipping_address.first_name} ${order.shipping_address.last_name}</strong></p>
        <p>${order.shipping_address.street}</p>
        <p>${order.shipping_address.city}, ${order.shipping_address.state} ${order.shipping_address.zip_code}</p>
        ${order.shipping_address.phone ? `<p>هاتف: ${order.shipping_address.phone}</p>` : ''}
      </div>

      <div class="info-box">
        <h3>معلومات الدفع</h3>
        <p><strong>طريقة الدفع:</strong> ${order.payment_method === 'card' ? 'بطاقة ائتمان' : 'الدفع عند الاستلام'}</p>
        <p><strong>حالة الدفع:</strong> <span class="status-badge ${order.payment_status === 'paid' ? 'status-paid' : 'status-pending'}">${order.payment_status === 'paid' ? 'مدفوع' : 'قيد الانتظار'}</span></p>
        <p><strong>حالة الطلب:</strong> ${orderService.getStatusDisplay(order.status)}</p>
      </div>
    </div>

    <table>
      <thead>
        <tr>
          <th>المنتج</th>
          <th>المواصفات</th>
          <th>الكمية</th>
          <th>السعر</th>
          <th>المجموع</th>
        </tr>
      </thead>
      <tbody>
        ${order.items.map(item => `
          <tr>
            <td><strong>${item.product_variant.product.name}</strong></td>
            <td>الحجم: ${item.product_variant.size} | اللون: ${item.product_variant.color}</td>
            <td>${item.quantity}</td>
            <td>$${Number(item.price).toFixed(2)}</td>
            <td>$${(Number(item.price) * item.quantity).toFixed(2)}</td>
          </tr>
        `).join('')}
      </tbody>
    </table>

    <div class="totals">
      <div class="totals-row">
        <span>المجموع الفرعي:</span>
        <span>$${(Number(order.total_amount) + Number(order.discount_amount)).toFixed(2)}</span>
      </div>
      ${Number(order.discount_amount) > 0 ? `
      <div class="totals-row">
        <span>الخصم:</span>
        <span style="color: #dc2626;">-$${Number(order.discount_amount).toFixed(2)}</span>
      </div>
      ` : ''}
      <div class="totals-row">
        <span>التوصيل:</span>
        <span>مجاني</span>
      </div>
      <div class="totals-row total">
        <span>الإجمالي:</span>
        <span>$${Number(order.total_amount).toFixed(2)}</span>
      </div>
    </div>

    <div class="footer">
      <p>شكراً لتسوقك معنا!</p>
      <p>للاستفسارات، يرجى التواصل معنا باستخدام الرقم المرجعي: ${order.reference_number}</p>
    </div>
  </div>
</body>
</html>
    `;

    // Create a blob and download
    const blob = new Blob([invoiceHTML], { type: 'text/html' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `invoice-${order.order_number}.html`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    // Open in new window for printing
    const printWindow = window.open('', '_blank');
    if (printWindow) {
      printWindow.document.write(invoiceHTML);
      printWindow.document.close();
    }
  };

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

  if (error || !order) {
    return (
      <div className="min-h-screen pt-6 sm:pt-9 lg:pt-[55px]">
        <Card className="p-8 text-center max-w-2xl mx-auto">
          <p className="text-red-500 mb-4">{error || 'الطلب غير موجود'}</p>
          <Button onClick={() => router.push('/order')} className="flex-row-reverse">
            العودة إلى الطلبات
            <ArrowLeft className="ml-2 h-4 w-4" />
          </Button>
        </Card>
      </div>
    );
  }

  return (
    <div className="pt-6 sm:pt-9 lg:pt-[55px] space-y-[140px]">
      <div className="px-4 md:px-6">
        <div className="w-full max-w-[1240px] mx-auto">
          {/* Back Button */}
          <Button 
            variant="ghost" 
            onClick={() => router.push('/order')}
            className="mb-6 flex-row-reverse"
          >
            العودة إلى الطلبات
            <ArrowLeft className="ml-2 h-4 w-4" />
          </Button>

          {/* 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="grid grid-cols-1 md:grid-cols-2 gap-6">
              

           
                <div>
                <p className="text-sm text-gray-600 mb-1">رقم الطلب</p>
                <h2 className="text-2xl md:text-3xl font-bold text-gray-900">
                  #{order.order_number}
                </h2>
                <p className="text-sm text-gray-500 mt-1">
                  تم الطلب في {new Date(order.created_at).toLocaleString('ar-SA-u-ca-gregory', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: true
                  })}
                </p>
                
                {/* Reference Number Box */}
                <div className="bg-white border-2 border-blue-300 rounded-lg p-3 mt-4">
                  <p className="text-xs text-gray-600 mb-1">الرقم المرجعي</p>
                  <p className="font-mono font-bold text-blue-600 text-lg">{order.reference_number}</p>
                  <p className="text-xs text-gray-500 mt-1">استخدم هذا الرقم المرجعي لدعم العملاء</p>
                </div>
              </div>
                 <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 ${
                  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-sm text-gray-500 mt-2">
                  الدفع: {order.payment_method === 'card' ? 'بطاقة' : 'الدفع عند الاستلام'}
                    </p>
                    <p className="text-sm text-gray-500">
                  حالة الدفع: {order.payment_status === 'paid' ? 'مدفوع' : 'قيد الانتظار'}
                    </p>
                </div>
            </div>
          </Card>

          {/* Order Status Timeline */}
          <OrderStatus 
            currentStatus={order.status as "ordered" | "shipped" | "delivered"}
            orderNumber={order.reference_number}
            orderDate={new Date(order.created_at).toLocaleString('ar-SA-u-ca-gregory', {
              year: 'numeric',
              month: 'short',
              day: 'numeric'
            })}
            estimatedDelivery={new Date(new Date(order.created_at).getTime() + 5 * 24 * 60 * 60 * 1000).toLocaleDateString('ar-SA-u-ca-gregory', {
              year: 'numeric',
              month: 'short',
              day: 'numeric'
            })}
            onExportInvoice={exportInvoice}
            createdAt={order.created_at}
          />

          {/* Order Details */}
          <Card className="pl-[17px] pr-[21px] md:px-[22px] py-[26px] md:py-[30px]">
            <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">
                عناصر الطلب
              </h3>

              <div className="space-y-[17px] sm:space-y-7 lg:space-y-10">
                {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",
                    }} 
                  />
                ))}
              </div>
            </div>

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

            <div className="flex items-start gap-8 sm:gap-[50px] md:mt-8 my-6 md:mb-14">
              {/* 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">
                    {order.payment_method === 'card' ? 'بطاقة ائتمان' : 'الدفع عند الاستلام'}
                  </h4>
                  {order.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">
                  الحالة: {order.payment_status === 'paid' ? 'مدفوع' : 'قيد الانتظار'}
                </p>
              </div>

              {/* 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">
                    {order.shipping_address.first_name} {order.shipping_address.last_name}
                  </span>
                  <TypographyH3 className="max-w-[215px] text-[14px] sm:text-[20px] leading-[22px] sm:leading-7 font-medium">
                    {order.shipping_address.street}, {order.shipping_address.city}, {order.shipping_address.state} {order.shipping_address.zip_code}
                  </TypographyH3>
                  {order.shipping_address.phone && (
                    <p className="text-sm text-gray-500 mt-1">{order.shipping_address.phone}</p>
                  )}
                </div>
              </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-[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 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(order.total_amount) + Number(order.discount_amount)).toFixed(2)}
                    </TypographyH3>
                  </div>
                  {Number(order.discount_amount) > 0 && (
                    <div className="flex items-center justify-between">
                      <TypographyH4>الخصم</TypographyH4>
                      <TypographyH4 className="text-[10px] sm:text-[18px]">
                        -${Number(order.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(order.total_amount).toFixed(2)}
                    </TypographyH3>
                  </div>
                </div>
              </div>
            </div>
          </Card>
        </div>
      </div>
      
      <SearchCTA />
    </div>
  );
}
