'use client';

import { useState, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/hooks/useAuth';
import { api } from '@/lib/api';
import { Upload, FileText, Trash2, Loader2, CheckCircle, AlertCircle, CreditCard, X, Check, Copy, Sparkles, AlertTriangle, Info } from 'lucide-react';
import { useDropzone } from 'react-dropzone';
import { SearchableLanguageSelect, languages, getLanguageMultiplier, getOcrQualityMultiplier, isOcrSupported, OCR_FALLBACK_MULTIPLIER } from '@/components/SearchableLanguageSelect';

// Default pricing (fetched from API on load)
const DEFAULT_PRICING = {
  ai_translation_base_cost: 1,
  human_review_base_cost: 15000,
  certificate_fee: 20000,
  notarization_sg_fee: 250000,
  notarization_my_fee: 280000,
};

interface UploadedFile {
  file: File;
  documentId?: string;
  tempPath?: string;
  sessionId?: string;
  pages: number;
  contentType?: string;
  needsOcr?: boolean;
  progress: number;
  status: 'pending' | 'uploading' | 'done' | 'error';
  error?: string;
}

export default function NewOrderPage() {
  const router = useRouter();
  const { toast } = useToast();
  const { user } = useAuth();

  const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([]);
  const [sourceLanguage, setSourceLanguage] = useState('');
  const [targetLanguage, setTargetLanguage] = useState('');
  const [notarizationCountry, setNotarizationCountry] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Service selection checkboxes (AI always included)
  const [includeHumanReview, setIncludeHumanReview] = useState(false);
  const [includeCertificate, setIncludeCertificate] = useState(false);
  const [includeNotarization, setIncludeNotarization] = useState(false);

  // Pricing from API
  const [pricing, setPricing] = useState(DEFAULT_PRICING);
  const [isLoadingPricing, setIsLoadingPricing] = useState(true);

  // Top-up modal state
  const [showTopUpModal, setShowTopUpModal] = useState(false);
  const [packages, setPackages] = useState<any[]>([]);
  const [isLoadingPackages, setIsLoadingPackages] = useState(false);
  const [selectedPackage, setSelectedPackage] = useState<string | null>(null);
  const [customAmount, setCustomAmount] = useState('');
  const [isPurchasing, setIsPurchasing] = useState(false);
  const [paymentDetails, setPaymentDetails] = useState<any>(null);
  const [transactionId, setTransactionId] = useState('');
  const [isVerifying, setIsVerifying] = useState(false);
  const [verificationStatus, setVerificationStatus] = useState<'idle' | 'pending' | 'success' | 'error'>('idle');
  const [copiedField, setCopiedField] = useState<string | null>(null);

  const onDrop = useCallback(async (acceptedFiles: File[]) => {
    // Add files to state with pending status
    const newFiles: UploadedFile[] = acceptedFiles.map(file => ({
      file,
      pages: 1, // Default, will be updated after upload
      progress: 0,
      status: 'pending' as const,
    }));

    setUploadedFiles(prev => [...prev, ...newFiles]);

    // Upload each file
    for (let i = 0; i < acceptedFiles.length; i++) {
      const file = acceptedFiles[i];
      const fileIndex = uploadedFiles.length + i;

      try {
        // Update status to uploading
        setUploadedFiles(prev => prev.map((f, idx) =>
          idx === fileIndex ? { ...f, status: 'uploading' as const } : f
        ));

        // Upload file with progress
        const result = await api.uploadFile(file, (progress) => {
          setUploadedFiles(prev => prev.map((f, idx) =>
            idx === fileIndex ? { ...f, progress } : f
          ));
        });

        // Update with document ID and page count from API response
        setUploadedFiles(prev => prev.map((f, idx) =>
          idx === fileIndex
            ? {
                ...f,
                documentId: result.document_id,
                tempPath: result.temp_path,
                sessionId: result.session_id,
                pages: result.pages || 1,
                contentType: result.content_type,
                needsOcr: result.needs_ocr,
                status: 'done' as const,
                progress: 100
              }
            : f
        ));
      } catch (error: any) {
        setUploadedFiles(prev => prev.map((f, idx) =>
          idx === fileIndex
            ? { ...f, status: 'error' as const, error: error.message || 'Upload failed' }
            : f
        ));
      }
    }
  }, [uploadedFiles.length]);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      'application/pdf': ['.pdf'],
      'image/*': ['.jpg', '.jpeg', '.png'],
      'application/msword': ['.doc'],
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'],
      'text/plain': ['.txt'],
    },
    maxSize: 10 * 1024 * 1024, // 10MB
  });

  const removeFile = async (index: number) => {
    const file = uploadedFiles[index];

    // If file was uploaded, delete from server
    if (file.documentId) {
      try {
        await api.deleteDocument(file.documentId);
      } catch (error) {
        console.error('Failed to delete document:', error);
      }
    }

    setUploadedFiles(prev => prev.filter((_, i) => i !== index));
  };

  // Fetch pricing from API on load
  useEffect(() => {
    const fetchPricing = async () => {
      try {
        const response = await api.getSettings();
        if (response.success && response.settings) {
          setPricing({
            ai_translation_base_cost: response.settings.ai_translation_base_cost || DEFAULT_PRICING.ai_translation_base_cost,
            human_review_base_cost: response.settings.human_review_base_cost || DEFAULT_PRICING.human_review_base_cost,
            certificate_fee: response.settings.certificate_fee || DEFAULT_PRICING.certificate_fee,
            notarization_sg_fee: response.settings.notarization_sg_fee || DEFAULT_PRICING.notarization_sg_fee,
            notarization_my_fee: response.settings.notarization_my_fee || DEFAULT_PRICING.notarization_my_fee,
          });
        }
      } catch (error) {
        console.error('Failed to fetch pricing:', error);
      } finally {
        setIsLoadingPricing(false);
      }
    };
    fetchPricing();
  }, []);

  // Fetch credit packages when top-up modal opens
  useEffect(() => {
    if (showTopUpModal && packages.length === 0) {
      fetchPackages();
    }
  }, [showTopUpModal]);

  // Handle checkbox dependencies
  const handleHumanReviewChange = (checked: boolean) => {
    setIncludeHumanReview(checked);
    if (!checked) {
      // If unchecking human review, also uncheck certificate and notarization
      setIncludeCertificate(false);
      setIncludeNotarization(false);
      setNotarizationCountry('');
    }
  };

  const handleCertificateChange = (checked: boolean) => {
    setIncludeCertificate(checked);
    if (checked) {
      // Certificate requires human review
      setIncludeHumanReview(true);
    } else {
      // If unchecking certificate, also uncheck notarization
      setIncludeNotarization(false);
      setNotarizationCountry('');
    }
  };

  const handleNotarizationChange = (checked: boolean) => {
    setIncludeNotarization(checked);
    if (checked) {
      // Notarization requires certificate and human review
      setIncludeHumanReview(true);
      setIncludeCertificate(true);
      // Default to Singapore if no country selected
      if (!notarizationCountry) {
        setNotarizationCountry('Singapore');
      }
    } else {
      setNotarizationCountry('');
    }
  };

  const fetchPackages = async () => {
    setIsLoadingPackages(true);
    try {
      const response = await api.getPackages();
      if (response.success) {
        setPackages(response.packages || []);
      }
    } catch (error) {
      console.error('Failed to fetch packages:', error);
    } finally {
      setIsLoadingPackages(false);
    }
  };

  const handleQuickTopUp = async (packageId: string) => {
    setSelectedPackage(packageId);
    setIsPurchasing(true);

    try {
      const response = await api.createPayment(packageId);
      if (response.success) {
        setPaymentDetails(response.payment);
        toast({
          title: 'Payment initiated',
          description: 'Please complete the payment using PayNow',
        });
      }
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.message || 'Failed to create payment',
        variant: 'destructive',
      });
    } finally {
      setIsPurchasing(false);
    }
  };

  const handleCustomTopUp = async () => {
    // Use entered amount or default to suggested amount
    const amount = customAmount ? parseFloat(customAmount) : Math.ceil(creditsNeeded / 1000);
    const minRequired = Math.ceil(creditsNeeded / 1000);

    if (isNaN(amount) || amount < 1) {
      toast({
        title: 'Invalid amount',
        description: 'Please enter a valid amount (minimum $1)',
        variant: 'destructive',
      });
      return;
    }

    // Check if amount covers the required credits
    if (amount < minRequired) {
      toast({
        title: 'Insufficient amount',
        description: `You need at least S$${minRequired} to cover ${creditsNeeded.toLocaleString()} credits required for this order.`,
        variant: 'destructive',
      });
      return;
    }

    setSelectedPackage('custom');
    setIsPurchasing(true);

    try {
      const response = await api.createCustomPayment(amount);
      if (response.success) {
        // Store full response (includes payment, paynow, credits, amount)
        setPaymentDetails(response);
        toast({
          title: 'Payment initiated',
          description: 'Please complete the payment using PayNow',
        });
      }
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.message || 'Failed to create payment',
        variant: 'destructive',
      });
    } finally {
      setIsPurchasing(false);
    }
  };

  const copyToClipboard = async (text: string, field: string) => {
    await navigator.clipboard.writeText(text);
    setCopiedField(field);
    setTimeout(() => setCopiedField(null), 2000);
  };

  const handleVerifyPayment = async () => {
    if (!transactionId.trim()) {
      toast({
        title: 'Transaction ID required',
        description: 'Please enter the transaction ID from your payment confirmation',
        variant: 'destructive',
      });
      return;
    }

    setIsVerifying(true);
    setVerificationStatus('pending');

    try {
      // Payment ID is in payment.payment_id field
      const paymentId = paymentDetails.payment?.payment_id || paymentDetails.payment?.id;
      const response = await api.verifyPayment(
        paymentId,
        transactionId.trim()
      );

      if (response.success) {
        setVerificationStatus('success');
        toast({
          title: 'Payment submitted',
          description: 'Your credits will be added shortly.',
        });

        // Reset modal state and close after 2 seconds
        setTimeout(() => {
          setShowTopUpModal(false);
          setPaymentDetails(null);
          setTransactionId('');
          setVerificationStatus('idle');
          setSelectedPackage(null);
          // Refresh the page to update credits
          window.location.reload();
        }, 2000);
      }
    } catch (error: any) {
      setVerificationStatus('error');
      toast({
        title: 'Verification failed',
        description: error.message || 'Failed to verify payment',
        variant: 'destructive',
      });
    } finally {
      setIsVerifying(false);
    }
  };

  const closeTopUpModal = () => {
    setShowTopUpModal(false);
    setPaymentDetails(null);
    setTransactionId('');
    setVerificationStatus('idle');
    setSelectedPackage(null);
  };

  // Calculate total pages from all successfully uploaded files
  const totalPages = uploadedFiles
    .filter(f => f.status === 'done')
    .reduce((sum, f) => sum + (f.pages || 1), 0);

  // Check if any uploaded files need OCR (images, scanned PDFs)
  const hasOcrFiles = uploadedFiles.some(f => {
    const ext = f.file.name.split('.').pop()?.toLowerCase();
    return ext === 'jpg' || ext === 'jpeg' || ext === 'png' || ext === 'pdf';
  });

  // Get language multiplier for human review pricing (based on language complexity)
  const languageMultiplier = sourceLanguage && targetLanguage
    ? getLanguageMultiplier(sourceLanguage, targetLanguage)
    : 1.0;

  // Get OCR quality multiplier (1.0 for Qwen2.5-VL, 1.5 for DeepSeek-VL2 fallback)
  // Only applies when source document needs OCR and source language has no Qwen support
  const ocrQualityMultiplier = sourceLanguage && hasOcrFiles
    ? getOcrQualityMultiplier(sourceLanguage)
    : 1.0;

  // Combined multiplier for human review cost
  const totalHumanReviewMultiplier = languageMultiplier * ocrQualityMultiplier;

  // Calculate cost breakdown using API pricing
  // Note: Human Review price INCLUDES AI translation, so don't add aiCost when Human Review is selected
  const aiCost = includeHumanReview ? 0 : totalPages * pricing.ai_translation_base_cost;
  const humanReviewCost = includeHumanReview
    ? totalPages * Math.round(pricing.human_review_base_cost * totalHumanReviewMultiplier)
    : 0;
  const certificateCost = includeCertificate ? pricing.certificate_fee : 0;
  const notarizationCost = includeNotarization
    ? (notarizationCountry === 'Singapore' ? pricing.notarization_sg_fee :
       notarizationCountry === 'Malaysia' ? pricing.notarization_my_fee : 0)
    : 0;

  const estimatedCredits = aiCost + humanReviewCost + certificateCost + notarizationCost;

  // Service type for display/submission
  const getServiceType = () => {
    if (includeNotarization) return 'Notarized Translation';
    if (includeCertificate) return 'Certified Translation';
    if (includeHumanReview) return 'AI + Human Review';
    return 'AI Translation';
  };
  const serviceType = getServiceType();

  // Calculate total available credits (support both snake_case and PascalCase)
  const totalCredits =
    (user?.credits_balance || user?.['Credits Balance'] || user?.['Purchased Credits'] || 0) +
    (user?.daily_free_credits || user?.['Daily Free Credits'] || user?.['Free Credits Daily'] || 10) +
    (user?.bonus_credits || user?.['Bonus Credits'] || 0);

  const creditsNeeded = Math.max(0, estimatedCredits - totalCredits);
  const hasInsufficientCredits = creditsNeeded > 0;

  const allFilesUploaded = uploadedFiles.length > 0 && uploadedFiles.every(f => f.status === 'done');

  const handleSubmit = async () => {
    // Validation
    if (!allFilesUploaded) {
      toast({
        title: 'Error',
        description: 'Please wait for all files to finish uploading',
        variant: 'destructive',
      });
      return;
    }

    if (!sourceLanguage || !targetLanguage) {
      toast({
        title: 'Error',
        description: 'Please select source and target languages',
        variant: 'destructive',
      });
      return;
    }

    if (sourceLanguage === targetLanguage) {
      toast({
        title: 'Error',
        description: 'Source and target languages cannot be the same',
        variant: 'destructive',
      });
      return;
    }

    if (includeNotarization && !notarizationCountry) {
      toast({
        title: 'Error',
        description: 'Please select notarization country',
        variant: 'destructive',
      });
      return;
    }

    if (totalCredits < estimatedCredits) {
      setShowTopUpModal(true);
      return;
    }

    setIsSubmitting(true);

    try {
      // Prepare order data with actual page counts from upload response
      const documents = uploadedFiles
        .filter(f => f.status === 'done')
        .map(f => ({
          filename: f.file.name,
          pages: f.pages || 1,
          type: f.file.name.split('.').pop()?.toUpperCase() || 'PDF',
          document_id: f.documentId,
          temp_path: f.tempPath,
          session_id: f.sessionId,
          content_type: f.contentType,
          needs_ocr: f.needsOcr,
        }));

      const orderData = {
        documents,
        source_lang: sourceLanguage,
        target_lang: targetLanguage,
        service_type: serviceType,
        include_human_review: includeHumanReview,
        include_certificate: includeCertificate,
        notarization_country: includeNotarization ? notarizationCountry : undefined,
      };

      const result = await api.createOrder(orderData);

      toast({
        title: 'Order Created!',
        description: `Order ${result.order?.['Order ID'] || ''} has been created successfully.`,
      });

      router.push('/dashboard/orders');
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.message || 'Failed to create order',
        variant: 'destructive',
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="p-6 lg:p-8 max-w-4xl mx-auto">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">New Translation Order</h1>
        <p className="text-gray-600 mt-1">Upload your documents and select translation options</p>
      </div>

      {/* Step 1: File Upload */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>Step 1: Upload Documents</CardTitle>
          <CardDescription>
            Supported formats: PDF, JPG, PNG, DOC, DOCX, TXT (Max 10MB per file)
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div
            {...getRootProps()}
            className={`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${
              isDragActive ? 'border-blue-500 bg-blue-50' : 'border-gray-300 hover:border-gray-400'
            }`}
          >
            <input {...getInputProps()} />
            <Upload className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <p className="text-lg font-medium text-gray-700 mb-2">
              {isDragActive ? 'Drop files here' : 'Drag & drop files here'}
            </p>
            <p className="text-sm text-gray-500">or click to browse</p>
          </div>

          {/* File List with Upload Progress */}
          {uploadedFiles.length > 0 && (
            <div className="mt-4 space-y-2">
              {uploadedFiles.map((item, index) => (
                <div
                  key={index}
                  className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
                >
                  <div className="flex items-center space-x-3 flex-1">
                    {item.status === 'uploading' && (
                      <Loader2 className="h-5 w-5 text-blue-600 animate-spin" />
                    )}
                    {item.status === 'done' && (
                      <CheckCircle className="h-5 w-5 text-green-600" />
                    )}
                    {item.status === 'error' && (
                      <AlertCircle className="h-5 w-5 text-red-600" />
                    )}
                    {item.status === 'pending' && (
                      <FileText className="h-5 w-5 text-gray-400" />
                    )}
                    <div className="flex-1">
                      <p className="text-sm font-medium">{item.file.name}</p>
                      <div className="flex items-center gap-2">
                        <p className="text-xs text-gray-500">
                          {(item.file.size / 1024 / 1024).toFixed(2)} MB
                          {item.status === 'done' && item.pages > 0 && (
                            <span className="ml-2 text-blue-600">• {item.pages} page{item.pages > 1 ? 's' : ''}</span>
                          )}
                        </p>
                        {item.status === 'uploading' && (
                          <div className="flex-1 max-w-[200px]">
                            <div className="h-1 bg-gray-200 rounded-full overflow-hidden">
                              <div
                                className="h-full bg-blue-600 transition-all duration-300"
                                style={{ width: `${item.progress}%` }}
                              />
                            </div>
                          </div>
                        )}
                        {item.status === 'error' && (
                          <span className="text-xs text-red-600">{item.error}</span>
                        )}
                      </div>
                    </div>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => removeFile(index)}
                    className="text-red-600 hover:text-red-700"
                    disabled={item.status === 'uploading'}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Step 2: Language Selection */}
      <Card className="mb-6 overflow-visible">
        <CardHeader>
          <CardTitle>Step 2: Select Languages</CardTitle>
          <CardDescription>Choose source and target languages (100+ languages supported)</CardDescription>
        </CardHeader>
        <CardContent className="overflow-visible">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Source Language</Label>
              <SearchableLanguageSelect
                value={sourceLanguage}
                onChange={setSourceLanguage}
                placeholder="Search or select language..."
                excludeCode={targetLanguage}
              />
            </div>

            <div className="space-y-2">
              <Label>Target Language</Label>
              <SearchableLanguageSelect
                value={targetLanguage}
                onChange={setTargetLanguage}
                placeholder="Search or select language..."
                excludeCode={sourceLanguage}
              />
            </div>
          </div>

          {/* Language pricing info */}
          {sourceLanguage && targetLanguage && languageMultiplier > 1.0 && (
            <div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
              <div className="flex items-start gap-2">
                <Info className="h-4 w-4 text-blue-600 mt-0.5 flex-shrink-0" />
                <div className="text-sm">
                  <p className="font-medium text-blue-800">
                    Regional rate adjustment (+{Math.round((languageMultiplier - 1) * 100)}%)
                  </p>
                  <p className="text-blue-700 mt-1">
                    Translator rates vary by region based on local market conditions.
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* OCR quality warning for non-Qwen languages */}
          {sourceLanguage && hasOcrFiles && ocrQualityMultiplier > 1.0 && (
            <div className="mt-4 p-3 bg-orange-50 border border-orange-200 rounded-lg">
              <div className="flex items-start gap-2">
                <AlertTriangle className="h-4 w-4 text-orange-600 mt-0.5 flex-shrink-0" />
                <div className="text-sm">
                  <p className="font-medium text-orange-800">
                    Scanned document adjustment (+{Math.round((ocrQualityMultiplier - 1) * 100)}%)
                  </p>
                  <p className="text-orange-700 mt-1">
                    {languages.find(l => l.code === sourceLanguage)?.name} documents may need extra review when scanned.
                    This covers additional quality checking for best results.
                  </p>
                </div>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Step 3: Select Services */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>Step 3: Select Services</CardTitle>
          <CardDescription>Choose the services you need (AI translation always included)</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* AI Translation - Always included */}
          <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
            <div className="flex items-start justify-between">
              <div className="flex items-center gap-3">
                <div className="w-5 h-5 rounded bg-blue-600 flex items-center justify-center">
                  <Check className="h-3 w-3 text-white" />
                </div>
                <div>
                  <p className="font-medium text-blue-900">AI Translation</p>
                  <p className="text-sm text-blue-700">Instant AI-powered translation (always included)</p>
                </div>
              </div>
              <span className={`font-bold ${includeHumanReview ? 'text-green-600' : 'text-blue-600'}`}>
                {includeHumanReview ? 'FREE' : `${pricing.ai_translation_base_cost} credit/page`}
              </span>
            </div>
          </div>

          {/* Human Review - Optional (PHASE 2 - COMING SOON) */}
          <div
            className={`p-4 border-2 rounded-lg transition-all opacity-50 cursor-not-allowed border-gray-200 bg-gray-50`}
          >
            <div className="flex items-start justify-between">
              <div className="flex items-center gap-3">
                <Checkbox
                  checked={false}
                  disabled
                  className="mt-0.5"
                />
                <div>
                  <div className="flex items-center gap-2">
                    <p className="font-medium">Human Review</p>
                    <span className="px-2 py-0.5 text-xs font-semibold bg-orange-100 text-orange-700 rounded">Coming Soon</span>
                  </div>
                  <p className="text-sm text-gray-600">AI translation + professional review & quality guarantee</p>
                  <p className="text-xs text-gray-500 mt-1">24-48 hour delivery</p>
                </div>
              </div>
              <div className="text-right">
                <span className="font-bold text-gray-400">
                  +{Math.round(pricing.human_review_base_cost * totalHumanReviewMultiplier).toLocaleString()} cr/page
                </span>
              </div>
            </div>
          </div>

          {/* Certificate - PHASE 2 - COMING SOON */}
          <div
            className={`p-4 border-2 rounded-lg transition-all opacity-50 cursor-not-allowed border-gray-200 bg-gray-50`}
          >
            <div className="flex items-start justify-between">
              <div className="flex items-center gap-3">
                <Checkbox
                  checked={false}
                  disabled
                  className="mt-0.5"
                />
                <div>
                  <div className="flex items-center gap-2">
                    <p className="font-medium">Translation Certificate</p>
                    <span className="px-2 py-0.5 text-xs font-semibold bg-orange-100 text-orange-700 rounded">Coming Soon</span>
                  </div>
                  <p className="text-sm text-gray-600">Official certificate for government agencies</p>
                  <p className="text-xs text-gray-500 mt-1">Accepted by MOM, universities</p>
                </div>
              </div>
              <span className="font-bold text-gray-400">
                +{pricing.certificate_fee.toLocaleString()} credits
              </span>
            </div>
          </div>

          {/* Notarization - PHASE 2 - COMING SOON */}
          <div
            className={`p-4 border-2 rounded-lg transition-all opacity-50 cursor-not-allowed border-gray-200 bg-gray-50`}
          >
            <div className="flex items-start justify-between">
              <div className="flex items-center gap-3">
                <Checkbox
                  checked={false}
                  disabled
                  className="mt-0.5"
                />
                <div>
                  <div className="flex items-center gap-2">
                    <p className="font-medium">Notarization</p>
                    <span className="px-2 py-0.5 text-xs font-semibold bg-orange-100 text-orange-700 rounded">Coming Soon</span>
                  </div>
                  <p className="text-sm text-gray-600">Full notarization with government authentication</p>
                  <p className="text-xs text-gray-500 mt-1">Required by ICA, court-ready, 3-5 business days</p>
                </div>
              </div>
              <div className="text-right">
                <span className="font-bold text-gray-400">
                  +{pricing.notarization_sg_fee.toLocaleString()} credits
                </span>
                <span className="text-xs text-gray-500 block">(Singapore)</span>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Step 4: Review & Submit */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>Step 4: Review & Submit</CardTitle>
          <CardDescription>Verify your order details before submitting</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Files</span>
              <span className="font-medium">
                {uploadedFiles.filter(f => f.status === 'done').length} file(s) uploaded
              </span>
            </div>
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Translation</span>
              <span className="font-medium">
                {languages.find(l => l.code === sourceLanguage)?.name || '-'} →{' '}
                {languages.find(l => l.code === targetLanguage)?.name || '-'}
              </span>
            </div>
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Service</span>
              <span className="font-medium">{serviceType}</span>
            </div>
            <div className="flex justify-between py-2 border-b">
              <span className="text-gray-600">Total Pages</span>
              <span className="font-medium">{totalPages} page{totalPages !== 1 ? 's' : ''}</span>
            </div>
            <div className="flex justify-between py-3 bg-blue-50 -mx-6 px-6">
              <span className="font-semibold text-lg">Estimated Cost</span>
              <span className="font-bold text-lg text-blue-600">
                {estimatedCredits.toLocaleString()} credits
              </span>
            </div>
            <div className="flex justify-between py-2">
              <span className="text-gray-600">Your Balance</span>
              <span className={`font-medium ${totalCredits < estimatedCredits ? 'text-red-600' : 'text-green-600'}`}>
                {totalCredits.toLocaleString()} credits
              </span>
            </div>
            {hasInsufficientCredits && (
              <div className="bg-red-50 border border-red-200 p-4 rounded-lg">
                <div className="flex items-start gap-3">
                  <AlertTriangle className="h-5 w-5 text-red-600 flex-shrink-0 mt-0.5" />
                  <div className="flex-1">
                    <h4 className="font-medium text-red-800">Insufficient Credits</h4>
                    <p className="text-sm text-red-700 mt-1">
                      You need {creditsNeeded.toLocaleString()} more credits to place this order.
                    </p>
                    <Button
                      size="sm"
                      className="mt-3"
                      onClick={() => setShowTopUpModal(true)}
                    >
                      <CreditCard className="mr-2 h-4 w-4" />
                      Top Up Now
                    </Button>
                  </div>
                </div>
              </div>
            )}
          </div>

          <div className="mt-6 flex gap-4">
            <Button
              onClick={handleSubmit}
              disabled={
                isSubmitting ||
                !allFilesUploaded ||
                uploadedFiles.length === 0 ||
                !sourceLanguage ||
                !targetLanguage
              }
              className="flex-1"
              size="lg"
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Creating Order...
                </>
              ) : hasInsufficientCredits ? (
                <>
                  <CreditCard className="mr-2 h-4 w-4" />
                  Top Up & Submit
                </>
              ) : (
                'Submit Order'
              )}
            </Button>
            <Button
              variant="outline"
              onClick={() => router.push('/dashboard')}
              size="lg"
            >
              Cancel
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Top-Up Modal */}
      {showTopUpModal && (
        <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto">
          <Card className="max-w-2xl w-full my-4 max-h-[90vh] overflow-y-auto bg-white shadow-2xl">
            <CardHeader className="relative">
              <button
                onClick={closeTopUpModal}
                className="absolute right-4 top-4 p-1 rounded-full hover:bg-gray-100"
              >
                <X className="h-5 w-5 text-gray-500" />
              </button>
              <CardTitle className="flex items-center gap-2">
                <CreditCard className="h-5 w-5 text-blue-600" />
                {verificationStatus === 'success' ? 'Payment Successful' : paymentDetails ? 'Complete Payment' : 'Top Up Credits'}
              </CardTitle>
              <CardDescription>
                {verificationStatus === 'success' ? (
                  <span className="text-green-600">Your credits are being added to your account</span>
                ) : paymentDetails ? (
                  (() => {
                    const amount = paymentDetails.paynow?.amount_sgd || paymentDetails.amount || 0;
                    const baseCredits = paymentDetails.base_credits || (amount * 1000);
                    const bonusCredits = paymentDetails.bonus_credits || 0;
                    const totalCredits = paymentDetails.total_credits || paymentDetails.credits || baseCredits + bonusCredits;

                    return (
                      <span>
                        Pay S${amount.toFixed(2)} to receive{' '}
                        <span className="font-semibold">{totalCredits.toLocaleString()} credits</span>
                        {bonusCredits > 0 && (
                          <span className="text-green-600 ml-1">
                            (incl. {bonusCredits.toLocaleString()} bonus)
                          </span>
                        )}
                      </span>
                    );
                  })()
                ) : (
                  <span>You need {creditsNeeded.toLocaleString()} more credits to complete this order</span>
                )}
              </CardDescription>
            </CardHeader>
            <CardContent>
              {/* Success State */}
              {verificationStatus === 'success' && (
                <div className="text-center py-8">
                  <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <CheckCircle className="h-8 w-8 text-green-600" />
                  </div>
                  <h3 className="text-lg font-semibold text-green-700 mb-2">Payment Submitted!</h3>
                  <p className="text-gray-600">Your credits will be added shortly. Refreshing...</p>
                </div>
              )}

              {/* Payment Flow */}
              {verificationStatus !== 'success' && !paymentDetails && (
                <div className="space-y-4">
                  {/* Suggested Amount */}
                  <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
                    <div className="flex items-center gap-2 mb-2">
                      <Info className="h-4 w-4 text-blue-600" />
                      <span className="font-medium text-blue-800">Suggested Amount</span>
                    </div>
                    <p className="text-sm text-blue-700">
                      To cover this order ({creditsNeeded.toLocaleString()} credits needed), we suggest topping up at least <strong>S${Math.ceil(creditsNeeded / 1000)}</strong>.
                    </p>
                  </div>

                  {/* Custom Amount Input */}
                  <div>
                    <Label htmlFor="topupAmount" className="font-medium">Enter amount (SGD)</Label>
                    <div className="flex gap-3 mt-2">
                      <div className="flex-1 relative">
                        <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">S$</span>
                        <Input
                          id="topupAmount"
                          type="number"
                          min="1"
                          step="1"
                          placeholder={String(Math.ceil(creditsNeeded / 1000))}
                          value={customAmount || Math.ceil(creditsNeeded / 1000)}
                          onChange={(e) => setCustomAmount(e.target.value)}
                          className="pl-10 text-lg font-semibold"
                          disabled={isPurchasing}
                        />
                      </div>
                      <Button
                        onClick={handleCustomTopUp}
                        disabled={isPurchasing || (customAmount ? parseFloat(customAmount) * 1000 : Math.ceil(creditsNeeded / 1000) * 1000) < creditsNeeded}
                        size="lg"
                      >
                        {isPurchasing && selectedPackage === 'custom' ? (
                          <Loader2 className="h-4 w-4 animate-spin" />
                        ) : (
                          'Proceed to Pay'
                        )}
                      </Button>
                    </div>
                    <div className="mt-2 text-sm">
                      <span className="text-gray-600">
                        = {((customAmount ? parseFloat(customAmount) : Math.ceil(creditsNeeded / 1000)) * 1000).toLocaleString()} credits
                      </span>
                      {(customAmount ? parseFloat(customAmount) * 1000 : Math.ceil(creditsNeeded / 1000) * 1000) >= creditsNeeded ? (
                        <span className="text-green-600 ml-2">✓ Covers your order</span>
                      ) : (
                        <span className="text-red-600 ml-2">✗ Need at least S${Math.ceil(creditsNeeded / 1000)}</span>
                      )}
                    </div>
                  </div>

                  {/* Rate info */}
                  <p className="text-xs text-gray-500 text-center">
                    1 SGD = 1,000 credits • Instant top-up via PayNow
                  </p>
                </div>
              )}

              {/* QR Payment Section */}
              {paymentDetails && verificationStatus !== 'success' && (
                <div className="space-y-4">
                  {/* QR Code */}
                  <div className="text-center">
                    {paymentDetails.paynow?.qr_code ? (
                      <div className="inline-block p-3 bg-white rounded-lg border-2 border-gray-200">
                        <img
                          src={paymentDetails.paynow.qr_code}
                          alt="PayNow QR Code"
                          className="w-40 h-40 mx-auto"
                        />
                      </div>
                    ) : (
                      <div className="w-40 h-40 bg-gray-100 rounded-lg flex items-center justify-center mx-auto">
                        <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
                      </div>
                    )}
                    <p className="text-sm text-gray-600 mt-2">Scan with your banking app</p>
                  </div>

                  {/* Payment Details */}
                  <div className="bg-gray-50 rounded-lg p-3 space-y-2 text-sm">
                    <div className="flex justify-between">
                      <span className="text-gray-600">Amount</span>
                      <div className="flex items-center gap-2">
                        <span className="font-semibold">
                          S${paymentDetails.paynow?.amount_sgd?.toFixed(2) || paymentDetails.amount}
                        </span>
                        <button
                          onClick={() => copyToClipboard(
                            String(paymentDetails.paynow?.amount_sgd || paymentDetails.amount),
                            'amount'
                          )}
                          className="p-1 hover:bg-gray-200 rounded"
                        >
                          {copiedField === 'amount' ? (
                            <Check className="h-3 w-3 text-green-600" />
                          ) : (
                            <Copy className="h-3 w-3 text-gray-500" />
                          )}
                        </button>
                      </div>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-600">Reference</span>
                      <div className="flex items-center gap-2">
                        <span className="font-mono text-xs">{paymentDetails.paynow?.reference}</span>
                        <button
                          onClick={() => copyToClipboard(paymentDetails.paynow?.reference || '', 'reference')}
                          className="p-1 hover:bg-gray-200 rounded"
                        >
                          {copiedField === 'reference' ? (
                            <Check className="h-3 w-3 text-green-600" />
                          ) : (
                            <Copy className="h-3 w-3 text-gray-500" />
                          )}
                        </button>
                      </div>
                    </div>
                  </div>

                  {/* Transaction ID Input */}
                  <div className="pt-3 border-t">
                    <Label htmlFor="topupTransactionId">Transaction ID</Label>
                    <Input
                      id="topupTransactionId"
                      placeholder="Enter transaction ID from payment confirmation"
                      value={transactionId}
                      onChange={(e) => setTransactionId(e.target.value)}
                      className="mt-1"
                      disabled={isVerifying}
                    />
                    <Button
                      className="w-full mt-3"
                      onClick={handleVerifyPayment}
                      disabled={isVerifying || !transactionId.trim()}
                    >
                      {isVerifying ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          Verifying...
                        </>
                      ) : (
                        <>
                          <CheckCircle className="mr-2 h-4 w-4" />
                          I've Made Payment
                        </>
                      )}
                    </Button>
                  </div>

                  {/* Error State */}
                  {verificationStatus === 'error' && (
                    <div className="bg-red-50 border border-red-200 rounded-lg p-3">
                      <p className="text-sm text-red-700">
                        Verification failed. Please check your transaction ID and try again.
                      </p>
                    </div>
                  )}

                  {/* Back button */}
                  <Button
                    variant="ghost"
                    className="w-full"
                    onClick={() => {
                      setPaymentDetails(null);
                      setTransactionId('');
                      setVerificationStatus('idle');
                      setSelectedPackage(null);
                    }}
                  >
                    Choose Different Amount
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
}
