import { ProfilPerusahaan, DokumenSignatoriesConfig } from '../../types/accounting';
import { StorageService } from '../../services/storage';
import { ShieldCheck, QrCode } from 'lucide-react';

interface PrintHeaderProps {
  profile: ProfilPerusahaan;
  title: string;
  subtitle?: string;
  periode?: string;
}

export const PrintHeader: React.FC<PrintHeaderProps> = ({
  profile,
  title,
  subtitle,
  periode,
}) => {
  const currentDate = new Date().toLocaleDateString('id-ID', {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
  });

  return (
    <div className="mb-6 border-b-2 border-slate-900 pb-4 print:block">
      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-4">
          {profile.logoUrl && (
            <img
              src={profile.logoUrl}
              alt="Logo Perusahaan"
              className="h-16 w-16 rounded object-cover border border-slate-300"
            />
          )}
          <div>
            <h1 className="text-2xl font-bold tracking-tight text-slate-900 uppercase">
              {profile.namaPerusahaan}
            </h1>
            <p className="text-xs text-slate-600">
              {profile.alamat}, {profile.kota}, {profile.provinsi} {profile.kodePos}
            </p>
            <p className="text-xs text-slate-500">
              Telp: {profile.telepon} | Email: {profile.email} | NPWP: {profile.npwp}
              {profile.website && ` | Web: ${profile.website}`}
            </p>
          </div>
        </div>
        <div className="text-right">
          <span className="inline-block rounded bg-blue-100 px-3 py-1 text-xs font-semibold text-blue-900 uppercase tracking-wider">
            Dokumen Resmi
          </span>
          <p className="mt-1 text-xs text-slate-500">Tanggal Cetak: {currentDate}</p>
        </div>
      </div>

      <div className="mt-4 text-center">
        <h2 className="text-lg font-bold uppercase tracking-wider text-slate-900 underline">
          {title}
        </h2>
        {subtitle && <p className="text-xs font-medium text-slate-700">{subtitle}</p>}
        {periode && (
          <p className="text-xs font-semibold text-blue-800">
            Periode: {periode} (Mata Uang: {profile.mataUang})
          </p>
        )}
      </div>
    </div>
  );
};

import React, { useState, useEffect } from 'react';
import QRCode from 'qrcode';
import { buildSignatoryCertificatePayload } from '../../services/qrCertificate';

// Reusable Authentic ISO/IEC 18004 Scannable QR Code Renderer
export const SvgQrCode: React.FC<{
  data: string;
  size?: number;
  label?: string;
  className?: string;
}> = ({ data, size = 80, label, className = '' }) => {
  const [dataUrl, setDataUrl] = useState<string>('');

  useEffect(() => {
    let isSubscribed = true;
    if (!data) {
      setDataUrl('');
      return;
    }

    QRCode.toDataURL(data, {
      margin: 2,
      width: Math.max(size * 3, 260),
      errorCorrectionLevel: 'L',
      color: {
        dark: '#000000',
        light: '#ffffff',
      },
    })
      .then((url) => {
        if (isSubscribed) {
          setDataUrl(url);
        }
      })
      .catch((err) => {
        console.error('Failed to generate valid QR code:', err);
      });

    return () => {
      isSubscribed = false;
    };
  }, [data, size]);

  return (
    <div
      className={`inline-flex flex-col items-center justify-center p-1 bg-white border border-slate-300 rounded shadow-xs print:border-none print:shadow-none ${className}`}
    >
      {dataUrl ? (
        <img
          src={dataUrl}
          alt="QR Code E-Sign"
          style={{ width: size, height: size, imageRendering: 'pixelated' }}
          className="block object-contain"
        />
      ) : (
        <div
          style={{ width: size, height: size }}
          className="flex items-center justify-center bg-slate-50 text-[9px] text-slate-400 font-mono"
        >
          ...
        </div>
      )}
      {label && (
        <span className="text-[8px] font-mono text-slate-500 mt-0.5 tracking-tighter print:text-black">
          {label}
        </span>
      )}
    </div>
  );
};

export const PrintSignature: React.FC<{
  profile: ProfilPerusahaan;
  config?: DokumenSignatoriesConfig;
}> = ({ profile, config }) => {
  const activeConfig = config || StorageService.getSignatoriesConfig();
  const today = new Date().toLocaleDateString('id-ID', {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
  });

  const kota = activeConfig.kotaPenetapan || profile.kota || 'Semarang';
  const signatories = activeConfig.signatories || [];

  return (
    <div className="mt-8 pt-5 border-t border-slate-300 print:mt-6">
      <div className="flex justify-between items-center mb-3">
        <div className="text-left text-[11px] text-slate-500">
          Penetapan Dokumen: <span className="font-semibold text-slate-700">{kota}, {today}</span>
        </div>
        {activeConfig.enableQrVerification && (
          <div className="flex items-center gap-1.5 text-[10px] text-blue-700 font-semibold bg-blue-50 border border-blue-200 px-2 py-0.5 rounded-full print:border-slate-400 print:bg-white print:text-slate-900">
            <ShieldCheck className="h-3 w-3 text-blue-600 print:text-slate-800" />
            <span>Dokumen Disahkan dengan Tanda Tangan Digital &amp; QR Code Terverifikasi</span>
          </div>
        )}
      </div>

      <div
        className="grid gap-4 text-center text-xs text-slate-800"
        style={{
          gridTemplateColumns: `repeat(${Math.max(1, signatories.length)}, minmax(0, 1fr))`,
        }}
      >
        {signatories.map((sig, idx) => {
          const isLast = idx === signatories.length - 1;
          const qrPayload = buildSignatoryCertificatePayload(sig, profile, kota);

          return (
            <div key={sig.id} className="flex flex-col justify-between items-center px-2 py-1">
              <div>
                <p className="font-semibold text-slate-700">{sig.peranLabel}:</p>
                <p className="text-[11px] text-slate-500 mb-2">{sig.jabatan}</p>
              </div>

              {/* Digital QR Code or Blank Space */}
              <div className="my-2 flex flex-col items-center justify-center min-h-[85px]">
                {sig.enableQrCode ? (
                  <div className="flex flex-col items-center">
                    <SvgQrCode data={qrPayload} size={85} />
                    <span className="text-[9px] font-mono font-bold text-emerald-700 mt-1 flex items-center gap-1 print:text-slate-900">
                      <ShieldCheck className="h-2.5 w-2.5" />
                      TERVERIFIKASI
                    </span>
                  </div>
                ) : (
                  <div className="h-16" />
                )}
              </div>

              <div>
                <p className="font-bold underline text-slate-900 leading-tight">{sig.nama}</p>
                {sig.nipNik && <p className="text-[10px] font-mono text-slate-500 mt-0.5">NIP/NIK: {sig.nipNik}</p>}
                <p className="text-[10px] text-slate-400">{isLast ? 'Pimpinan / Direksi' : 'Pejabat Penandatangan'}</p>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};
