'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { useToast } from '@/hooks/use-toast';
import { api } from '@/lib/api';
import {
  ArrowLeft,
  Download,
  FileText,
  Clock,
  CheckCircle2,
  XCircle,
  AlertCircle,
  Loader2,
  RefreshCw,
  Languages,
  Trash2
} from 'lucide-react';
import { DownloadMenu } from '@/components/orders/DownloadMenu';

// Dynamic status steps based on service type
const getStatusSteps = (serviceType: string, includeHumanReview: boolean) => {
  const baseSteps = [
    { key: 'Processing', label: 'Processing', icon: Loader2 },
    { key: 'AI Translating', label: 'AI Translating', icon: FileText },
  ];

  // Add Human Review step if service includes human review
  if (includeHumanReview || serviceType?.toLowerCase().includes('human')) {
    baseSteps.push({ key: 'Human Review', label: 'Human Review', icon: AlertCircle });
  }

  // Add Quality Check for certified/notarized orders
  if (serviceType?.toLowerCase().includes('certified') || serviceType?.toLowerCase().includes('notari')) {
    baseSteps.push({ key: 'Quality Check', label: 'Quality Check', icon: AlertCircle });
  }

  baseSteps.push({ key: 'Completed', label: 'Completed', icon: CheckCircle2 });

  return baseSteps;
};

const statusColors: Record<string, { bg: string; text: string; border: string }> = {
  'Pending Payment': { bg: 'bg-yellow-100', text: 'text-yellow-700', border: 'border-yellow-300' },
  'Processing': { bg: 'bg-blue-100', text: 'text-blue-700', border: 'border-blue-300' },
  'AI Translating': { bg: 'bg-blue-100', text: 'text-blue-700', border: 'border-blue-300' },
  'Human Review': { bg: 'bg-purple-100', text: 'text-purple-700', border: 'border-purple-300' },
  'Quality Check': { bg: 'bg-orange-100', text: 'text-orange-700', border: 'border-orange-300' },
  'Completed': { bg: 'bg-green-100', text: 'text-green-700', border: 'border-green-300' },
  'Failed': { bg: 'bg-red-100', text: 'text-red-700', border: 'border-red-300' },
  'Cancelled': { bg: 'bg-gray-100', text: 'text-gray-700', border: 'border-gray-300' },
};

// Helper to get field value supporting both PostgreSQL (snake_case) and Airtable (PascalCase) formats
const getField = (order: any, snakeCase: string, pascalCase: string, defaultValue: any = null) => {
  return order[snakeCase] ?? order[pascalCase] ?? defaultValue;
};

interface Order {
  // PostgreSQL snake_case fields
  order_id?: string;
  order_name?: string;
  customer_id?: string;
  source_language?: string;
  target_language?: string;
  service_type?: string;
  status?: string;
  total_documents?: number;
  total_pages?: number;
  total_cost?: number;
  created_at?: string;
  expected_delivery?: string;
  completion_date?: string;
  certificate_requested?: boolean;
  notarization_country?: string;
  express_service?: string;
  ai_translation_cost?: number;
  human_review_cost?: number;
  certificate_fee?: number;
  notarization_fee?: number;
  express_fee?: number;
  internal_notes?: string;
  // Airtable PascalCase fields (for backward compatibility)
  'Order ID'?: string;
  'Order Name'?: string;
  'Customer'?: string[];
  'Source Language'?: string;
  'Target Language'?: string;
  'Service Type'?: string;
  'Status'?: string;
  'Total Documents'?: number;
  'Total Pages'?: number;
  'Total Cost'?: number;
  'Created At'?: string;
  'Expected Delivery'?: string;
  'Completion Date'?: string;
  'Certificate Requested'?: boolean;
  'Notarization Country'?: string;
  'Express Service'?: string;
  'AI Translation Cost'?: number;
  'Human Review Cost'?: number;
  'Certificate Fee'?: number;
  'Notarization Fee'?: number;
  'Express Fee'?: number;
  'Internal Notes'?: string;
}

interface Document {
  id: string;
  name: string;
  type: 'source' | 'translated' | 'certificate';
  status: string;
  size: number;
  created_at: string;
}

