import React, { useEffect, useState } from 'react';
import { CheckCircle, AlertTriangle, ArrowLeft, Send } from 'lucide-react';
import { HRDocument, SignatureStep } from '../types';

interface ApprovalVerificationViewsProps {
  approvalDocId: string | null;
  approvalStep: number | null;
  verifyDocId: string | null;
  onBackToHome: () => void;
}

export default function ApprovalVerificationViews({
  approvalDocId,
  approvalStep,
  verifyDocId,
  onBackToHome
}: ApprovalVerificationViewsProps) {
  const [doc, setDoc] = useState<HRDocument | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isSuccess, setIsSuccess] = useState(false);
  const [customKopAtas, setCustomKopAtas] = useState<string>('');
  const [customKopBawah, setCustomKopBawah] = useState<string>('');

  useEffect(() => {
    fetch('/api/settings')
      .then(res => res.json())
      .then(data => {
        if (data.customKopAtas) setCustomKopAtas(data.customKopAtas);
        if (data.customKopBawah) setCustomKopBawah(data.customKopBawah);
      })
      .catch(e => console.error('Failed to load kop settings in approval views:', e));
  }, []);

  const docId = approvalDocId || verifyDocId;
  const isApprovalMode = !!approvalDocId;

  useEffect(() => {
    if (!docId) return;

    setLoading(true);
    fetch(`/api/documents/${docId}`)
      .then((res) => {
        if (!res.ok) throw new Error('Dokumen tidak ditemukan.');
        return res.json();
      })
      .then((data) => {
        setDoc(data);
        setLoading(false);
      })
      .catch((err) => {
        setError(err.message);
        setLoading(false);
      });
  }, [docId]);

  const handleApprove = async () => {
    if (!doc || approvalStep === null) return;

    try {
      setLoading(true);
      const res = await fetch(`/api/documents/${doc.id}/approve`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ stepIndex: approvalStep })
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Gagal menyetujui dokumen.');
      }

      const updatedDoc = await res.json();
      setDoc(updatedDoc);
      setIsSuccess(true);
      setLoading(false);
    } catch (err: any) {
      alert(err.message);
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-slate-50 flex items-center justify-center p-6 select-none">
        <div className="text-center space-y-3">
          <div className="w-10 h-10 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mx-auto"></div>
          <p className="text-xs text-slate-500 font-bold">Memuat dokumen dari database...</p>
        </div>
      </div>
    );
  }

  if (error || !doc) {
    return (
      <div className="min-h-screen bg-slate-50 flex items-center justify-center p-6 select-none">
        <div className="bg-white rounded-3xl border border-slate-200 shadow-xl max-w-md w-full p-8 text-center flex flex-col items-center">
          <div className="w-14 h-14 bg-red-50 text-red-600 border border-red-100 rounded-full flex items-center justify-center mb-4">
            <AlertTriangle className="w-7 h-7" />
          </div>
          <h3 className="text-base font-black text-slate-800 leading-snug">Gagal Memuat Dokumen</h3>
          <p className="text-xs text-slate-500 font-semibold mt-2.5 leading-relaxed">
            {error || 'Dokumen yang Anda cari tidak dapat ditemukan.'}
          </p>
          <button
            onClick={onBackToHome}
            className="mt-6 w-full py-2.5 bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold rounded-xl transition-all cursor-pointer"
          >
            Kembali ke Beranda
          </button>
        </div>
      </div>
    );
  }

  if (isApprovalMode) {
    const step = doc.signatureFlow?.[approvalStep ?? -1];
    const isStepPending = step?.status === 'pending';
    const isStepTurn = doc.currentStepIndex === approvalStep;
    const canApprove = isStepPending && isStepTurn;

    const isLetterheadMode = doc.isLetterheadMode || false;
    const letterheadHeight = doc.letterheadHeight ?? 5.0;
    const isIkiLetterhead = doc.isIkiLetterhead || false;
    const marginTop = doc.marginTop ?? 2.5;
    const marginBottom = doc.marginBottom ?? 2.5;
    const marginLeft = doc.marginLeft ?? 2.5;
    const marginRight = doc.marginRight ?? 2.5;

    const effectiveTopMargin = isLetterheadMode 
      ? (letterheadHeight + marginTop) 
      : isIkiLetterhead 
        ? Math.max(5.2, marginTop) 
        : marginTop;
    const effectiveBottomMargin = isIkiLetterhead 
      ? Math.max(1.5, marginBottom) 
      : marginBottom;

    const paperW = doc.paperSize === 'F4' ? 215 : 210;
    const paperH = doc.paperSize === 'F4' ? 330 : 297;
    const xMm = doc.signatureX !== undefined ? (doc.signatureX / 100) * paperW : 0;
    const yMm = doc.signatureY !== undefined ? (doc.signatureY / 100) * paperH : 0;

    return (
      <div className="min-h-screen bg-slate-100 py-8 px-4 flex flex-col md:flex-row items-stretch justify-center gap-6 max-w-6xl mx-auto">
        {/* Left Side: Document Canvas (Read Only) */}
        <div className="flex-1 bg-slate-50 border border-slate-200 shadow-inner rounded-3xl p-5 overflow-y-auto relative h-[85vh] flex justify-center items-start select-none">
          <div className="w-full overflow-x-auto flex justify-center">
            <div
              className="bg-white shadow-md border border-slate-200 rounded flex-shrink-0"
              style={{
                width: doc.paperSize === 'F4' ? '215mm' : '210mm',
                minHeight: doc.paperSize === 'F4' ? '330mm' : '297mm',
                position: 'relative',
                overflow: 'hidden',
                boxSizing: 'border-box',
                paddingTop: `${effectiveTopMargin}cm`,
                paddingBottom: `${effectiveBottomMargin}cm`,
                paddingLeft: `${marginLeft}cm`,
                paddingRight: `${marginRight}cm`,
              }}
            >
              {/* Digital Kop Header */}
              {isIkiLetterhead && (
                <div className="absolute top-0 left-0 right-0 pointer-events-none select-none" style={{ padding: '8mm 8mm 3mm 8mm', boxSizing: 'border-box' }}>
                  <img src={customKopAtas || "/kop-atas.jpg"} alt="Kop Atas" className="w-full h-auto object-contain" />
                </div>
              )}

              {/* Document Content */}
              <div 
                className="pointer-events-none select-none text-black overflow-hidden"
                style={{
                  fontFamily: doc.fontFamily || 'Times New Roman',
                  fontSize: doc.fontSize || '11pt',
                  lineHeight: doc.lineHeight || '1.5',
                  textAlign: 'justify'
                }}
                dangerouslySetInnerHTML={{ __html: doc.content }}
              />

              {/* Footnotes inside Approval Preview */}
              {doc.signatureFlow && doc.signatureFlow.some(s => s.type === 'paraf' && s.status === 'approved') && (
                <div 
                  className="mt-6 border-t border-slate-200 pt-2 select-none text-[9.5px] italic text-slate-500 font-semibold"
                  style={{ fontFamily: doc.fontFamily || 'sans-serif' }}
                >
                  {doc.signatureFlow
                    .filter(s => s.type === 'paraf' && s.status === 'approved')
                    .map(s => (
                      <div key={s.id} className="leading-relaxed">
                        * Telah diparaf oleh {s.role} ({s.name}) pada {s.signedAt ? new Date(s.signedAt).toLocaleString('id-ID', {
                          day: 'numeric',
                          month: 'short',
                          year: 'numeric',
                          hour: '2-digit',
                          minute: '2-digit'
                        }) : ''}
                      </div>
                    ))
                  }
                </div>
              )}

              {/* Digital Kop Footer */}
              {isIkiLetterhead && (
                <div className="absolute bottom-0 left-0 right-0 pointer-events-none select-none" style={{ padding: '3mm 8mm 8mm 8mm', boxSizing: 'border-box' }}>
                  <img src={customKopBawah || "/kop-bawah.jpg"} alt="Kop Bawah" className="w-full h-auto object-contain" />
                </div>
              )}

              {/* QR Code inside Approval Preview */}
              {doc.isSigned && doc.signatureX !== undefined && doc.signatureY !== undefined && (
                <div 
                  className="absolute select-none z-30 flex flex-col items-center justify-center pointer-events-none"
                  style={{
                    left: `${xMm}mm`,
                    top: `${yMm}mm`,
                    transform: 'translate(-50%, -50%)',
                    width: '21mm',
                    height: '24mm',
                  }}
                >
                  <img 
                    src={`https://api.qrserver.com/v1/create-qr-code/?size=70x70&data=${encodeURIComponent(
                      window.location.origin + '/?verify=' + doc.id
                    )}`}
                    alt="QR Code TTD"
                    style={{ width: '18mm', height: '18mm', border: '1px solid #e2e8f0', background: '#fff', padding: '1px', objectFit: 'contain' }}
                  />
                  <div style={{ fontSize: '1.6mm', color: '#475569', fontWeight: 700, textAlign: 'center', marginTop: '1px', maxWidth: '21mm', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                    Ttd {doc.signatureFlow?.[doc.signatureFlow.length - 1]?.name}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Right Side: Approval Form Panel */}
        <div className="w-full md:w-[360px] bg-white border border-slate-200 shadow-lg rounded-3xl p-6 flex flex-col justify-between h-fit select-none">
          <div className="space-y-6">
            <div>
              <span className="text-blue-600 font-extrabold text-[10px] uppercase tracking-widest bg-blue-50 border border-blue-100 rounded-full px-2.5 py-1">
                Persetujuan Dokumen
              </span>
              <h2 className="text-base font-black text-slate-800 tracking-tight mt-3">
                {doc.title}
              </h2>
              <p className="text-[11px] text-slate-500 font-semibold mt-1 leading-relaxed">
                Anda diminta untuk memverifikasi dokumen ketenagakerjaan di samping dan memberikan paraf atau tanda tangan digital.
              </p>
            </div>

            {isSuccess ? (
              <div className="bg-emerald-50 border border-emerald-100 rounded-2xl p-5 text-center flex flex-col items-center">
                <CheckCircle className="w-10 h-10 text-emerald-600 mb-3 animate-bounce" />
                <h3 className="text-xs font-black text-emerald-800">Berhasil Disetujui!</h3>
                <p className="text-[10px] text-emerald-600 font-semibold mt-1">
                  Persetujuan Anda telah disimpan di database. Silakan beritahu pembuat surat.
                </p>
              </div>
            ) : (
              <div className="border border-slate-150 rounded-2xl p-4 bg-slate-50/50 space-y-3">
                <div className="text-[10px] text-slate-400 font-extrabold uppercase tracking-wider">
                  Detail Pemaraf
                </div>
                {step ? (
                  <div className="space-y-2">
                    <div className="flex justify-between text-xs">
                      <span className="text-slate-400 font-semibold">Nama:</span>
                      <span className="font-bold text-slate-800">{step.name}</span>
                    </div>
                    <div className="flex justify-between text-xs">
                      <span className="text-slate-400 font-semibold">Jabatan:</span>
                      <span className="font-bold text-slate-800">{step.role}</span>
                    </div>
                    <div className="flex justify-between text-xs">
                      <span className="text-slate-400 font-semibold">Tipe Aksi:</span>
                      <span className="font-black text-blue-650 uppercase text-[10px]">
                        {step.type === 'paraf' ? 'Paraf Footnote' : 'Tanda Tangan QR'}
                      </span>
                    </div>
                    
                    <div className="border-t border-slate-150 pt-2.5 mt-2">
                      {canApprove ? (
                        <button
                          onClick={handleApprove}
                          className="w-full py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-black rounded-xl shadow-md shadow-emerald-100 transition-all cursor-pointer"
                        >
                          {step.type === 'paraf' ? 'Berikan Paraf Sekarang' : 'Tanda Tangani & Terbitkan QR'}
                        </button>
                      ) : (
                        <div className="text-center py-2 bg-amber-50 border border-amber-100 rounded-xl text-[10px] font-bold text-amber-700 flex items-center justify-center space-x-1">
                          <AlertTriangle className="w-3.5 h-3.5" />
                          <span>
                            {!isStepPending 
                              ? 'Langkah ini sudah disetujui sebelumnya' 
                              : 'Menunggu persetujuan langkah sebelumnya'}
                          </span>
                        </div>
                      )}
                    </div>
                  </div>
                ) : (
                  <p className="text-xs text-red-500 font-bold">Langkah tidak ditemukan.</p>
                )}
              </div>
            )}
          </div>

          <button
            onClick={onBackToHome}
            className="mt-8 w-full py-2 bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold rounded-xl transition-all cursor-pointer flex items-center justify-center space-x-1.5"
          >
            <ArrowLeft className="w-3.5 h-3.5" />
            <span>Kembali ke Dashboard</span>
          </button>
        </div>
      </div>
    );
  }

  // Verification Mode
  return (
    <div className="min-h-screen bg-slate-100 py-8 px-4 flex flex-col items-center justify-center select-none">
      <div className="bg-white rounded-3xl border border-slate-200 shadow-xl max-w-2xl w-full p-7 md:p-8 space-y-6">
        
        {/* Verification Success Header */}
        <div className="text-center pb-5 border-b border-slate-100">
          <div className="w-14 h-14 bg-emerald-50 border border-emerald-100 text-emerald-600 rounded-full flex items-center justify-center mx-auto mb-4 animate-bounce">
            <CheckCircle className="w-8 h-8" />
          </div>
          <h2 className="text-lg font-black text-slate-800 tracking-tight">
            Dokumen Terverifikasi Sah & Asli
          </h2>
          <p className="text-xs text-emerald-600 font-bold mt-1">
            Sistem Keabsahan Surat Digital PT. Dharma Kreasi Nusantara
          </p>
        </div>

        {/* Info Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-5 text-xs border border-slate-150 rounded-2xl p-4 bg-slate-50/50">
          <div className="space-y-2">
            <div className="flex flex-col">
              <span className="text-[10px] text-slate-400 font-extrabold uppercase">Judul Dokumen</span>
              <span className="font-bold text-slate-800 text-sm mt-0.5">{doc.title}</span>
            </div>
            <div className="flex flex-col">
              <span className="text-[10px] text-slate-400 font-extrabold uppercase">Kategori Surat</span>
              <span className="font-bold text-slate-800 mt-0.5">{doc.category}</span>
            </div>
          </div>
          
          <div className="space-y-2">
            <div className="flex flex-col">
              <span className="text-[10px] text-slate-400 font-extrabold uppercase">Tanggal Diterbitkan</span>
              <span className="font-bold text-slate-800 mt-0.5">
                {new Date(doc.createdAt).toLocaleDateString('id-ID', {
                  day: 'numeric',
                  month: 'long',
                  year: 'numeric'
                })}
              </span>
            </div>
            <div className="flex flex-col">
              <span className="text-[10px] text-slate-400 font-extrabold uppercase">Status</span>
              <span className="font-black text-emerald-650 uppercase text-[10px] mt-0.5">
                Ditandatangani QR Code
              </span>
            </div>
          </div>
        </div>

        {/* Steps Flow Result */}
        <div className="space-y-3">
          <h3 className="text-xs font-extrabold text-slate-400 uppercase tracking-wider">
            Riwayat Alur Persetujuan & Paraf
          </h3>
          <div className="space-y-2">
            {doc.signatureFlow?.map((step, idx) => (
              <div key={step.id} className="bg-white border border-slate-200 rounded-xl p-3 flex items-center justify-between">
                <div className="flex items-center space-x-2.5">
                  <span className="w-5 h-5 rounded-full bg-slate-100 text-slate-650 flex items-center justify-center text-[10px] font-black shrink-0">
                    {idx + 1}
                  </span>
                  <div>
                    <p className="text-xs font-black text-slate-850">{step.name}</p>
                    <p className="text-[10px] text-slate-500 font-semibold">{step.role}</p>
                  </div>
                </div>
                <div className="text-right">
                  <span className="text-[10px] font-black bg-emerald-50 text-emerald-700 px-2 py-1 rounded border border-emerald-100 uppercase tracking-tight">
                    {step.type === 'paraf' ? 'Paraf' : 'Tanda Tangan QR'}
                  </span>
                  <p className="text-[9px] text-slate-400 mt-1 font-semibold">
                    {step.signedAt ? new Date(step.signedAt).toLocaleString('id-ID') : ''}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>

        <button
          onClick={onBackToHome}
          className="w-full py-2.5 bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold rounded-xl transition-all cursor-pointer"
        >
          Masuk ke Aplikasi Pembuat Surat
        </button>
      </div>
    </div>
  );
}
