'use client';

import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import {
  ArrowLeft,
  Edit,
  DollarSign,
  Printer,
  User,
} from 'lucide-react';
import ProtectedRoute from '../../../protected-route';
import SidebarLayout from '../../../components/sidebar-layout';
import { useTranslations } from '../../../hooks/useTranslations';
import { useSettings } from '../../../contexts/SettingsContext';
import { useFormatCurrency } from '../../../hooks/useFormatCurrency';
import {
  formatClinicStreetLine,
  formatClinicCityLine,
  formatClinicPhoneEmail,
} from '@/lib/clinic-display';

export default function InvoiceDetailPage() {
  const router = useRouter();
  const params = useParams();
  const { t, translationsLoaded } = useTranslations();
  const { settings } = useSettings();
  const formatCurrency = useFormatCurrency();
  const [invoice, setInvoice] = useState<any>(null);
  const [payments, setPayments] = useState<any[]>([]);
  const [totalPaid, setTotalPaid] = useState(0);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (params.id) {
      fetchInvoice();
    }
  }, [params.id]);

  const fetchInvoice = async () => {
    try {
      setLoading(true);
      const response = await fetch(`/api/billing/invoices/${params.id}`);
      if (response.ok) {
        const data = await response.json();
        setInvoice(data.invoice);
        setPayments(data.payments || []);
        setTotalPaid(data.totalPaid || 0);
      }
    } catch (error) {
      console.error('Error fetching invoice:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (date: string | Date) => {
    return new Date(date).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'paid': return 'bg-green-100 text-green-800';
      case 'pending': return 'bg-yellow-100 text-yellow-800';
      case 'partial': return 'bg-blue-100 text-blue-800';
      case 'draft': return 'bg-gray-100 text-gray-800';
      case 'cancelled': return 'bg-red-100 text-red-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  if (!translationsLoaded || loading) {
    return (
      <ProtectedRoute>
        <SidebarLayout title={t('billing.invoiceDetails')} description="">
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-4 text-gray-600">{t('common.loading')}</p>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  if (!invoice) {
    return (
      <ProtectedRoute>
        <SidebarLayout title={t('billing.invoiceDetails')} description="">
          <div className="text-center py-12">
            <p className="text-gray-600">{t('billing.invoiceNotFound')}</p>
            <Link href="/billing" className="mt-4 inline-block text-blue-600 hover:text-blue-700">
              {t('common.back')} {t('billing.toBilling')}
            </Link>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  const remaining = invoice.total - totalPaid;
  const hospitalName = settings?.systemTitle || 'Medical Center';
  const addr = settings?.address;
  const streetLine = formatClinicStreetLine(addr);
  const cityLine = formatClinicCityLine(addr);
  const phoneEmailLine = formatClinicPhoneEmail(addr);
  const billingFooterContact = (() => {
    const phone = (addr?.phone || '').trim();
    const email = (addr?.email || '').trim();
    if (phone && email) {
      return `please contact us at ${phone} or ${email}`;
    }
    if (phone) return `please contact us at ${phone}`;
    if (email) return `please email us at ${email}`;
    return 'please contact our billing department for any inquiries';
  })();

  return (
    <ProtectedRoute>
      <SidebarLayout title={t('billing.invoiceDetails')} description={invoice.invoiceNumber}>
        <div className="space-y-6">
          {/* Header Actions - Hidden in print */}
          <div className="flex items-center justify-between print:hidden">
            <Link href="/billing" className="flex items-center gap-2 text-gray-600 hover:text-gray-900">
              <ArrowLeft className="h-5 w-5" />
              <span>{t('common.back')}</span>
            </Link>
            <div className="flex items-center gap-3">
              <button
                type="button"
                onClick={() => window.print()}
                className="flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
              >
                <Printer className="h-5 w-5" />
                <span>{t('billing.print')}</span>
              </button>
              <Link
                href={`/billing/invoices/${params.id}/edit`}
                className="flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
              >
                <Edit className="h-5 w-5" />
                <span>{t('billing.edit')}</span>
              </Link>
              {remaining > 0 && (
                <Link
                  href={`/billing/invoices/${params.id}/payment`}
                  className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  <DollarSign className="h-5 w-5" />
                  <span>{t('billing.addPayment')}</span>
                </Link>
              )}
            </div>
          </div>

          {/* ===== PRINT VIEW - Professional Invoice ===== */}
          <div className="hidden print:block invoice-print">
            {/* Header */}
            <div style={{ borderBottom: '3px solid #374151', paddingBottom: '16px', marginBottom: '24px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                {/* Logo & Hospital Info */}
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: '16px' }}>
                  {settings?.invoiceLogoUrl ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={settings.invoiceLogoUrl}
                      alt=""
                      style={{ maxHeight: '60px', maxWidth: '180px', objectFit: 'contain' }}
                    />
                  ) : (
                    <div
                      style={{
                        width: '60px',
                        height: '60px',
                        background: 'linear-gradient(135deg, #374151 0%, #6b7280 100%)',
                        borderRadius: '8px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        color: 'white',
                        fontSize: '22px',
                        fontWeight: 'bold',
                      }}
                    >
                      {hospitalName.trim().charAt(0).toUpperCase() || '·'}
                    </div>
                  )}
                  <div>
                    <h1 style={{ fontSize: '20pt', fontWeight: '700', color: '#1f2937', margin: 0, letterSpacing: '-0.5px' }}>
                      {hospitalName}
                    </h1>
                    {settings?.systemDescription ? (
                      <p style={{ fontSize: '9pt', color: '#4b5563', margin: '2px 0 0 0' }}>{settings.systemDescription}</p>
                    ) : null}
                    {streetLine ? (
                      <p style={{ fontSize: '8pt', color: '#6b7280', margin: '6px 0 0 0' }}>{streetLine}</p>
                    ) : null}
                    {cityLine ? (
                      <p style={{ fontSize: '8pt', color: '#6b7280', margin: '2px 0 0 0' }}>{cityLine}</p>
                    ) : null}
                    {phoneEmailLine ? (
                      <p style={{ fontSize: '8pt', color: '#6b7280', margin: '2px 0 0 0' }}>{phoneEmailLine}</p>
                    ) : null}
                  </div>
                </div>
                {/* Invoice Title */}
                <div style={{ textAlign: 'right' }}>
                  <div style={{ 
                    background: '#f3f4f6', 
                    color: '#1f2937', 
                    padding: '10px 24px',
                    fontSize: '14pt',
                    fontWeight: '700',
                    letterSpacing: '3px',
                    border: '2px solid #374151'
                  }}>
                    INVOICE
                  </div>
                  <div style={{ marginTop: '12px' }}>
                    <p style={{ fontSize: '9pt', color: '#6b7280', margin: 0 }}>Invoice Number</p>
                    <p style={{ fontSize: '12pt', fontWeight: '700', color: '#111827', margin: '2px 0 0 0' }}>{invoice.invoiceNumber}</p>
                  </div>
                </div>
              </div>
            </div>

            {/* Invoice Details Bar */}
            <div style={{ 
              display: 'grid', 
              gridTemplateColumns: 'repeat(4, 1fr)', 
              gap: '1px', 
              background: '#e5e7eb',
              border: '1px solid #d1d5db',
              marginBottom: '24px'
            }}>
              <div style={{ background: '#f9fafb', padding: '12px 14px' }}>
                <p style={{ fontSize: '7pt', color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.5px', margin: 0 }}>Invoice Date</p>
                <p style={{ fontSize: '10pt', fontWeight: '600', color: '#111827', margin: '2px 0 0 0' }}>{formatDate(invoice.createdAt)}</p>
              </div>
              <div style={{ background: '#f9fafb', padding: '12px 14px' }}>
                <p style={{ fontSize: '7pt', color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.5px', margin: 0 }}>Due Date</p>
                <p style={{ fontSize: '10pt', fontWeight: '600', color: '#111827', margin: '2px 0 0 0' }}>{invoice.dueDate ? formatDate(invoice.dueDate) : 'Upon Receipt'}</p>
              </div>
              <div style={{ background: '#f9fafb', padding: '12px 14px' }}>
                <p style={{ fontSize: '7pt', color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.5px', margin: 0 }}>Status</p>
                <p style={{ 
                  fontSize: '10pt', 
                  fontWeight: '700', 
                  color: invoice.status === 'paid' ? '#166534' : invoice.status === 'pending' ? '#d97706' : '#111827', 
                  margin: '2px 0 0 0',
                  textTransform: 'uppercase'
                }}>{invoice.status}</p>
              </div>
              <div style={{ background: '#f9fafb', padding: '12px 14px' }}>
                <p style={{ fontSize: '7pt', color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.5px', margin: 0 }}>Amount Due</p>
                <p style={{ fontSize: '11pt', fontWeight: '700', color: remaining > 0 ? '#dc2626' : '#166534', margin: '2px 0 0 0' }}>
                  {formatCurrency(remaining > 0 ? remaining : 0)}
                </p>
              </div>
            </div>

            {/* Bill To Section */}
            <div style={{ marginBottom: '24px' }}>
              <div style={{ 
                background: '#f3f4f6', 
                color: '#374151', 
                padding: '8px 14px', 
                fontSize: '9pt', 
                fontWeight: '600', 
                letterSpacing: '0.5px',
                display: 'inline-block',
                marginBottom: '12px',
                border: '1px solid #d1d5db'
              }}>
                BILL TO
              </div>
              <div style={{ paddingLeft: '2px' }}>
                <p style={{ fontSize: '12pt', fontWeight: '700', color: '#111827', margin: '0 0 4px 0' }}>{invoice.patientName}</p>
                <p style={{ fontSize: '9pt', color: '#374151', fontWeight: '500', margin: '0 0 4px 0' }}>Patient ID: {invoice.hospitalPatientId || invoice.patientId}</p>
                <p style={{ fontSize: '9pt', color: '#4b5563', margin: '0 0 2px 0' }}>{invoice.patientEmail}</p>
                {invoice.patientPhone && (
                  <p style={{ fontSize: '9pt', color: '#4b5563', margin: 0 }}>{invoice.patientPhone}</p>
                )}
              </div>
            </div>

            {/* Items Table */}
            <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: '24px' }}>
              <thead>
                <tr style={{ background: '#f3f4f6' }}>
                  <th style={{ padding: '12px 14px', textAlign: 'left', fontSize: '8pt', fontWeight: '600', color: '#374151', textTransform: 'uppercase', letterSpacing: '0.5px', width: '50%', borderBottom: '2px solid #374151' }}>
                    Description
                  </th>
                  <th style={{ padding: '12px 14px', textAlign: 'center', fontSize: '8pt', fontWeight: '600', color: '#374151', textTransform: 'uppercase', letterSpacing: '0.5px', width: '10%', borderBottom: '2px solid #374151' }}>
                    Qty
                  </th>
                  <th style={{ padding: '12px 14px', textAlign: 'right', fontSize: '8pt', fontWeight: '600', color: '#374151', textTransform: 'uppercase', letterSpacing: '0.5px', width: '20%', borderBottom: '2px solid #374151' }}>
                    Unit Price
                  </th>
                  <th style={{ padding: '12px 14px', textAlign: 'right', fontSize: '8pt', fontWeight: '600', color: '#374151', textTransform: 'uppercase', letterSpacing: '0.5px', width: '20%', borderBottom: '2px solid #374151' }}>
                    Amount
                  </th>
                </tr>
              </thead>
              <tbody>
                {invoice.items.map((item: any, index: number) => (
                  <tr key={index} style={{ borderBottom: '1px solid #e5e7eb', background: index % 2 === 0 ? 'white' : '#f9fafb' }}>
                    <td style={{ padding: '12px 14px', fontSize: '9pt', color: '#1f2937' }}>
                      <span style={{ fontWeight: '500' }}>{item.description}</span>
                      {item.serviceType && (
                        <span style={{ display: 'block', fontSize: '8pt', color: '#6b7280', marginTop: '2px', textTransform: 'capitalize' }}>
                          {item.serviceType}
                        </span>
                      )}
                    </td>
                    <td style={{ padding: '12px 14px', textAlign: 'center', fontSize: '9pt', color: '#374151' }}>
                      {item.quantity}
                    </td>
                    <td style={{ padding: '12px 14px', textAlign: 'right', fontSize: '9pt', color: '#374151' }}>
                      {formatCurrency(item.unitPrice)}
                    </td>
                    <td style={{ padding: '12px 14px', textAlign: 'right', fontSize: '10pt', fontWeight: '600', color: '#111827' }}>
                      {formatCurrency(item.total)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>

            {/* Totals Section */}
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '24px' }}>
              <div style={{ width: '280px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>
                  <span style={{ fontSize: '9pt', color: '#6b7280' }}>Subtotal</span>
                  <span style={{ fontSize: '10pt', fontWeight: '500', color: '#374151' }}>{formatCurrency(invoice.subtotal)}</span>
                </div>
                {invoice.tax > 0 && (
                  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>
                    <span style={{ fontSize: '9pt', color: '#6b7280' }}>Tax</span>
                    <span style={{ fontSize: '10pt', fontWeight: '500', color: '#374151' }}>{formatCurrency(invoice.tax)}</span>
                  </div>
                )}
                {invoice.discount > 0 && (
                  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>
                    <span style={{ fontSize: '9pt', color: '#6b7280' }}>Discount</span>
                    <span style={{ fontSize: '10pt', fontWeight: '500', color: '#374151' }}>-{formatCurrency(invoice.discount)}</span>
                  </div>
                )}
                <div style={{ display: 'flex', justifyContent: 'space-between', padding: '12px 0', background: '#f9fafb', marginTop: '8px', borderTop: '2px solid #374151' }}>
                  <span style={{ fontSize: '10pt', fontWeight: '700', color: '#111827' }}>Total</span>
                  <span style={{ fontSize: '12pt', fontWeight: '700', color: '#1f2937' }}>{formatCurrency(invoice.total)}</span>
                </div>
                {totalPaid > 0 && (
                  <>
                    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>
                      <span style={{ fontSize: '9pt', color: '#6b7280' }}>Amount Paid</span>
                      <span style={{ fontSize: '10pt', fontWeight: '500', color: '#374151' }}>{formatCurrency(totalPaid)}</span>
                    </div>
                    {remaining > 0 && (
                      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 12px', background: '#fef2f2', marginTop: '8px' }}>
                        <span style={{ fontSize: '10pt', fontWeight: '700', color: '#dc2626' }}>Balance Due</span>
                        <span style={{ fontSize: '12pt', fontWeight: '700', color: '#dc2626' }}>{formatCurrency(remaining)}</span>
                      </div>
                    )}
                  </>
                )}
              </div>
            </div>

            {/* Payment Info Box */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px', marginBottom: '24px' }}>
              {/* Payment Methods */}
              <div style={{ border: '1px solid #d1d5db', borderRadius: '4px', overflow: 'hidden' }}>
                <div style={{ background: '#f3f4f6', padding: '10px 14px', borderBottom: '1px solid #d1d5db' }}>
                  <p style={{ fontSize: '8pt', fontWeight: '600', color: '#374151', textTransform: 'uppercase', letterSpacing: '0.5px', margin: 0 }}>Payment Methods</p>
                </div>
                <div style={{ padding: '12px 14px', fontSize: '9pt', color: '#4b5563', lineHeight: '1.6' }}>
                  <p style={{ margin: '0 0 6px 0' }}><strong>Cash:</strong> Pay at the billing counter</p>
                  <p style={{ margin: '0 0 6px 0' }}><strong>Card:</strong> Visa, MasterCard, AMEX accepted</p>
                  <p style={{ margin: '0 0 6px 0' }}><strong>Bank Transfer:</strong> Account details available on request</p>
                  <p style={{ margin: 0 }}><strong>Insurance:</strong> Please provide your policy details</p>
                </div>
              </div>

              {/* Notes */}
              <div style={{ border: '1px solid #d1d5db', borderRadius: '4px', overflow: 'hidden' }}>
                <div style={{ background: '#f3f4f6', padding: '10px 14px', borderBottom: '1px solid #d1d5db' }}>
                  <p style={{ fontSize: '8pt', fontWeight: '600', color: '#374151', textTransform: 'uppercase', letterSpacing: '0.5px', margin: 0 }}>Notes & Terms</p>
                </div>
                <div style={{ padding: '12px 14px', fontSize: '9pt', color: '#4b5563', lineHeight: '1.6' }}>
                  {invoice.notes ? (
                    <p style={{ margin: 0 }}>{invoice.notes}</p>
                  ) : (
                    <>
                      <p style={{ margin: '0 0 6px 0' }}>• Payment is due upon receipt unless otherwise agreed</p>
                      <p style={{ margin: '0 0 6px 0' }}>• Please include invoice number with payment</p>
                      <p style={{ margin: 0 }}>• Contact billing department for any queries</p>
                    </>
                  )}
                </div>
              </div>
            </div>

            {/* Payment History (if any) */}
            {payments.length > 0 && (
              <div style={{ marginBottom: '24px' }}>
                <p style={{ fontSize: '9pt', fontWeight: '600', color: '#374151', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '10px' }}>Payment History</p>
                <table style={{ width: '100%', borderCollapse: 'collapse', border: '1px solid #d1d5db' }}>
                  <thead>
                    <tr style={{ background: '#f3f4f6' }}>
                      <th style={{ padding: '8px 12px', textAlign: 'left', fontSize: '8pt', fontWeight: '600', color: '#374151', borderBottom: '1px solid #d1d5db' }}>Date</th>
                      <th style={{ padding: '8px 12px', textAlign: 'left', fontSize: '8pt', fontWeight: '600', color: '#374151', borderBottom: '1px solid #d1d5db' }}>Method</th>
                      <th style={{ padding: '8px 12px', textAlign: 'left', fontSize: '8pt', fontWeight: '600', color: '#374151', borderBottom: '1px solid #d1d5db' }}>Reference</th>
                      <th style={{ padding: '8px 12px', textAlign: 'right', fontSize: '8pt', fontWeight: '600', color: '#374151', borderBottom: '1px solid #d1d5db' }}>Amount</th>
                    </tr>
                  </thead>
                  <tbody>
                    {payments.map((payment: any, index: number) => (
                      <tr key={payment._id} style={{ background: index % 2 === 0 ? 'white' : '#f9fafb' }}>
                        <td style={{ padding: '8px 12px', fontSize: '9pt', color: '#374151', borderBottom: '1px solid #e5e7eb' }}>{formatDate(payment.paymentDate)}</td>
                        <td style={{ padding: '8px 12px', fontSize: '9pt', color: '#374151', borderBottom: '1px solid #e5e7eb', textTransform: 'capitalize' }}>{payment.paymentMethod}</td>
                        <td style={{ padding: '8px 12px', fontSize: '9pt', color: '#6b7280', borderBottom: '1px solid #e5e7eb' }}>{payment.transactionId || '-'}</td>
                        <td style={{ padding: '8px 12px', fontSize: '9pt', fontWeight: '600', color: '#374151', textAlign: 'right', borderBottom: '1px solid #e5e7eb' }}>{formatCurrency(payment.amount)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}

            {/* Footer */}
            <div style={{ borderTop: '2px solid #374151', paddingTop: '16px', marginTop: '40px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div style={{ fontSize: '8pt', color: '#6b7280', maxWidth: '55%' }}>
                  <p style={{ margin: '0 0 8px 0', fontWeight: '600', color: '#374151' }}>Thank you for choosing {hospitalName}!</p>
                  <p style={{ margin: 0, lineHeight: '1.5' }}>
                    This invoice is computer-generated and is valid without signature. For any billing inquiries, {billingFooterContact}.
                  </p>
                </div>
                <div style={{ textAlign: 'right', fontSize: '7pt', color: '#6b7280' }}>
                  <p style={{ margin: '0 0 2px 0' }}>Invoice: {invoice.invoiceNumber}</p>
                  <p style={{ margin: '0 0 2px 0' }}>Generated: {new Date().toLocaleString()}</p>
                  <p style={{ margin: '0 0 10px 0' }}>Page 1 of 1</p>
                  <div style={{ 
                    width: '60px', 
                    height: '60px', 
                    border: '1px solid #d1d5db',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: '6pt',
                    color: '#9ca3af',
                    marginLeft: 'auto'
                  }}>
                    QR Code
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* ===== SCREEN VIEW ===== */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 print:hidden">
            {/* Invoice Header */}
            <div className="mb-8">
              <div className="flex flex-wrap items-start gap-4 pb-6 mb-6 border-b border-gray-200">
                {settings?.invoiceLogoUrl ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={settings.invoiceLogoUrl}
                    alt=""
                    className="max-h-16 max-w-[200px] object-contain shrink-0"
                  />
                ) : (
                  <div className="w-14 h-14 rounded-lg bg-gradient-to-br from-gray-700 to-gray-500 flex items-center justify-center text-white text-xl font-bold shrink-0">
                    {hospitalName.trim().charAt(0).toUpperCase() || '·'}
                  </div>
                )}
                <div className="min-w-0 flex-1">
                  <p className="text-lg font-bold text-gray-900">{hospitalName}</p>
                  {settings?.systemDescription ? (
                    <p className="text-sm text-gray-600 mt-0.5">{settings.systemDescription}</p>
                  ) : null}
                  {streetLine ? <p className="text-xs text-gray-500 mt-2">{streetLine}</p> : null}
                  {cityLine ? <p className="text-xs text-gray-500">{cityLine}</p> : null}
                  {phoneEmailLine ? <p className="text-xs text-gray-500 mt-0.5">{phoneEmailLine}</p> : null}
                </div>
              </div>
              <div className="flex items-start justify-between mb-6">
                <div>
                  <h1 className="text-3xl font-bold text-gray-900 mb-2">INVOICE</h1>
                  <div className="mt-2">
                    <p className="text-sm text-gray-500">{t('billing.invoiceNumber')}</p>
                    <p className="text-xl font-semibold text-gray-900">{invoice.invoiceNumber}</p>
                  </div>
                </div>
                <div className="text-right">
                  <p className="text-sm text-gray-500 mb-1">{t('billing.date')}</p>
                  <p className="text-lg font-semibold text-gray-900">{formatDate(invoice.createdAt)}</p>
                  {invoice.dueDate && (
                    <>
                      <p className="text-sm text-gray-500 mt-2 mb-1">{t('billing.dueDate')}</p>
                      <p className="text-base font-medium text-gray-900">{formatDate(invoice.dueDate)}</p>
                    </>
                  )}
                </div>
              </div>
              <span className={`inline-block px-3 py-1 rounded-full text-sm font-medium ${getStatusColor(invoice.status)}`}>
                {t(`billing.statusLabels.${invoice.status}`)}
              </span>
            </div>

            {/* Patient Information */}
            <div className="border-t border-gray-300 pt-6 mb-6">
              <div className="flex items-center mb-4">
                <User className="w-5 h-5 text-gray-600 mr-2" />
                <h3 className="text-lg font-semibold text-gray-900">{t('billing.patientInformation')}</h3>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <p className="text-xs text-gray-500 mb-1">{t('billing.patient')}</p>
                  <p className="text-base font-semibold text-gray-900">{invoice.patientName}</p>
                </div>
                <div>
                  <p className="text-xs text-gray-500 mb-1">{t('billing.email')}</p>
                  <p className="text-base text-gray-900">{invoice.patientEmail}</p>
                </div>
                {invoice.patientPhone && (
                  <div>
                    <p className="text-xs text-gray-500 mb-1">{t('billing.phone')}</p>
                    <p className="text-base text-gray-900">{invoice.patientPhone}</p>
                  </div>
                )}
              </div>
            </div>

            {/* Invoice Items */}
            <div className="border-t border-gray-300 pt-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">{t('billing.invoiceItems')}</h3>
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-300">
                  <thead className="bg-gray-100">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wide">
                        {t('billing.itemDescription')}
                      </th>
                      <th className="px-4 py-3 text-right text-xs font-bold text-gray-700 uppercase tracking-wide">
                        {t('billing.quantity')}
                      </th>
                      <th className="px-4 py-3 text-right text-xs font-bold text-gray-700 uppercase tracking-wide">
                        {t('billing.unitPrice')}
                      </th>
                      <th className="px-4 py-3 text-right text-xs font-bold text-gray-700 uppercase tracking-wide">
                        {t('billing.total')}
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-300">
                    {invoice.items.map((item: any, index: number) => (
                      <tr key={index}>
                        <td className="px-4 py-3 text-sm text-gray-900">{item.description}</td>
                        <td className="px-4 py-3 text-sm text-gray-900 text-right">{item.quantity}</td>
                        <td className="px-4 py-3 text-sm text-gray-900 text-right">{formatCurrency(item.unitPrice)}</td>
                        <td className="px-4 py-3 text-sm font-semibold text-gray-900 text-right">{formatCurrency(item.total)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Totals */}
              <div className="mt-6 flex justify-end">
                <div className="w-full md:w-1/3 space-y-2">
                  <div className="flex justify-between text-gray-700">
                    <span className="font-medium">{t('billing.subtotal')}:</span>
                    <span className="font-semibold">{formatCurrency(invoice.subtotal)}</span>
                  </div>
                  {invoice.tax > 0 && (
                    <div className="flex justify-between text-gray-700">
                      <span className="font-medium">{t('billing.tax')}:</span>
                      <span className="font-semibold">{formatCurrency(invoice.tax)}</span>
                    </div>
                  )}
                  {invoice.discount > 0 && (
                    <div className="flex justify-between text-gray-700">
                      <span className="font-medium">{t('billing.discount')}:</span>
                      <span className="font-semibold">-{formatCurrency(invoice.discount)}</span>
                    </div>
                  )}
                  <div className="flex justify-between text-lg font-bold text-gray-900 pt-3 border-t-2 border-gray-900">
                    <span>{t('billing.grandTotal')}:</span>
                    <span className="text-blue-600">{formatCurrency(invoice.total)}</span>
                  </div>
                  {totalPaid > 0 && (
                    <>
                      <div className="flex justify-between text-gray-700 pt-3">
                        <span className="font-medium">{t('billing.paidAmount')}:</span>
                        <span className="font-semibold text-green-600">{formatCurrency(totalPaid)}</span>
                      </div>
                      {remaining > 0 && (
                        <div className="flex justify-between text-gray-700">
                          <span className="font-medium">{t('billing.remaining')}:</span>
                          <span className="font-semibold text-red-600">{formatCurrency(remaining)}</span>
                        </div>
                      )}
                    </>
                  )}
                </div>
              </div>

              {invoice.notes && (
                <div className="mt-6 pt-6 border-t border-gray-300">
                  <p className="text-xs font-semibold text-gray-700 mb-2">{t('billing.notes')}</p>
                  <p className="text-sm text-gray-900">{invoice.notes}</p>
                </div>
              )}
            </div>
          </div>

          {/* Payment History - Screen Only */}
          {payments.length > 0 && (
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 print:hidden">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">{t('billing.paymentHistory')}</h3>
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('billing.paymentDate')}</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('billing.paymentMethod')}</th>
                      <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">{t('billing.paymentAmount')}</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('billing.status')}</th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {payments.map((payment: any) => (
                      <tr key={payment._id}>
                        <td className="px-4 py-3 text-sm text-gray-900">{formatDate(payment.paymentDate)}</td>
                        <td className="px-4 py-3 text-sm text-gray-900">{t(`billing.${payment.paymentMethod}`)}</td>
                        <td className="px-4 py-3 text-sm font-medium text-gray-900 text-right">{formatCurrency(payment.amount)}</td>
                        <td className="px-4 py-3 text-sm">
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                            payment.status === 'completed' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
                          }`}>
                            {payment.status === 'completed' ? t('billing.paymentCompleted') : payment.status}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