export default function OrderDetailPage() {
  const params = useParams();
  const router = useRouter();
  const { toast } = useToast();
  const [order, setOrder] = useState<Order | null>(null);
  const [documents, setDocuments] = useState<Document[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [downloadingId, setDownloadingId] = useState<string | null>(null);
  const [isDeletingFiles, setIsDeletingFiles] = useState(false);

  const fetchOrder = async () => {
    try {
      const [orderResponse, docsResponse] = await Promise.all([
        api.getOrder(params.id as string),
        api.getOrderDocuments(params.id as string).catch(() => ({ documents: [] })),
      ]);

      // Debug logging for troubleshooting
      console.log('[DEBUG] Order API Response:', orderResponse);
      console.log('[DEBUG] Documents API Response:', docsResponse);
      console.log('[DEBUG] Order Status:', orderResponse.order?.status);
      console.log('[DEBUG] Total Documents in Response:', docsResponse.documents?.length || 0);

      // Log document types
      if (docsResponse.documents && docsResponse.documents.length > 0) {
        console.log('[DEBUG] Document Types:', docsResponse.documents.map((d: any) => ({
          id: d.id,
          name: d.name,
          type: d.type
        })));
      }

      setOrder(orderResponse.order);
      setDocuments(docsResponse.documents || []);
    } catch (error: any) {
      console.error('[DEBUG] Error fetching order:', error);
      toast({
        title: 'Error',
        description: error.message || 'Failed to load order',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    fetchOrder();

    // Auto-refresh every 30 seconds if order is in progress
    const interval = setInterval(() => {
      const orderStatus = order?.status || order?.['Status'] || '';
      if (order && !['Completed', 'Failed', 'Cancelled'].includes(orderStatus)) {
        fetchOrder();
      }
    }, 30000);

    return () => clearInterval(interval);
  }, [params.id]);

  const handleRefresh = async () => {
    setIsRefreshing(true);
    await fetchOrder();
  };

  const handleDownload = async (documentId: string, fileName: string) => {
    setDownloadingId(documentId);
    try {
      const blob = await api.downloadDocument(documentId);
      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({
        title: 'Download started',
        description: `Downloading ${fileName}`,
      });
    } catch (error: any) {
      toast({
        title: 'Download failed',
        description: error.message || 'Failed to download file',
        variant: 'destructive',
      });
    } finally {
      setDownloadingId(null);
    }
  };

  const handleDeleteFiles = async () => {
    const ok = window.confirm(
      'Delete all files for this order?\n\n' +
      'Your uploaded documents and their translations will be permanently deleted and cannot be recovered. ' +
      'The order and payment record is kept for our accounts.'
    );
    if (!ok) return;
    setIsDeletingFiles(true);
    try {
      await api.deleteOrderFiles(params.id as string);
      toast({ title: 'Files deleted', description: 'The documents for this order have been deleted.' });
      await fetchOrder();
    } catch (error: any) {
      toast({
        title: 'Delete failed',
        description: error.response?.data?.detail || error.message || 'Failed to delete files',
        variant: 'destructive',
      });
    } finally {
      setIsDeletingFiles(false);
    }
  };

  // Group documents by type
  const sourceDocuments = documents.filter(doc => doc.type === 'source');
  const translatedDocuments = documents.filter(doc => doc.type === 'translated');
  const certificateDocuments = documents.filter(doc => doc.type === 'certificate');

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
  };

  if (isLoading) {
    return (
      <div className="p-6 lg:p-8 max-w-5xl mx-auto">
        <div className="flex items-center justify-center h-64">
          <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
        </div>
      </div>
    );
  }

  if (!order) {
    return (
      <div className="p-6 lg:p-8 max-w-5xl mx-auto">
        <div className="text-center py-12">
          <XCircle className="h-12 w-12 text-red-600 mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-gray-900 mb-2">Order Not Found</h2>
          <p className="text-gray-600 mb-4">The order you're looking for doesn't exist.</p>
          <Button onClick={() => router.push('/dashboard/orders')}>
            Back to Orders
          </Button>
        </div>
      </div>
    );
  }

  // Extract fields with fallbacks for both PostgreSQL and Airtable formats
  const orderId = getField(order, 'order_id', 'Order ID', 'Unknown');
  const orderName = getField(order, 'order_name', 'Order Name', orderId);
  const sourceLang = getField(order, 'source_language', 'Source Language', 'N/A');
  const targetLang = getField(order, 'target_language', 'Target Language', 'N/A');
  const serviceType = getField(order, 'service_type', 'Service Type', 'AI Translation');
  const status = getField(order, 'status', 'Status', 'Pending Payment');
  const totalDocs = getField(order, 'total_documents', 'Total Documents', 0);

  // Map service type to service tier for DownloadMenu component
  const getServiceTier = (serviceType: string): 'ai_text' | 'ai_ocr' | 'ai_human' | 'certified' => {
    const type = serviceType?.toLowerCase() || '';
    if (type.includes('certified') || type.includes('notarized')) {
      return 'certified';
    }
    if (type.includes('human')) {
      return 'ai_human';
    }
    // For AI Translation, default to ai_ocr (most common case)
    return 'ai_ocr';
  };
  const totalPages = getField(order, 'total_pages', 'Total Pages', 0);
  const totalCost = getField(order, 'total_cost', 'Total Cost', 0);
  const createdAt = getField(order, 'created_at', 'Created At', null);
  const expectedDelivery = getField(order, 'expected_delivery', 'Expected Delivery', null);
  const completionDate = getField(order, 'completion_date', 'Completion Date', null);
  const certificateRequested = getField(order, 'certificate_requested', 'Certificate Requested', false);
  const notarizationCountry = getField(order, 'notarization_country', 'Notarization Country', null);
  const expressService = getField(order, 'express_service', 'Express Service', null);
  const aiTranslationCost = getField(order, 'ai_translation_cost', 'AI Translation Cost', 0);
  const humanReviewCost = getField(order, 'human_review_cost', 'Human Review Cost', 0);
  const certificateFee = getField(order, 'certificate_fee', 'Certificate Fee', 0);
  const notarizationFee = getField(order, 'notarization_fee', 'Notarization Fee', 0);
  const expressFee = getField(order, 'express_fee', 'Express Fee', 0);
  const filesDeletedAt = getField(order, 'files_deleted_at', 'Files Deleted At', null);
  const canDeleteFiles = !filesDeletedAt && ['Completed', 'Failed', 'Cancelled', 'Refunded'].includes(status);

  // Get dynamic status steps based on service type
  const includeHumanReview = humanReviewCost > 0;
  const statusSteps = getStatusSteps(serviceType, includeHumanReview);

  const getCurrentStepIndex = () => {
    return statusSteps.findIndex(step => step.key === status);
  };

  const currentStepIndex = getCurrentStepIndex();
  const statusColor = statusColors[status] || statusColors['Processing'];
  const isCompleted = status === 'Completed';
  const isFailed = status === 'Failed';

  return (
    <div className="p-6 lg:p-8 max-w-5xl mx-auto">
      {/* Header */}
      <div className="mb-8">
        <Button
          variant="ghost"
          onClick={() => router.push('/dashboard/orders')}
          className="mb-4"
        >
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back to Orders
        </Button>
        <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">
              {orderName}
            </h1>
            <p className="text-gray-500 text-sm">{orderId}</p>
            <p className="text-gray-600 mt-1">
              {sourceLang} → {targetLang}
            </p>
          </div>
          <div className="flex items-center gap-3">
            <Button
              variant="outline"
              size="sm"
              onClick={handleRefresh}
              disabled={isRefreshing}
            >
              <RefreshCw className={`h-4 w-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`} />
              Refresh
            </Button>
            <div className={`px-4 py-2 rounded-full border-2 ${statusColor.bg} ${statusColor.text} ${statusColor.border}`}>
              <span className="font-semibold">{status}</span>
            </div>
          </div>
        </div>
      </div>

      {/* Progress Tracker */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>Order Progress</CardTitle>
          <CardDescription>Track your translation status</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="relative">
            {/* Progress Line */}
            <div className="absolute top-5 left-0 right-0 h-1 bg-gray-200">
              <div
                className="h-full bg-blue-600 transition-all duration-500"
                style={{ width: `${Math.max(0, (currentStepIndex / (statusSteps.length - 1)) * 100)}%` }}
              />
            </div>

            {/* Steps */}
            <div className="relative flex justify-between">
              {statusSteps.map((step, index) => {
                const isStepCompleted = index <= currentStepIndex;
                const isCurrent = index === currentStepIndex;
                const Icon = step.icon;

                return (
                  <div key={step.key} className="flex flex-col items-center">
                    <div
                      className={`w-10 h-10 rounded-full flex items-center justify-center border-2 transition-all ${
                        isStepCompleted
                          ? 'bg-blue-600 border-blue-600 text-white'
                          : 'bg-white border-gray-300 text-gray-400'
                      }`}
                    >
                      <Icon className={`h-5 w-5 ${isCurrent ? 'animate-pulse' : ''}`} />
                    </div>
                    <p className={`mt-2 text-xs text-center max-w-[80px] ${
                      isStepCompleted ? 'text-gray-900 font-medium' : 'text-gray-500'
                    }`}>
                      {step.label}
                    </p>
                  </div>
                );
              })}
            </div>
          </div>

          {isFailed && (
            <div className="mt-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
              <XCircle className="h-5 w-5 text-red-600 flex-shrink-0 mt-0.5" />
              <div>
                <h4 className="font-medium text-red-900">Order Failed</h4>
                <p className="text-sm text-red-700 mt-1">
                  There was an issue processing your order. Please contact support for assistance.
                </p>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Order Details */}
      <div className="grid lg:grid-cols-2 gap-6 mb-6">
        <Card>
          <CardHeader>
            <CardTitle>Translation Details</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Source Language</span>
              <span className="font-medium">{sourceLang}</span>
            </div>
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Target Language</span>
              <span className="font-medium">{targetLang}</span>
            </div>
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Service Type</span>
              <span className="font-medium">{serviceType}</span>
            </div>
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Total Documents</span>
              <span className="font-medium">{totalDocs}</span>
            </div>
            <div className="flex justify-between py-2">
              <span className="text-gray-600">Total Pages</span>
              <span className="font-medium">{totalPages}</span>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Order Information</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Created</span>
              <span className="font-medium">
                {createdAt ? new Date(createdAt).toLocaleString() : '-'}
              </span>
            </div>
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Expected Delivery</span>
              <span className="font-medium">
                {expectedDelivery ? new Date(expectedDelivery).toLocaleString() : '-'}
              </span>
            </div>
            {completionDate && (
              <div className="flex justify-between py-2 border-b">
                <span className="text-gray-600">Completed</span>
                <span className="font-medium">
                  {new Date(completionDate).toLocaleString()}
                </span>
              </div>
            )}
            <div className="flex justify-between py-2">
              <span className="text-gray-600">Total Cost</span>
              <span className="font-medium text-blue-600">
                {totalCost?.toLocaleString()} credits
              </span>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Cost Breakdown */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>Cost Breakdown</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="flex justify-between py-2 border-b">
            <span className="text-gray-600">AI Translation</span>
            <span className="font-medium">{aiTranslationCost?.toLocaleString() || 0} credits</span>
          </div>
          {humanReviewCost > 0 && (
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Human Review</span>
              <span className="font-medium">{humanReviewCost?.toLocaleString()} credits</span>
            </div>
          )}
          {certificateFee > 0 && (
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Certificate Fee</span>
              <span className="font-medium">{certificateFee?.toLocaleString()} credits</span>
            </div>
          )}
          {notarizationFee > 0 && (
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Notarization Fee ({notarizationCountry})</span>
              <span className="font-medium">{notarizationFee?.toLocaleString()} credits</span>
            </div>
          )}
          {expressFee > 0 && (
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Express Service ({expressService})</span>
              <span className="font-medium">{expressFee?.toLocaleString()} credits</span>
            </div>
          )}
          <div className="flex justify-between py-3 bg-blue-50 -mx-6 px-6 rounded">
            <span className="font-semibold text-lg">Total</span>
            <span className="font-bold text-lg text-blue-600">
              {totalCost?.toLocaleString()} credits
            </span>
          </div>
        </CardContent>
      </Card>

      {/* Additional Options */}
      {(certificateRequested || notarizationCountry || expressService) && (
        <Card className="mb-6">
          <CardHeader>
            <CardTitle>Additional Services</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-2">
              {serviceType?.includes('Human') && (
                <span className="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-sm">
                  Human Review
                </span>
              )}
              {certificateRequested && (
                <span className="px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm">
                  Certificate Included
                </span>
              )}
              {notarizationCountry && (
                <span className="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm">
                  Notarization ({notarizationCountry})
                </span>
              )}
              {expressService && (
                <span className="px-3 py-1 bg-orange-100 text-orange-700 rounded-full text-sm">
                  Express ({expressService})
                </span>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Debug Panel - Hidden for production launch */}
      {false && (
      <Card className="border-2 border-orange-300 bg-orange-50/50">
        <CardHeader>
          <CardTitle className="text-orange-700 flex items-center gap-2">
            <AlertCircle className="h-5 w-5" />
            Debug Information - Order Diagnostics
          </CardTitle>
          <CardDescription>
            Troubleshooting information for order {orderId}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Order Status Overview */}
          <div className="bg-white p-4 rounded-lg border">
            <h4 className="font-semibold text-sm text-gray-700 mb-3">Order Status Overview</h4>
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div>
                <span className="text-gray-500">Order ID:</span>
                <span className="ml-2 font-mono font-medium">{orderId}</span>
              </div>
              <div>
                <span className="text-gray-500">Status:</span>
                <span className={`ml-2 px-2 py-0.5 rounded ${statusColor.bg} ${statusColor.text} font-medium`}>
                  {status}
                </span>
              </div>
              <div>
                <span className="text-gray-500">Total Documents:</span>
                <span className="ml-2 font-medium">{totalDocs}</span>
              </div>
              <div>
                <span className="text-gray-500">Created:</span>
                <span className="ml-2 font-medium">
                  {createdAt ? new Date(createdAt).toLocaleString() : 'N/A'}
                </span>
              </div>
              {completionDate && (
                <div className="col-span-2">
                  <span className="text-gray-500">Completed:</span>
                  <span className="ml-2 font-medium">
                    {new Date(completionDate).toLocaleString()}
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* Document Analysis */}
          <div className="bg-white p-4 rounded-lg border">
            <h4 className="font-semibold text-sm text-gray-700 mb-3">Document Analysis</h4>
            <div className="space-y-2 text-sm">
              <div className="flex items-center justify-between p-2 bg-gray-50 rounded">
                <span className="text-gray-600">Total API Documents:</span>
                <span className="font-mono font-bold">{documents.length}</span>
              </div>
              <div className="flex items-center justify-between p-2 bg-green-50 rounded">
                <span className="text-gray-600">Source Documents:</span>
                <span className="font-mono font-bold text-green-700">{sourceDocuments.length}</span>
              </div>
              <div className="flex items-center justify-between p-2 bg-blue-50 rounded">
                <span className="text-gray-600">Translated Documents:</span>
                <span className="font-mono font-bold text-blue-700">{translatedDocuments.length}</span>
              </div>
              <div className="flex items-center justify-between p-2 bg-purple-50 rounded">
                <span className="text-gray-600">Certificate Documents:</span>
                <span className="font-mono font-bold text-purple-700">{certificateDocuments.length}</span>
              </div>
            </div>
          </div>

          {/* Root Cause Analysis */}
          {isCompleted && translatedDocuments.length === 0 && (
            <div className="bg-red-50 border-2 border-red-300 p-4 rounded-lg">
              <h4 className="font-semibold text-sm text-red-700 mb-2 flex items-center gap-2">
                <XCircle className="h-4 w-4" />
                Root Cause: 0 Translated Documents
              </h4>
              <p className="text-sm text-red-600 mb-3">
                Order shows as "Completed" but no translated documents are available.
              </p>
              <div className="text-xs text-red-700 space-y-1">
                <p className="font-medium">Possible causes:</p>
                <ul className="list-disc list-inside ml-2 space-y-1">
                  <li>Translation worker failed to create translated documents</li>
                  <li>Documents created but not marked with type='translated'</li>
                  <li>Database link missing between order and translated docs</li>
                  <li>Translation process completed but file upload failed</li>
                </ul>
              </div>
            </div>
          )}

          {/* Raw Document Data */}
          <details className="bg-white p-4 rounded-lg border">
            <summary className="font-semibold text-sm text-gray-700 cursor-pointer hover:text-gray-900">
              Raw Document Data (Click to expand)
            </summary>
            <div className="mt-3 space-y-2">
              {documents.length > 0 ? (
                documents.map((doc, idx) => (
                  <div key={doc.id || idx} className="p-3 bg-gray-50 rounded border text-xs font-mono">
                    <div className="grid grid-cols-2 gap-2">
                      <div><span className="text-gray-500">ID:</span> {doc.id || 'N/A'}</div>
                      <div><span className="text-gray-500">Type:</span> <span className="font-bold text-blue-600">{doc.type || 'NULL'}</span></div>
                      <div className="col-span-2"><span className="text-gray-500">Name:</span> {doc.name || 'N/A'}</div>
                      <div><span className="text-gray-500">Size:</span> {formatFileSize(doc.size || 0)}</div>
                      <div><span className="text-gray-500">Status:</span> {(doc as any).status || 'N/A'}</div>
                    </div>
                  </div>
                ))
              ) : (
                <p className="text-sm text-gray-500 italic">No documents returned from API</p>
              )}
            </div>
          </details>

          {/* API Response Debug */}
          <details className="bg-white p-4 rounded-lg border">
            <summary className="font-semibold text-sm text-gray-700 cursor-pointer hover:text-gray-900">
              Full API Response (Click to expand)
            </summary>
            <div className="mt-3">
              <div className="mb-3">
                <h5 className="text-xs font-semibold text-gray-600 mb-1">Order Object:</h5>
                <pre className="bg-gray-900 text-green-400 p-3 rounded text-xs overflow-x-auto">
                  {JSON.stringify(order, null, 2)}
                </pre>
              </div>
              <div>
                <h5 className="text-xs font-semibold text-gray-600 mb-1">Documents Array:</h5>
                <pre className="bg-gray-900 text-green-400 p-3 rounded text-xs overflow-x-auto">
                  {JSON.stringify(documents, null, 2)}
                </pre>
              </div>
            </div>
          </details>

          {/* Troubleshooting Steps */}
          <div className="bg-blue-50 border border-blue-300 p-4 rounded-lg">
            <h4 className="font-semibold text-sm text-blue-700 mb-2">Next Steps</h4>
            <ol className="text-sm text-blue-900 space-y-1 list-decimal list-inside">
              <li>Check "Raw Document Data" above to see document types</li>
              <li>Verify documents exist but have wrong type (not 'translated')</li>
              <li>Check backend logs for translation worker errors</li>
              <li>Query database: <code className="bg-blue-100 px-1 rounded text-xs font-mono">SELECT * FROM documents WHERE order_id = '{orderId}'</code></li>
              <li>Contact support with this debug info if issue persists</li>
            </ol>
          </div>
        </CardContent>
      </Card>
      )}

      {/* Download Section */}
      <Card>
        <CardHeader className="flex flex-row items-start justify-between gap-4 space-y-0">
          <div>
            <CardTitle>Files</CardTitle>
            <CardDescription>{filesDeletedAt ? 'Files deleted' : 'Download your documents'}</CardDescription>
          </div>
          {canDeleteFiles && (
            <Button
              size="sm"
              variant="outline"
              onClick={handleDeleteFiles}
              disabled={isDeletingFiles}
              className="text-red-600 border-red-300 hover:bg-red-50"
            >
              {isDeletingFiles ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <>
                  <Trash2 className="mr-2 h-4 w-4" />
                  Delete files
                </>
              )}
            </Button>
          )}
        </CardHeader>
        <CardContent>
          {filesDeletedAt ? (
            <p className="text-sm text-gray-600 py-2">
              You deleted this order&apos;s files on {new Date(filesDeletedAt).toLocaleString()}. The documents and
              translations are gone; copies in our database backups expire within 30 days. The order and payment
              record is kept for our accounts.
            </p>
          ) : (
          <div className="space-y-4">
            {/* Source Documents */}
            <div>
              <h4 className="text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                <FileText className="h-4 w-4 text-gray-500" />
                Source Documents ({sourceDocuments.length})
              </h4>
              {sourceDocuments.length > 0 ? (
                <div className="space-y-2">
                  {sourceDocuments.map(doc => (
                    <div key={doc.id} className="flex items-center justify-between p-3 border rounded-lg bg-gray-50">
                      <div className="flex items-center gap-3">
                        <FileText className="h-6 w-6 text-gray-400" />
                        <div>
                          <p className="font-medium text-sm">{doc.name}</p>
                          <p className="text-xs text-gray-500">{formatFileSize(doc.size)}</p>
                        </div>
                      </div>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleDownload(doc.id, doc.name)}
                        disabled={downloadingId === doc.id}
                      >
                        {downloadingId === doc.id ? (
                          <Loader2 className="h-4 w-4 animate-spin" />
                        ) : (
                          <Download className="h-4 w-4" />
                        )}
                      </Button>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-sm text-gray-500 py-2">No source documents</p>
              )}
            </div>

            {/* Translated Documents */}
            <div>
              <h4 className="text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                <FileText className="h-4 w-4 text-blue-500" />
                Translated Documents ({translatedDocuments.length})
              </h4>
              {translatedDocuments.length > 0 ? (
                <div className="space-y-2">
                  {translatedDocuments.map(doc => (
                    <div key={doc.id} className="flex items-center justify-between p-3 border rounded-lg bg-blue-50">
                      <div className="flex items-center gap-3">
                        <FileText className="h-6 w-6 text-blue-600" />
                        <div>
                          <p className="font-medium text-sm">{doc.name}</p>
                          <p className="text-xs text-gray-500">{formatFileSize(doc.size)}</p>
                        </div>
                      </div>
                      <DownloadMenu
                        documentId={doc.id}
                        documentName={doc.name}
                        serviceTier={getServiceTier(serviceType)}
                        isCompleted={isCompleted}
                      />
                    </div>
                  ))}
                </div>
              ) : isCompleted ? (
                <div className="text-center py-6 border rounded-lg bg-yellow-50">
                  <AlertCircle className="h-10 w-10 text-yellow-500 mx-auto mb-3" />
                  <p className="text-sm font-medium text-gray-700 mb-1">No Translated Files Available</p>
                  <p className="text-xs text-gray-500">
                    The translation process completed but no output files were generated.
                    Please contact support if this is unexpected.
                  </p>
                </div>
              ) : (
                <div className="text-center py-4 border rounded-lg bg-gray-50">
                  <Loader2 className="h-6 w-6 text-blue-500 mx-auto mb-2 animate-spin" />
                  <p className="text-sm text-gray-500">Translation in progress...</p>
                </div>
              )}
            </div>

            {/* Certificate Documents */}
            {certificateRequested && (
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
                  <FileText className="h-4 w-4 text-green-500" />
                  Certificate of Translation ({certificateDocuments.length})
                </h4>
                {certificateDocuments.length > 0 ? (
                  <div className="space-y-2">
                    {certificateDocuments.map(doc => (
                      <div key={doc.id} className="flex items-center justify-between p-3 border rounded-lg bg-green-50">
                        <div className="flex items-center gap-3">
                          <FileText className="h-6 w-6 text-green-600" />
                          <div>
                            <p className="font-medium text-sm">{doc.name}</p>
                            <p className="text-xs text-gray-500">{formatFileSize(doc.size)}</p>
                          </div>
                        </div>
                        <Button
                          size="sm"
                          onClick={() => handleDownload(doc.id, doc.name)}
                          disabled={downloadingId === doc.id}
                        >
                          {downloadingId === doc.id ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                          ) : (
                            <>
                              <Download className="mr-2 h-4 w-4" />
                              Download
                            </>
                          )}
                        </Button>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-4 border rounded-lg bg-gray-50">
                    <p className="text-sm text-gray-500">
                      {isCompleted ? 'Certificate will be generated soon' : 'Will be generated upon completion'}
                    </p>
                  </div>
                )}
              </div>
            )}
          </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
