// app/components/admin/orders/OrderDetailModal.tsx
'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import {
  Order,
  OrderItem,
  PackageOrderItem,
  OrderItemDetail,
  LiveLink,
  OrderDocument,
  AssignedWebsite,
} from '@/types/order';
import toast from 'react-hot-toast';

interface OrderDetailModalProps {
  order: Order;
  onClose: () => void;
}

// FIX: Only order-level statuses are valid per schema.
// order_items and package_order_items do NOT have a status column.
const ORDER_STATUS_COLOR_MAP: Record<string, string> = {
  pending: 'bg-var-warning-bg text-var-warning-text',
  confirmed: 'bg-var-primary-muted text-var-primary-text',
  pending_review: 'bg-var-info-bg text-var-info-text',
  completed: 'bg-var-success-bg text-var-success-text',
  cancelled: 'bg-var-danger-bg text-var-danger-text',
  paid: 'bg-var-success-bg text-var-success-text',
  failed: 'bg-var-danger-bg text-var-danger-text',
  refunded: 'bg-var-surface-hover text-var-text-muted',
} as const;

// Live link display uses the JSONB object shape from live_links in order_items.
// Schema: live_links JSONB DEFAULT '[]'
// Each entry: { url: string, submitted_at: string }
// FIX: No link-level 'status' exists in schema — removed from rendering.

function getStatusColor(status: string): string {
  return ORDER_STATUS_COLOR_MAP[status] ?? 'bg-var-surface-hover text-var-text-muted';
}

function getCustomerName(user: Order['user']): string {
  if (!user) return 'Guest';
  return (
    user.display_name ||
    [user.first_name, user.last_name].filter(Boolean).join(' ') ||
    user.email ||
    'Guest'
  );
}

function formatDate(dateString: string): string {
  return new Date(dateString).toLocaleString();
}

function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'] as const;
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
}

