
import React, { useState } from 'react';
import { Screen, UserProfile, BillableActivity, CompanyProfile } from '../types';
import { Language, translations } from '../i18n';
import { MOCK_BILLABLE } from '../constants';

interface InvoicePreviewProps {
  navigateTo: (screen: Screen) => void;
  language: Language;
  user: UserProfile | null;
  selectedBillableIds: string[];
  hourlyRate: number;
  companyProfile: CompanyProfile;
}

const InvoicePreview: React.FC<InvoicePreviewProps> = ({ navigateTo, language, user, selectedBillableIds, hourlyRate, companyProfile }) => {
  const t = translations[language].invoice;
  const common = translations[language].common;
  const [isPreparingPrint, setIsPreparingPrint] = useState(false);
  
  const selectedItems = MOCK_BILLABLE.filter(item => selectedBillableIds.includes(item.id));
  const totalAmount = (selectedItems.length * hourlyRate).toFixed(2);
  const formattedAmount = language === 'nl' ? totalAmount.replace('.', ',') : totalAmount;

  const invoiceNumber = `INV-${new Date().getFullYear()}-${Math.floor(Math.random() * 10000).toString().padStart(4, '0')}`;
  const today = new Date().toLocaleDateString(language === 'nl' ? 'nl-NL' : 'en-US');
  const dueDate = new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toLocaleDateString(language === 'nl' ? 'nl-NL' : 'en-US');

  const handlePrint = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    
    if (typeof window.print !== 'function') {
      console.error('Printing is not supported in this browser/environment.');
      return;
    }

    setIsPreparingPrint(true);
    
    // We use a double requestAnimationFrame to ensure the state update 
    // ('Preparing...') is painted to the screen before the blocking window.print() 
    // is called. This maintains the "user gesture" context better than setTimeout.
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        try {
          window.print();
        } catch (error) {
          console.error('Print dialog failed to open:', error);
        } finally {
          setIsPreparingPrint(false);
        }
      });
    });
  };

  return (
    <div className="bg-slate-100 dark:bg-slate-900 min-h-screen">
      <header className="sticky top-0 z-50 bg-white/90 dark:bg-slate-800/90 backdrop-blur-md border-b border-slate-200 dark:border-slate-700 px-4 safe-area-pt pb-4 flex items-center justify-between print:hidden shadow-sm">
        <button 
          onClick={() => navigateTo('billing')} 
          type="button"
          className="p-2 -ml-2 text-primary flex items-center gap-1 active:opacity-70 transition-opacity"
        >
          <span className="material-icons">arrow_back</span>
          <span className="text-sm font-semibold">{common.back}</span>
        </button>
        <h1 className="text-lg font-bold">{t.title}</h1>
        <button 
          onClick={handlePrint}
          type="button"
          disabled={isPreparingPrint}
          className={`${
            isPreparingPrint ? 'bg-slate-400' : 'bg-primary hover:bg-primary/90'
          } text-white px-4 py-2 rounded-lg font-bold text-sm shadow-md active:scale-95 transition-all flex items-center gap-2 relative z-10`}
        >
          <span className={`material-icons text-lg ${isPreparingPrint ? 'animate-spin' : ''}`}>
            {isPreparingPrint ? 'sync' : 'print'}
          </span>
          {isPreparingPrint ? (language === 'nl' ? 'Voorbereiden...' : 'Preparing...') : t.print}
        </button>
      </header>

      <main className="p-4 md:p-8 flex justify-center">
        <div className="bg-white dark:bg-white dark:text-slate-900 w-full max-w-[210mm] min-h-[297mm] shadow-2xl p-[15mm] md:p-[20mm] flex flex-col print:shadow-none print:m-0 print:p-[10mm] print:max-w-none">
          
          {/* Invoice Header */}
          <div className="flex justify-between items-start mb-12 border-b-2 border-primary pb-8">
            <div className="flex items-center gap-4">
              {companyProfile.logoUrl && (
                <img src={companyProfile.logoUrl} alt="Logo" className="w-16 h-16 object-contain" />
              )}
              <div>
                <h2 className="text-3xl font-black text-primary tracking-tighter leading-tight">{companyProfile.name}</h2>
                <p className="text-sm font-bold text-slate-400 uppercase tracking-widest leading-none">Social Care Professional</p>
              </div>
            </div>
            <div className="text-right">
              <h3 className="text-3xl font-light text-slate-300 uppercase tracking-tighter mb-2">FACTUUR</h3>
              <p className="text-sm font-bold">{t.invoiceNumber}: <span className="text-slate-900">{invoiceNumber}</span></p>
            </div>
          </div>

          {/* Details Grid */}
          <div className="grid grid-cols-2 gap-12 mb-12">
            <div>
              <h4 className="text-xs font-black text-slate-400 uppercase tracking-widest mb-3">{t.from}</h4>
              <div className="text-sm space-y-1 font-medium">
                <p className="font-bold text-lg leading-tight">{companyProfile.name}</p>
                <p className="whitespace-pre-line">{companyProfile.address}</p>
                <p>{companyProfile.email}</p>
                <p>{t.kvk}: {companyProfile.kvk}</p>
                <p>{t.btw}: {companyProfile.btw}</p>
                {user && <p className="text-xs text-slate-400 mt-2">Dossier beheer: {user.fullName} (BIG: {user.bigNumber})</p>}
              </div>
            </div>
            <div>
              <h4 className="text-xs font-black text-slate-400 uppercase tracking-widest mb-3">{t.billTo}</h4>
              <div className="text-sm space-y-1 font-medium">
                <p className="font-bold text-lg leading-tight">{selectedItems[0]?.clientName || 'Client'}</p>
                <p>Cliënt Dossier: {selectedItems[0]?.id || 'N/A'}</p>
                <p>Facturatieadres conform zorgplan</p>
              </div>
            </div>
          </div>

          {/* Metadata Grid */}
          <div className="bg-slate-50 p-6 rounded-xl grid grid-cols-3 gap-8 mb-12">
            <div>
              <p className="text-[10px] font-black text-slate-400 uppercase mb-1">{t.date}</p>
              <p className="text-sm font-bold">{today}</p>
            </div>
            <div>
              <p className="text-[10px] font-black text-slate-400 uppercase mb-1">{t.dueDate}</p>
              <p className="text-sm font-bold">{dueDate}</p>
            </div>
            <div>
              <p className="text-[10px] font-black text-slate-400 uppercase mb-1">{t.bankAccount}</p>
              <p className="text-sm font-bold uppercase">{companyProfile.iban}</p>
            </div>
          </div>

          {/* Items Table */}
          <div className="flex-grow">
            <table className="w-full text-left mb-8">
              <thead>
                <tr className="border-b border-slate-200">
                  <th className="py-4 text-[11px] font-black text-slate-400 uppercase tracking-widest">{t.date}</th>
                  <th className="py-4 text-[11px] font-black text-slate-400 uppercase tracking-widest">{t.activity}</th>
                  <th className="py-4 text-[11px] font-black text-slate-400 uppercase tracking-widest">{t.nzaCode}</th>
                  <th className="py-4 text-[11px] font-black text-slate-400 uppercase tracking-widest text-right">{t.amount}</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {selectedItems.map((item) => (
                  <tr key={item.id}>
                    <td className="py-4 text-sm font-medium">{item.date}</td>
                    <td className="py-4">
                      <p className="text-sm font-bold">{item.type}</p>
                      <p className="text-xs text-slate-400">{item.duration}</p>
                    </td>
                    <td className="py-4 text-sm font-mono text-slate-500">{item.nzaCode}</td>
                    <td className="py-4 text-sm font-bold text-right">€ {hourlyRate.toFixed(2).replace('.', ',')}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Totals Section */}
          <div className="border-t-2 border-slate-100 pt-8 mt-auto">
            <div className="flex justify-end mb-8">
              <div className="w-full max-w-[250px] space-y-4">
                <div className="flex justify-between text-sm text-slate-500">
                  <span>{t.subtotal}</span>
                  <span className="font-bold">€ {formattedAmount}</span>
                </div>
                <div className="flex justify-between text-sm text-slate-500">
                  <span>{t.vat} (0% Vrijgesteld)</span>
                  <span className="font-bold">€ 0,00</span>
                </div>
                <div className="flex justify-between text-xl border-t border-slate-100 pt-4">
                  <span className="font-black text-primary uppercase text-sm self-center tracking-widest">{t.total}</span>
                  <span className="font-black text-3xl tracking-tighter text-slate-900">€ {formattedAmount}</span>
                </div>
              </div>
            </div>

            {/* Footer Information */}
            <div className="text-center border-t border-slate-100 pt-8 text-[10px] text-slate-400 space-y-1 font-medium">
              <p className="uppercase font-black tracking-widest text-slate-300 mb-2">Betaalinformatie</p>
              <p className="text-slate-500 max-w-lg mx-auto leading-relaxed">{companyProfile.invoiceFooter}</p>
              <p className="mt-4">{companyProfile.name} • KvK {companyProfile.kvk} • BTW {companyProfile.btw}</p>
              <p>© {new Date().getFullYear()} - Professional Health Administration</p>
            </div>
          </div>
        </div>
      </main>

      <style>{`
        @media print {
          body {
            background: white !important;
            padding: 0 !important;
            margin: 0 !important;
          }
          .dark body {
            background: white !important;
            color: black !important;
          }
          nav, header, button, .print-hidden {
            display: none !important;
          }
          main {
            padding: 0 !important;
            margin: 0 !important;
            width: 100% !important;
            max-width: none !important;
          }
          .shadow-2xl {
            box-shadow: none !important;
          }
        }
      `}</style>
    </div>
  );
};

export default InvoicePreview;
