'use client';

import Link from 'next/link';
import 'bootstrap/dist/css/bootstrap.min.css';
import { useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { useRouter, useParams } from 'next/navigation';
import Image from "next/image";
import { useSession } from 'next-auth/react';
import { AccountSidebar } from '../../dashboard/AccountSidebar';

interface OrderProduct {
    id: number;
    product_name?: string;
    product_image?: { image: string } | string;
    quantity: number;
    price: string | number;
    product_qty?: number;
    product_price?: number | string;
    product_size?: string;
    productdetail?: {
        attributes?: Array<{
            id: number;
            size?: string;
            price?: string | number;
            stock?: string | number;
            sku?: string;
        }>;
        product_image?: { image: string } | string;
    };
}

interface Order {
    id: number;
    order_status: string;
    grand_total: string;
    created_at: string;
    order_products: OrderProduct[];
}

interface SelectedItem {
    productId: number;
    quantity: number;
    maxQuantity: number;
    actionType?: 'exchange' | 'return';
    selectedAttributeId?: number;
}

export default function ExchangeReturnPage({ params }: { params: Promise<{ id: string }> }) {
    const router = useRouter();
    const { id: orderId } = useParams();
    const { data: session } = useSession();
    const token = session?.user?.token;

    const [order, setOrder] = useState<Order | null>(null);
    const [loading, setLoading] = useState(true);
    const [submitting, setSubmitting] = useState(false);

    // Form State
    const [reason, setReason] = useState<string>('');
    const [comments, setComments] = useState<string>('');
    const [selectedItems, setSelectedItems] = useState<SelectedItem[]>([]);

    const reasonOptions = [
        'Damaged or Defective',
        'Wrong Item Received',
        'Size/Fit Issue',
        'Quality Issue',
        'Changed My Mind',
        'Other'
    ];

    // Fetch Order Details
    useEffect(() => {
        console.log("Fetching order details for orderId:", orderId);
        const fetchOrderDetails = async () => {
            if (!orderId) return;
            setLoading(true);
            try {
                const token = session?.user?.token;
                const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/user/order-detail/${orderId}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        Authorization: `Bearer ${token}`,
                    }
                });
                
                if (!res.ok) throw new Error('Failed to fetch order');
                
                const orderData = await res.json();
                console.log("exchange order details : ", orderData);
                
                setOrder(orderData?.data);
                
                // Initialize selected items with 0 quantity
                const initialItems = orderData?.data?.order_products.map((product: OrderProduct) => ({
                    productId: product.id,
                    quantity: 0,
                    maxQuantity: product.product_qty || product.quantity || 0,
                    actionType: undefined,
                    selectedAttributeId: undefined
                }));
                setSelectedItems(initialItems || []);
            } catch (error) {
                console.error("Fetch error:", error);
                toast.error("Failed to load order details.");
            } finally {
                setLoading(false);
            }
        };

        fetchOrderDetails();
    }, [orderId, session?.user?.token]);

    const handleQuantityChange = (productId: number, newQuantity: number) => {
        setSelectedItems(prev => prev.map(item => {
            if (item.productId === productId) {
                // Ensure minimum quantity is 1 when actionType is set
                const minQty = item.actionType ? 1 : 0;
                const validQty = Math.max(minQty, Math.min(newQuantity, item.maxQuantity));
                return { ...item, quantity: validQty };
            }
            return item;
        }));
    };

    const handleActionTypeChange = (productId: number, action: 'exchange' | 'return') => {
        setSelectedItems(prev => prev.map(item => {
            if (item.productId === productId) {
                // When action is selected, set quantity to 1 if it's 0
                const newQuantity = item.quantity === 0 ? 1 : item.quantity;
                return { ...item, actionType: action, quantity: newQuantity };
            }
            return item;
        }));
    };

    const handleAttributeChange = (productId: number, attributeId: number) => {
        setSelectedItems(prev => prev.map(item => {
            if (item.productId === productId) {
                return { ...item, selectedAttributeId: attributeId };
            }
            return item;
        }));
    };

    const getSelectedProductDetails = () => {
        if (!order) return [];
        return selectedItems
            .filter(item => item.quantity > 0 && item.actionType)
            .map(item => {
                const product = order.order_products.find(p => p.id === item.productId);
                return {
                    productId: item.productId,
                    productName: product?.product_name,
                    quantity: item.quantity,
                    actionType: item.actionType,
                    selectedAttributeId: item.selectedAttributeId
                };
            });
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        const selectedProducts = getSelectedProductDetails();

        if (selectedProducts.length === 0) {
            toast.error("Please select at least one product to exchange or return.");
            return;
        }

        // Check if exchange products have attribute selected
        const exchangeProductsWithNoAttribute = selectedProducts.filter(
            p => p.actionType === 'exchange' && !p.selectedAttributeId
        );

        if (exchangeProductsWithNoAttribute.length > 0) {
            toast.error("Please select replacement option for exchange products.");
            return;
        }

        if (!reason) {
            toast.error("Please select a reason for your request.");
            return;
        }

        setSubmitting(true);
        try {
            const token = session?.user?.token;
            
            const exchangeProducts = selectedProducts.filter(p => p.actionType === 'exchange');
            const returnProducts = selectedProducts.filter(p => p.actionType === 'return');

            let payload;
            
            if (exchangeProducts.length > 0 && returnProducts.length > 0) {
                payload = {
                    order_id: orderId,
                    action_type: 'mixed',
                    exchange_products: exchangeProducts.map(p => ({
                        product_id: p.productId,
                        quantity: p.quantity,
                        attribute_id: p.selectedAttributeId
                    })),
                    return_products: returnProducts.map(p => ({
                        product_id: p.productId,
                        quantity: p.quantity
                    })),
                    reason: reason,
                    comments: comments
                };
            } else if (exchangeProducts.length > 0) {
                payload = {
                    order_id: orderId,
                    action_type: 'exchange',
                    products: exchangeProducts.map(p => ({
                        product_id: p.productId,
                        quantity: p.quantity,
                        attribute_id: p.selectedAttributeId
                    })),
                    reason: reason,
                    comments: comments
                };
            } else {
                payload = {
                    order_id: orderId,
                    action_type: 'return',
                    products: returnProducts.map(p => ({
                        product_id: p.productId,
                        quantity: p.quantity
                    })),
                    reason: reason,
                    comments: comments
                };
            }

            const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/user/exchange-return`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${token}`,
                },
                body: JSON.stringify(payload)
            });

            const data = await res.json();

            if (res.ok) {
                const actionText = exchangeProducts.length > 0 && returnProducts.length > 0 
                    ? 'Exchange and Return' 
                    : exchangeProducts.length > 0 ? 'Exchange' : 'Return';
                toast.success(`${actionText} request submitted successfully!`);
                router.push('/user/dashboard');
            } else {
                toast.error(data.message || "Failed to submit request. Please try again.");
            }
        } catch (error) {
            console.error("Submit error:", error);
            toast.error("An unexpected error occurred.");
        } finally {
            setSubmitting(false);
        }
    };

    // Modern UI Styles Injection based on provided design
    const pageStyles = `
        body {
            background: #f7f7f7;
            font-family: Arial, sans-serif;
        }
        .page-wrapper {
            max-width: 1100px;
            margin: 40px auto;
        }
        .card-box {
            background: #fff;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 2px 12px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        .product-card {
            border: 1px solid #e5e5e5;
            border-radius: 10px;
            padding: 18px;
            margin-bottom: 15px;
            transition: .2s;
        }
        .product-card.selected {
            border-color: #111;
            background: #fafafa;
        }
        .product-image {
            width: 100px;
            height: 120px;
            object-fit: cover;
            border-radius: 8px;
            background: #eee;
        }
        .product-name {
            font-size: 17px;
            font-weight: 600;
        }
        .product-meta {
            color: #777;
            font-size: 14px;
        }
        .price {
            font-weight: 600;
            font-size: 16px;
        }
        .action-buttons button {
            min-width: 100px;
            margin-right:10px;
        }
        .qty-control {
            display: inline-flex;
            align-items: center;
            border: 1px solid #ddd;
            border-radius: 6px;
            overflow: hidden;
        }
        .qty-control button {
            width: 35px;
            height: 35px;
            border: 0;
            background: #f5f5f5;
            cursor: pointer;
        }
        .qty-control button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .qty-control span {
            width: 40px;
            text-align: center;
        }
        .reason-box {
            display: none;
            margin-top: 15px;
            padding: 15px;
            background: #f8f8f8;
            border-radius: 8px;
        }
        .selected .reason-box {
            display: block;
        }
        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }
        .summary-item:last-child {
            border-bottom: 0;
        }
        .status-badge {
            font-size: 12px;
            padding: 5px 10px;
            border-radius: 20px;
            font-weight: 600;
        }
        .status-delivered {
            background: #e8f7ed;
            color: #198754;
        }
        .status-pending {
            background: #fff4d6;
            color: #a26b00;
        }
        .status-selected-exchange {
            background: #e5f0ff;
            color: #0d6efd;
        }
        .status-selected-return {
            background: #fff4d6;
            color: #a26b00;
        }
        .window-alert {
            background: #fff8e1;
            border: 1px solid #ffe08a;
            border-radius: 8px;
            padding: 12px 15px;
            font-size: 14px;
        }
        .step {
            text-align: center;
            position: relative;
            flex: 1;
        }
        .step-circle {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background: #111;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: auto;
            font-size: 14px;
        }
        .step-label {
            margin-top: 8px;
            font-size: 12px;
            color: #666;
        }
        .steps-line {
            height: 2px;
            background: #ddd;
            flex: 1;
            margin-top: 17px;
        }
        .exchange-fields {
            display: none;
        }
        .selected-exchange .exchange-fields {
            display: block;
        }
        @media(max-width: 768px) {
            .page-wrapper {
                margin: 20px 10px;
            }
            .product-image {
                width: 80px;
                height: 100px;
            }
        }
    `;

    if (loading) {
        return (
            <main className="main" style={{ background: '#f7f7f7', minHeight: '100vh' }}>
                <style>{pageStyles}</style>
                <section id="account" className="account section py-5">
                    <div className='container'>
                        <div className="row g-4">
                            <div className="col-lg-3">
                                <AccountSidebar />
                            </div>
                            <div className="col-lg-9">
                                <div className="card-box text-center py-5">
                                    <div className="spinner-border text-primary" style={{width: '3rem', height: '3rem'}} role="status">
                                        <span className="visually-hidden">Loading...</span>
                                    </div>
                                    <p className="mt-3 text-muted fw-medium">Loading order details...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>
            </main>
        );
    }

    if (!order) {
        return (
            <main className="main" style={{ background: '#f7f7f7', minHeight: '100vh' }}>
                <style>{pageStyles}</style>
                <section id="account" className="account section py-5">
                    <div className='container'>
                        <div className="row g-4">
                            <div className="col-lg-3">
                                <AccountSidebar />
                            </div>
                            <div className="col-lg-9">
                                <div className="card-box text-center py-5">
                                    <div className="mb-3">
                                        <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#EF5350" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                            <circle cx="12" cy="12" r="10"></circle>
                                            <line x1="12" y1="8" x2="12" y2="12"></line>
                                            <line x1="12" y1="16" x2="12.01" y2="16"></line>
                                        </svg>
                                    </div>
                                    <h3 className="fw-bold mb-2 text-primary">Order Not Found</h3>
                                    <p className="text-muted mb-4">The order you are looking for does not exist or you do not have permission to view it.</p>
                                    <Link href="/user/dashboard" className="btn btn-primary px-4">
                                        Back to My Orders
                                    </Link>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>
            </main>
        );
    }

    // Calculate return window (7 days from order date)
    const orderDate = new Date(order.created_at);
    const returnWindowDate = new Date(orderDate);
    returnWindowDate.setDate(returnWindowDate.getDate() + 7);

    const isDelivered = order.order_status === 'Delivered';

    // Helper function to get image URL
    const getImageUrl = (product: OrderProduct) => {
        const detailImage = product?.productdetail?.product_image;
        if (detailImage) {
            if (typeof detailImage === 'string') {
                return detailImage;
            }
            if (detailImage.image) {
                return detailImage.image;
            }
        }
        if (typeof product?.product_image === 'string') {
            return product.product_image;
        }
        if (product?.product_image?.image) {
            return product.product_image.image;
        }
        return '/placeholder.jpg';
    };

    // Helper function to get attributes
    const getAttributes = (product: OrderProduct) => {
        return product?.productdetail?.attributes || [];
    };

    return (
        <main className="main" style={{ background: '#f7f7f7', minHeight: '100vh' }}>
            <style>{pageStyles}</style>
            <section id="account" className="account section py-5">
                <div className='container'>
                    <div className="row g-4">
                        {/* Sidebar */}
                        <div className="col-lg-3">
                            <AccountSidebar />
                        </div>
                        
                        {/* Main Content */}
                        <div className="col-lg-9">
                            <div className="page-wrapper" style={{ margin: 0 }}>
                                <form onSubmit={handleSubmit}>
                                    {/* HEADER */}
                                    <div className="card-box">
                                        <div className="d-flex justify-content-between align-items-center flex-wrap gap-2">
                                            <div>
                                                <h4 className="mb-1">Return / Exchange</h4>
                                                <div className="text-muted">
                                                    Order #{order.id}
                                                </div>
                                            </div>
                                            <span className={`status-badge ${order.order_status === 'Delivered' ? 'status-delivered' : 'status-pending'}`}>
                                                {order.order_status}
                                            </span>
                                        </div>

                                        <hr />

                                        <div className="row">
                                            <div className="col-md-4">
                                                <small className="text-muted">Order Date</small>
                                                <div>{new Date(order.created_at).toLocaleDateString("en-IN", {
                                                    year: "numeric", month: "long", day: "numeric"
                                                })}</div>
                                            </div>
                                            <div className="col-md-4">
                                                <small className="text-muted">Delivered Date</small>
                                                <div>{isDelivered ? new Date(order.created_at).toLocaleDateString("en-IN", {
                                                    year: "numeric", month: "long", day: "numeric"
                                                }) : 'Not delivered yet'}</div>
                                            </div>
                                            <div className="col-md-4">
                                                <small className="text-muted">Return Window</small>
                                                <div>Until {returnWindowDate.toLocaleDateString("en-IN", {
                                                    year: "numeric", month: "long", day: "numeric"
                                                })}</div>
                                            </div>
                                        </div>
                                    </div>

                                    {/* RETURN WINDOW */}
                                    <div className="card-box">
                                        <div className="window-alert">
                                            <strong>Return / Exchange window:</strong>
                                            You can request a return or exchange until
                                            <strong> {returnWindowDate.toLocaleDateString("en-IN", {
                                                year: "numeric", month: "long", day: "numeric"
                                            })}</strong>.
                                            {!isDelivered && (
                                                <span className="ms-2 text-danger">(Order must be delivered first)</span>
                                            )}
                                        </div>
                                    </div>

                                    {/* PRODUCTS */}
                                    <div className="card-box">
                                        <div className="d-flex justify-content-between align-items-center mb-3">
                                            <h5 className="mb-0">Select Products</h5>
                                            <span className="text-muted small">
                                                You can select multiple products
                                            </span>
                                        </div>

                                        {order.order_products.map((product) => {
                                            const selectedItem = selectedItems.find(i => i.productId === product.id);
                                            const isActive = selectedItem?.quantity && selectedItem.quantity > 0;
                                            const isExchange = selectedItem?.actionType === 'exchange';
                                            const isReturn = selectedItem?.actionType === 'return';
                                            const maxQty = product.product_qty || product.quantity || 0;
                                            const attributes = getAttributes(product);
                                            // Only show quantity control if maxQty > 1
                                            const showQuantityControl = maxQty > 1;
                                            // Get current product size
                                            const currentSize = product.product_size || '';

                                            return (
                                                <div 
                                                    key={product.id} 
                                                    className={`product-card ${isActive ? 'selected' : ''} ${isExchange ? 'selected-exchange' : ''}`}
                                                    id={`product-${product.id}`}
                                                >
                                                    <div className="row align-items-center">
                                                        <div className="col-auto">
                                                            <Image 
                                                                src={getImageUrl(product)}
                                                                alt={product.product_name || 'Product'} 
                                                                width={100} 
                                                                height={120} 
                                                                className="product-image"
                                                            />
                                                        </div>
                                                        <div className="col">
                                                            <div className="product-name">
                                                                {product.product_name}
                                                            </div>
                                                            <div className="product-meta">
                                                                Quantity: {maxQty}
                                                                {currentSize && ` | Size: ${currentSize}`}
                                                            </div>
                                                            <div className="price mt-2">
                                                                ₹{Math.round(Number(product.product_price || product.price || 0))} × {maxQty}
                                                            </div>
                                                        </div>
                                                        <div className="col-md-auto mt-3 mt-md-0">
                                                            <div className="action-buttons">
                                                                {/* <button
                                                                    type="button"
                                                                    className={`btn ${isReturn ? 'btn-dark' : 'btn-outline-dark'} btn-sm`}
                                                                    onClick={() => handleActionTypeChange(product.id, 'return')}
                                                                >
                                                                    Return
                                                                </button> */}
                                                                <button
                                                                    type="button"
                                                                    className={`btn ${isExchange ? 'btn-dark' : 'btn-outline-dark'} btn-sm`}
                                                                    onClick={() => handleActionTypeChange(product.id, 'exchange')}
                                                                >
                                                                    Exchange
                                                                </button>
                                                            </div>
                                                            {isActive && (
                                                                <div className="mt-2">
                                                                    <span className={`status-badge ${isExchange ? 'status-selected-exchange' : 'status-selected-return'}`}>
                                                                        {isExchange ? 'Exchange' : 'Return'} Selected
                                                                    </span>
                                                                </div>
                                                            )}
                                                        </div>
                                                    </div>

                                                    {/* PRODUCT ACTION AREA */}
                                                    <div className="reason-box">
                                                        <div className="row g-3">
                                                            <div className="col-md-4">
                                                                <label className="form-label">Quantity</label>
                                                                {showQuantityControl ? (
                                                                    <div className="qty-control">
                                                                        <button 
                                                                            type="button"
                                                                            onClick={() => handleQuantityChange(product.id, (selectedItem?.quantity || 0) - 1)}
                                                                            disabled={(selectedItem?.quantity || 0) <= 1 || (selectedItem?.quantity || 0) === 0}
                                                                        >
                                                                            −
                                                                        </button>
                                                                        <span id={`qty-${product.id}`}>{selectedItem?.quantity || 0}</span>
                                                                        <button 
                                                                            type="button"
                                                                            onClick={() => handleQuantityChange(product.id, (selectedItem?.quantity || 0) + 1)}
                                                                            disabled={(selectedItem?.quantity || 0) >= maxQty}
                                                                        >
                                                                            +
                                                                        </button>
                                                                    </div>
                                                                ) : (
                                                                    <div className="fw-bold">
                                                                        {selectedItem?.quantity || 0}
                                                                    </div>
                                                                )}
                                                                <div className="small text-muted mt-1">
                                                                    Maximum: {maxQty}
                                                                </div>
                                                            </div>

                                                            <div className="col-md-8">
                                                                <label className="form-label">Reason</label>
                                                                <select 
                                                                    className="form-select" 
                                                                    value={reason}
                                                                    onChange={(e) => setReason(e.target.value)}
                                                                >
                                                                    <option value="">Select reason</option>
                                                                    {reasonOptions.map(opt => (
                                                                        <option key={opt} value={opt}>{opt}</option>
                                                                    ))}
                                                                </select>
                                                            </div>
                                                        </div>

                                                        {/* EXCHANGE FIELDS */}
                                                        <div className="exchange-fields mt-3">
                                                            <label className="form-label">
                                                                Select Replacement Option
                                                            </label>
                                                            <select 
                                                                className="form-select"
                                                                value={selectedItem?.selectedAttributeId || ''}
                                                                onChange={(e) => handleAttributeChange(product.id, Number(e.target.value))}
                                                            >
                                                                <option value="">Select option</option>
                                                                {attributes.map((attr) => {
                                                                    // Check if this attribute size matches the current product size
                                                                    const isSameSize = !!(
                                                                        attr.size &&
                                                                        currentSize &&
                                                                        attr.size.toString() === currentSize.toString()
                                                                    );
                                                                    // Disable option if it's the same size
                                                                    return (
                                                                        <option 
                                                                            key={attr.id} 
                                                                            value={attr.id}
                                                                            disabled={isSameSize}
                                                                        >
                                                                            {attr.size} {isSameSize ? '(Current Size - Not Available)' : ''}
                                                                        </option>
                                                                    );
                                                                })}
                                                            </select>
                                                            {attributes.length === 0 && (
                                                                <div className="small text-muted mt-1">
                                                                    No replacement options available for this product.
                                                                </div>
                                                            )}
                                                            <div className="small text-muted mt-1">
                                                                Note: Exchange options will be available based on inventory.
                                                            </div>
                                                        </div>

                                                        <div className="mt-3">
                                                            <label className="form-label">Additional Comment</label>
                                                            <textarea
                                                                className="form-control"
                                                                rows={2}
                                                                placeholder="Tell us more..."
                                                                value={comments}
                                                                onChange={(e) => setComments(e.target.value)}
                                                            ></textarea>
                                                        </div>

                                                        <div className="mt-3">
                                                            <button
                                                                type="button"
                                                                className="btn btn-sm btn-outline-danger"
                                                                onClick={() => {
                                                                    handleQuantityChange(product.id, 0);
                                                                    // Reset action type
                                                                    setSelectedItems(prev => prev.map(item => 
                                                                        item.productId === product.id 
                                                                            ? { ...item, actionType: undefined, quantity: 0, selectedAttributeId: undefined } 
                                                                            : item
                                                                    ));
                                                                }}
                                                            >
                                                                Remove Selection
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>

                                    {/* REQUEST SUMMARY */}
                                    <div className="card-box">
                                        <h5 className="mb-3">Request Summary</h5>
                                        <div id="summary">
                                            {getSelectedProductDetails().length === 0 ? (
                                                <div className="text-muted">No products selected.</div>
                                            ) : (
                                                <>
                                                    {getSelectedProductDetails().map((item, index) => {
                                                        const product = order.order_products.find(p => p.id === item.productId);
                                                        const amount = Number(product?.product_price || product?.price || 0) * item.quantity;
                                                        const selectedAttr = product?.productdetail?.attributes?.find(a => a.id === item.selectedAttributeId);
                                                        return (
                                                            <div key={index} className="summary-item">
                                                                <div>
                                                                    <strong>{item.productName}</strong>
                                                                    <div className="small text-muted">
                                                                        {item.actionType?.toUpperCase()} | Qty: {item.quantity}
                                                                        {selectedAttr && ` | Replacement: ${selectedAttr.size || selectedAttr.sku || ''}`}
                                                                    </div>
                                                                    <div className="small text-muted">
                                                                        Reason: {reason || 'Not selected'}
                                                                    </div>
                                                                </div>
                                                                <div className="text-end">
                                                                    ₹ { Math.round(Number(amount || 0)) }
                                                                </div>
                                                            </div>
                                                        );
                                                    })}
                                                    {/* <div className="mt-3 pt-2 border-top">
                                                        <div className="d-flex justify-content-between">
                                                            <strong>Estimated Refund</strong>
                                                            <strong>
                                                                ₹{getSelectedProductDetails()
                                                                    .filter(item => item.actionType === 'return')
                                                                    .reduce((total, item) => {
                                                                        const product = order.order_products.find(p => p.id === item.productId);
                                                                        return total + (Math.round(Number(product?.product_price || product?.price || 0)) * item.quantity);
                                                                    }, 0)
                                                                    .toLocaleString("en-IN")}
                                                            </strong>
                                                        </div>
                                                        <div className="small text-muted mt-1">
                                                            Final refund may change after inspection and applicable discount/tax adjustments.
                                                        </div>
                                                    </div> */}
                                                </>
                                            )}
                                        </div>
                                    </div>

                                    {/* SUBMIT */}
                                    <div className="card-box">
                                        <div className="row align-items-center">
                                            <div className="col-md">
                                                <div className="fw-semibold">Ready to submit?</div>
                                                <div className="text-muted small">
                                                    Make sure the selected products and quantities are correct.
                                                </div>
                                            </div>
                                            <div className="col-md-auto mt-3 mt-md-0">
                                                <button
                                                    type="submit"
                                                    className="btn btn-dark px-4 d-flex align-items-center gap-2"
                                                    disabled={submitting || getSelectedProductDetails().length === 0 || !isDelivered}
                                                >
                                                    {submitting ? (
                                                        <>
                                                            <span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                                                            Submitting...
                                                        </>
                                                    ) : (
                                                        'Submit Return / Exchange Request'
                                                    )}
                                                </button>
                                                {!isDelivered && (
                                                    <div className="small text-danger mt-1">
                                                        Order must be delivered to request return/exchange.
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </main>
    );
}