function isUrl(str: string): boolean {
  try {
    new URL(str);
    return true;
  } catch {
    return false;
  }
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function RejectionBanner({ reason }: { reason: string }) {
  return (
    <div className="mt-3 pt-3 border-t border-var-danger-border bg-var-danger-bg rounded-lg p-3">
      <div className="flex items-start">
        <svg
          className="w-4 h-4 text-var-danger mt-0.5 mr-2 shrink-0"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
          />
        </svg>
        <div>
          <p className="text-sm font-medium text-var-danger-text">Rejection Reason:</p>
          <p className="text-sm text-var-danger-text mt-1">{reason}</p>
        </div>
      </div>
    </div>
  );
}

// FIX: LiveLink shape matches schema — only url & submitted_at.
// Removed status badge rendering since status doesn't exist on individual links in DB.
function LiveLinksSection({ links }: { links: LiveLink[] }) {
  if (!links || !links.length) return null;

  return (
    <div className="mt-3 pt-3 border-t border-var-border">
      <span className="text-sm font-medium text-var-text">
        Live Links ({links.length}):
      </span>
      <div className="mt-2 space-y-2">
        {links.map((link, idx) => (
          <div
            key={`${link.url}-${idx}`}
            className="flex items-center justify-between bg-var-surface-hover p-2 rounded-lg"
          >
            <div className="flex-1">
              <a
                href={link.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-sm text-var-primary hover:underline break-all"
              >
                Link {idx + 1}: {link.url}
              </a>
              {link.submitted_at && (
                <p className="text-xs text-var-text-muted mt-1">
                  Submitted: {formatDate(link.submitted_at)}
                </p>
              )}
            </div>
            {/* FIX: No per-link status badge — status only exists at order level */}
          </div>
        ))}
      </div>
    </div>
  );
}

function ContentDetailsSection({ detail }: { detail: OrderItemDetail }) {
  return (
    <div className="mt-3 pt-3 border-t border-var-border">
      <h5 className="text-sm font-medium text-var-text mb-2">Content Writing Requirements</h5>
      <div className="space-y-2 text-sm">
        <div className="bg-var-primary-muted rounded-lg p-3">
          <span className="text-var-text-secondary font-medium">Desired Topic:</span>
          <p className="mt-1 text-var-text">{detail.desired_topic}</p>
        </div>
        {detail.target_keywords && (
          <div className="bg-var-info-bg rounded-lg p-3">
            <span className="text-var-text-secondary font-medium">Target Keywords:</span>
            <div className="mt-1 flex flex-wrap gap-2">
              {detail.target_keywords.split(',').map((keyword, idx) => (
                <span
                  key={idx}
                  className="inline-flex items-center px-2 py-1 bg-var-surface rounded-md text-xs text-var-text border border-var-border"
                >
                  {keyword.trim()}
                </span>
              ))}
            </div>
          </div>
        )}
        {detail.word_count && (
          <div className="bg-var-success-bg rounded-lg p-3">
            <span className="text-var-text-secondary font-medium">Word Count:</span>
            <p className="mt-1 text-var-text">{detail.word_count.toLocaleString()} words</p>
          </div>
        )}
        {detail.special_instructions && (
          <div className="bg-var-warning-bg rounded-lg p-3">
            <span className="text-var-text-secondary font-medium">Special Instructions:</span>
            <p className="mt-1 text-var-text whitespace-pre-wrap">
              {detail.special_instructions}
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

function DocumentsSection({ documents }: { documents: OrderDocument[] }) {
  if (!documents.length) return null;

  const urlDocuments = documents.filter(
    (doc) => doc.file_type === 'url' || isUrl(doc.file_path)
  );
  const fileDocuments = documents.filter(
    (doc) => doc.file_type !== 'url' && !isUrl(doc.file_path)
  );

  const handleDownload = async (filePath: string, fileName: string) => {
    try {
      const response = await fetch(filePath);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
      toast.success('File downloaded successfully');
    } catch (error) {
      console.error('Download error:', error);
      toast.error('Failed to download file');
    }
  };

  return (
    <div className="mt-3 pt-3 border-t border-var-border">
      {urlDocuments.length > 0 && (
        <>
          <h5 className="text-sm font-medium text-var-text mb-2">Submitted URLs</h5>
          <div className="space-y-2 mb-4">
            {urlDocuments.map((doc) => (
              <div
                key={doc.id}
                className="flex items-center justify-between bg-var-primary-muted p-3 rounded-lg"
              >
                <div className="flex-1">
                  <a
                    href={doc.file_path}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-sm text-var-primary hover:underline break-all"
                  >
                    {doc.file_name}: {doc.file_path}
                  </a>
                  <p className="text-xs text-var-text-muted mt-1">
                    Submitted: {formatDate(doc.uploaded_at)}
                  </p>
                </div>
                <div className="flex gap-2 ml-3 shrink-0">
                  <button
                    onClick={() => window.open(doc.file_path, '_blank')}
                    className="px-3 py-1.5 text-sm text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted rounded-lg transition-colors"
                  >
                    Open
                  </button>
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(doc.file_path);
                      toast.success('URL copied to clipboard');
                    }}
                    className="px-3 py-1.5 text-sm text-var-text-muted hover:text-var-text hover:bg-var-surface-hover rounded-lg transition-colors"
                  >
                    Copy
                  </button>
                </div>
              </div>
            ))}
          </div>
        </>
      )}

      {fileDocuments.length > 0 && (
        <>
          <h5 className="text-sm font-medium text-var-text mb-2">Uploaded Files</h5>
          <div className="space-y-2">
            {fileDocuments.map((doc) => (
              <div
                key={doc.id}
                className="flex items-center justify-between bg-var-surface-hover p-3 rounded-lg"
              >
                <div className="flex items-center gap-3 flex-1">
                  <FileTypeIcon fileType={doc.file_type} />
                  <div className="flex-1">
                    <p className="text-sm font-medium text-var-text">{doc.file_name}</p>
                    <p className="text-xs text-var-text-muted">
                      {formatFileSize(doc.file_size)} • Uploaded: {formatDate(doc.uploaded_at)}
                    </p>
                  </div>
                </div>
                <div className="flex gap-2 ml-3 shrink-0">
                  <button
                    onClick={() => window.open(doc.file_path, '_blank')}
                    className="px-3 py-1.5 text-sm text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted rounded-lg transition-colors"
                  >
                    View
                  </button>
                  <button
                    onClick={() => handleDownload(doc.file_path, doc.file_name)}
                    className="px-3 py-1.5 text-sm text-var-success hover:text-var-success-text hover:bg-var-success-bg rounded-lg transition-colors"
                  >
                    Download
                  </button>
                </div>
              </div>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

// FIX: Extracted icon into named component to avoid inline JSX in render
function FileTypeIcon({ fileType }: { fileType?: string }) {
  if (fileType?.includes('pdf')) {
    return (
      <svg className="w-8 h-8 text-var-danger shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 7h6M9 11h6M9 15h4" />
      </svg>
    );
  }
  if (fileType?.includes('image')) {
    return (
      <svg className="w-8 h-8 text-var-primary shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
      </svg>
    );
  }
  return (
    <svg className="w-8 h-8 text-var-text-muted shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
    </svg>
  );
}

// FIX: Removed item.status references — order_items has no status column.
// The order-level status badge is shown in the parent order info section instead.
function IndividualItemCard({
  item,
  detail,
  documents,
}: {
  item: OrderItem;
  detail?: OrderItemDetail;
  documents: OrderDocument[];
}) {
  const urlDocument = documents.find((doc) => doc.file_type === 'url' || isUrl(doc.file_path));
  const submittedUrl = urlDocument?.file_path || item.submitted_url;
  const hasDocument = documents.length > 0;

  return (
    <div className="border border-var-border rounded-xl p-4 hover:shadow-var-card transition-shadow">
      <div className="flex justify-between items-start mb-3">
        <div>
          <h4 className="font-medium text-var-text text-lg">
            {item.website_name || item.website?.name || 'Website'}
          </h4>
          {(item.website_url || item.website?.domain) && (
            <a
              href={`https://${item.website_url || item.website?.domain}`}
              target="_blank"
              rel="noopener noreferrer"
              className="text-sm text-var-primary hover:underline"
            >
              {item.website_url || item.website?.domain}
            </a>
          )}
          {(item.website_da || item.website?.da) && (
            <p className="text-xs text-var-text-muted mt-1">
              DA: {item.website_da || item.website?.da}
            </p>
          )}
        </div>
        {/* FIX: No item-level status badge — order_items has no status column */}
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm mb-3">
        <div>
          <span className="text-var-text-muted">Quantity:</span>
          <p className="font-medium text-var-text">{item.quantity}</p>
        </div>
        <div>
          <span className="text-var-text-muted">Unit Price:</span>
          <p className="font-medium text-var-text">${item.unit_price.toFixed(2)}</p>
        </div>
        {item.content_service && (
          <div>
            <span className="text-var-text-muted">Content Service:</span>
            <p className="font-medium text-var-text">${item.content_service_price?.toFixed(2) ?? '0.00'}</p>
          </div>
        )}
        <div>
          <span className="text-var-text-muted">Subtotal:</span>
          <p className="font-medium text-var-text">${item.subtotal.toFixed(2)}</p>
        </div>
      </div>

      {/* Customer Submitted Content */}
      {!item.content_service && (hasDocument || submittedUrl) && (
        <div className="mt-3 pt-3 border-t border-var-border">
          <h5 className="text-sm font-medium text-var-text mb-2">Customer Submitted Content</h5>
          {hasDocument ? (
            <DocumentsSection documents={documents} />
          ) : submittedUrl ? (
            <div className="bg-var-primary-muted rounded-lg p-3">
              <div className="flex items-center justify-between">
                <a
                  href={submittedUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-sm text-var-primary hover:underline break-all flex-1"
                >
                  {submittedUrl}
                </a>
                <button
                  onClick={() => {
                    navigator.clipboard.writeText(submittedUrl);
                    toast.success('URL copied to clipboard');
                  }}
                  className="ml-2 px-2 py-1 text-xs text-var-text-muted hover:text-var-text hover:bg-var-surface-hover rounded transition-colors"
                >
                  Copy
                </button>
              </div>
              <p className="text-xs text-var-text-muted mt-2">
                Submitted: {formatDate(item.created_at)}
              </p>
            </div>
          ) : null}
        </div>
      )}

      {item.content_service && detail && <ContentDetailsSection detail={detail} />}

      {item.live_links && item.live_links.length > 0 && (
        <LiveLinksSection links={item.live_links} />
      )}

      {item.rejection_reason && <RejectionBanner reason={item.rejection_reason} />}
    </div>
  );
}

// FIX: Removed item.status references — package_order_items has no status column.
function PackageItemCard({
  item,
  documents,
}: {
  item: PackageOrderItem;
  documents: OrderDocument[];
}) {
  const urlDocument = documents.find((doc) => doc.file_type === 'url' || isUrl(doc.file_path));
  const submittedUrl = urlDocument?.file_path;
  const hasDocument = documents.length > 0;

  return (
    <div className="border border-var-border rounded-xl p-4 hover:shadow-var-card transition-shadow">
      <div className="flex justify-between items-start mb-3">
        <div>
          <h4 className="font-medium text-var-text text-lg">
            {item.package?.name ?? 'Package'}
          </h4>
          {item.package?.description && (
            <p className="text-sm text-var-text-secondary">{item.package.description}</p>
          )}
        </div>
        {/* FIX: No item-level status badge — package_order_items has no status column */}
      </div>

      <div className="grid grid-cols-2 md:grid-cols-3 gap-3 text-sm mb-3">
        <div>
          <span className="text-var-text-muted">Quantity:</span>
          <p className="font-medium text-var-text">{item.quantity}</p>
        </div>
        <div>
          <span className="text-var-text-muted">Unit Price:</span>
          <p className="font-medium text-var-text">${item.unit_price.toFixed(2)}</p>
        </div>
        <div>
          <span className="text-var-text-muted">Subtotal:</span>
          <p className="font-medium text-var-text">${item.subtotal.toFixed(2)}</p>
        </div>
      </div>

      {/* Customer submitted documents */}
      {hasDocument && (
        <div className="mt-3 pt-3 border-t border-var-border">
          <h5 className="text-sm font-medium text-var-text mb-2">Customer Submitted Content</h5>
          <DocumentsSection documents={documents} />
        </div>
      )}

      {submittedUrl && !hasDocument && (
        <div className="mt-3 pt-3 border-t border-var-border">
          <h5 className="text-sm font-medium text-var-text mb-2">Customer Submitted URL</h5>
          <div className="bg-var-primary-muted rounded-lg p-3">
            <div className="flex items-center justify-between">
              <a
                href={submittedUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="text-sm text-var-primary hover:underline break-all flex-1"
              >
                {submittedUrl}
              </a>
              <button
                onClick={() => {
                  navigator.clipboard.writeText(submittedUrl);
                  toast.success('URL copied to clipboard');
                }}
                className="ml-2 px-2 py-1 text-xs text-var-text-muted hover:text-var-text hover:bg-var-surface-hover rounded transition-colors"
              >
                Copy
              </button>
            </div>
          </div>
        </div>
      )}

      {item.google_sheet_url && (
        <div className="mt-3 pt-3 border-t border-var-border">
          <span className="text-sm font-medium text-var-text">Google Sheet:</span>
          <div className="mt-1">
            <a
              href={item.google_sheet_url}
              target="_blank"
              rel="noopener noreferrer"
              className="text-sm text-var-primary hover:underline break-all"
            >
              {item.google_sheet_url}
            </a>
          </div>
        </div>
      )}

      {item.assigned_websites && item.assigned_websites.length > 0 && (
        <div className="mt-3 pt-3 border-t border-var-border">
          <h5 className="text-sm font-medium text-var-text mb-2">
            Assigned Websites ({item.assigned_websites.length})
          </h5>
          <div className="space-y-2">
            {item.assigned_websites.map((website: AssignedWebsite) => (
              <div
                key={website.website_id}
                className="flex items-center justify-between bg-var-surface-hover p-2 rounded-lg"
              >
                <div>
                  <p className="text-sm font-medium text-var-text">{website.website_name}</p>
                  <p className="text-xs text-var-text-muted">
                    DA: {website.assigned_da || website.website_da || 'N/A'}
                  </p>
                </div>
                <a
                  href={`https://${website.website_domain}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-xs text-var-primary hover:underline"
                >
                  Visit
                </a>
              </div>
            ))}
          </div>
        </div>
      )}

      {item.rejection_reason && <RejectionBanner reason={item.rejection_reason} />}
    </div>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function OrderDetailModal({ order, onClose }: OrderDetailModalProps) {
  const [itemDetails, setItemDetails] = useState<Record<string, OrderItemDetail>>({});
  const [individualItemDocuments, setIndividualItemDocuments] = useState<
    Record<string, OrderDocument[]>
  >({});
  const [packageItemDocuments, setPackageItemDocuments] = useState<
    Record<string, OrderDocument[]>
  >({});
  const [loading, setLoading] = useState(true);

  const fetchIndividualItemDetails = useCallback(async (orderItemId: string) => {
    try {
      const response = await fetch(
        `/api/backend/admin/orders/order-item-details?order_item_id=${orderItemId}`
      );
      const data = await response.json();
      if (response.ok && data.detail) {
        setItemDetails((prev) => ({ ...prev, [orderItemId]: data.detail }));
      }
    } catch (error) {
      console.error('Failed to fetch item details:', error);
    }
  }, []);

  const fetchIndividualItemDocuments = useCallback(async (orderItemId: string) => {
    try {
      const response = await fetch(
        `/api/backend/admin/orders/order-item-documents?order_item_id=${orderItemId}`
      );
      const data = await response.json();
      if (response.ok && data.documents) {
        setIndividualItemDocuments((prev) => ({ ...prev, [orderItemId]: data.documents }));
      }
    } catch (error) {
      console.error('Failed to fetch item documents:', error);
    }
  }, []);

  const fetchPackageItemDocuments = useCallback(async (packageOrderItemId: string) => {
    try {
      const response = await fetch(
        `/api/backend/admin/orders/package-order-item-documents?package_order_item_id=${packageOrderItemId}`
      );
      const data = await response.json();
      if (response.ok && data.documents) {
        setPackageItemDocuments((prev) => ({ ...prev, [packageOrderItemId]: data.documents }));
      }
    } catch (error) {
      console.error('Failed to fetch package item documents:', error);
    }
  }, []);

  // FIX: fetchAllData only depends on stable callbacks and order identity fields,
  // not the whole order object — prevents stale closure issues.
  const fetchAllData = useCallback(async () => {
    setLoading(true);
    try {
      const individualItems =
        order.order_type === 'individual' || order.order_type === 'package_individual'
          ? (order.items as OrderItem[] | undefined) ?? []
          : [];

      const packageItems =
        order.order_type === 'package' || order.order_type === 'package_individual'
          ? (order.package_items as PackageOrderItem[] | undefined) ?? []
          : [];

      await Promise.all([
        ...individualItems.map(async (item) => {
          const tasks: Promise<void>[] = [fetchIndividualItemDocuments(item.id)];
          if (item.content_service) tasks.push(fetchIndividualItemDetails(item.id));
          await Promise.all(tasks);
        }),
        ...packageItems.map((item) => fetchPackageItemDocuments(item.id)),
      ]);
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  }, [
    order.order_type,
    order.items,
    order.package_items,
    fetchIndividualItemDetails,
    fetchIndividualItemDocuments,
    fetchPackageItemDocuments,
  ]);

  useEffect(() => {
    fetchAllData();
  }, [fetchAllData]);

  const customerName = useMemo(() => getCustomerName(order.user), [order.user]);

  const individualItems = useMemo(
    () =>
      order.order_type === 'individual' || order.order_type === 'package_individual'
        ? (order.items as OrderItem[] | undefined) ?? []
        : [],
    [order.items, order.order_type]
  );

  const packageItems = useMemo(
    () =>
      order.order_type === 'package' || order.order_type === 'package_individual'
        ? (order.package_items as PackageOrderItem[] | undefined) ?? []
        : [],
    [order.package_items, order.order_type]
  );

  const orderTypeLabel = useMemo(() => {
    switch (order.order_type) {
      case 'individual':
        return 'Individual';
      case 'package':
        return 'Package';
      case 'package_individual':
        return 'Mixed (Package + Individual)';
      default:
        return order.order_type;
    }
  }, [order.order_type]);

  return (
    <div className="fixed inset-0 bg-black/70 bg-opacity-50 flex items-center justify-center z-50 overflow-y-auto">
      <div className="bg-var-surface rounded-2xl max-w-5xl w-full mx-4 my-8 max-h-[90vh] overflow-y-auto shadow-var-modal">
        {/* Header */}
        <div className="sticky top-0 bg-var-surface border-b border-var-border px-6 py-4 flex justify-between items-center z-10">
          <div>
            <h2 className="text-xl font-bold text-var-text">Order Details</h2>
            <p className="text-sm text-var-text-muted">Order #{order.order_number}</p>
          </div>
          <button
            onClick={onClose}
            aria-label="Close modal"
            className="text-var-text-muted hover:text-var-text transition-colors"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>

        {loading ? (
          <div className="flex items-center justify-center py-12">
            <div className="text-center">
              <div className="w-12 h-12 border-4 border-var-border border-t-var-primary rounded-full animate-spin mx-auto mb-4" />
              <p className="text-var-text-muted">Loading order details...</p>
            </div>
          </div>
        ) : (
          <div className="p-6 space-y-6">
            {/* Order + Customer Info */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="bg-var-surface-hover rounded-xl p-4">
                <h3 className="text-sm font-medium text-var-text-muted mb-2">Order Information</h3>
                <div className="space-y-2">
                  <InfoRow label="Order Date" value={formatDate(order.created_at)} />
                  <InfoRow label="Order Type" value={orderTypeLabel} />
                  <div className="flex justify-between items-center">
                    <span className="text-sm text-var-text-muted">Order Status:</span>
                    <span
                      className={`inline-flex px-2 py-1 rounded text-xs font-medium ${getStatusColor(order.status)}`}
                    >
                      {order.status.replace(/_/g, ' ').toUpperCase()}
                    </span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm text-var-text-muted">Payment Status:</span>
                    <span
                      className={`inline-flex px-2 py-1 rounded text-xs font-medium ${getStatusColor(order.payment_status)}`}
                    >
                      {order.payment_status.toUpperCase()}
                    </span>
                  </div>
                </div>
              </div>

              <div className="bg-var-surface-hover rounded-xl p-4">
                <h3 className="text-sm font-medium text-var-text-muted mb-2">Customer Information</h3>
                <div className="space-y-2">
                  <InfoRow label="Name" value={customerName} />
                  <InfoRow label="Email" value={order.user?.email ?? 'N/A'} />
                  {order.user?.phone && <InfoRow label="Phone" value={order.user.phone} />}
                  {order.user?.company && (
                    <InfoRow label="Company" value={order.user.company} />
                  )}
                  {(order.user?.country || order.user?.city) && (
                    <InfoRow
                      label="Location"
                      value={[order.user?.city, order.user?.country].filter(Boolean).join(', ')}
                    />
                  )}
                  {order.payment_method && (
                    <InfoRow
                      label="Payment Method"
                      value={order.payment_method}
                      capitalize
                    />
                  )}
                  {order.transaction_id && (
                    <InfoRow label="Transaction ID" value={order.transaction_id} mono />
                  )}
                </div>
              </div>
            </div>

            {/* Order Items */}
            <div>
              <h3 className="text-lg font-semibold text-var-text mb-4">Order Items</h3>

              {individualItems.length > 0 && (
                <>
                  <h4 className="text-md font-medium text-var-text mb-3">
                    Individual Website Items
                  </h4>
                  <div className="space-y-4 mb-6">
                    {individualItems.map((item) => (
                      <IndividualItemCard
                        key={item.id}
                        item={item}
                        detail={itemDetails[item.id]}
                        documents={individualItemDocuments[item.id] ?? []}
                      />
                    ))}
                  </div>
                </>
              )}

              {packageItems.length > 0 && (
                <>
                  <h4 className="text-md font-medium text-var-text mb-3">Package Items</h4>
                  <div className="space-y-4">
                    {packageItems.map((item) => (
                      <PackageItemCard
                        key={item.id}
                        item={item}
                        documents={packageItemDocuments[item.id] ?? []}
                      />
                    ))}
                  </div>
                </>
              )}
            </div>

            {/* Total */}
            <div className="border-t border-var-border pt-4">
              <div className="flex justify-end">
                <div className="text-right">
                  <p className="text-sm text-var-text-muted">Total Amount</p>
                  <p className="text-2xl font-bold text-var-text">
                    ${order.total_amount.toFixed(2)}
                  </p>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Tiny helper to DRY up info rows ─────────────────────────────────────────

function InfoRow({
  label,
  value,
  capitalize,
  mono,
}: {
  label: string;
  value: string;
  capitalize?: boolean;
  mono?: boolean;
}) {
  return (
    <div className="flex justify-between">
      <span className="text-sm text-var-text-muted">{label}:</span>
      <span
        className={`text-sm font-medium text-var-text ${capitalize ? 'capitalize' : ''} ${mono ? 'font-mono' : ''}`}
      >
        {value}
      </span>
    </div>
  );
}