import React, { useState, useEffect } from 'react';
import { X, Plus, Trash2, Send, CheckCircle, Clock, Edit2, ArrowUp, ArrowDown } from 'lucide-react';
import { HRDocument, SignatureStep, ReferenceDatabase } from '../types';

interface SignatureModalProps {
  documentData: HRDocument;
  onClose: () => void;
  onSaveWorkflow: (docId: string, x: number, y: number, flow: SignatureStep[]) => void;
  databases?: ReferenceDatabase[];
}

export default function SignatureModal({
  documentData,
  onClose,
  onSaveWorkflow,
  databases = []
}: SignatureModalProps) {
  const [signatureX, setSignatureX] = useState<number>(documentData.signatureX ?? 70);
  const [signatureY, setSignatureY] = useState<number>(documentData.signatureY ?? 85);
  const [flowSteps, setFlowSteps] = useState<SignatureStep[]>(documentData.signatureFlow || []);
  const [positionChanged, setPositionChanged] = useState(false);

  const isLetterheadMode = documentData.isLetterheadMode || false;
  const letterheadHeight = documentData.letterheadHeight ?? 5.0;
  const isIkiLetterhead = documentData.isIkiLetterhead || false;
  const marginTop = documentData.marginTop ?? 2.5;
  const marginBottom = documentData.marginBottom ?? 2.5;
  const marginLeft = documentData.marginLeft ?? 2.5;
  const marginRight = documentData.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 [selectedSignerIndex, setSelectedSignerIndex] = useState<string>('');
  const [editingStepId, setEditingStepId] = useState<string | null>(null);

  const handleEditClick = (step: SignatureStep) => {
    setEditingStepId(step.id);
    const optIndex = signerOptions.findIndex(
      opt => opt.name === step.name && opt.role === step.role
    );
    if (optIndex !== -1) {
      setSelectedSignerIndex(String(optIndex));
    } else {
      setSelectedSignerIndex('');
    }
  };

  const handleSaveStep = () => {
    if (selectedSignerIndex === '') {
      alert('Silakan pilih orang terlebih dahulu.');
      return;
    }
    const selected = signerOptions[Number(selectedSignerIndex)];
    if (!selected.name.trim() || !selected.role.trim()) {
      alert('Data nama atau jabatan tidak lengkap.');
      return;
    }
    if (!selected.phone.trim()) {
      alert('Nomor WhatsApp orang ini belum diatur di Pengaturan / Database.');
      return;
    }
    let cleanedPhone = selected.phone.replace(/\D/g, '');
    if (cleanedPhone.startsWith('0')) {
      cleanedPhone = '62' + cleanedPhone.slice(1);
    }

    setFlowSteps(flowSteps.map(step => {
      if (step.id === editingStepId) {
        return {
          ...step,
          role: selected.role.trim(),
          name: selected.name.trim(),
          phone: cleanedPhone
        };
      }
      return step;
    }));

    setEditingStepId(null);
    setSelectedSignerIndex('');
  };

  const handleCancelEdit = () => {
    setEditingStepId(null);
    setSelectedSignerIndex('');
  };

  const handleMoveUp = (index: number) => {
    if (index === 0) return;
    const newSteps = [...flowSteps];
    const temp = newSteps[index];
    newSteps[index] = newSteps[index - 1];
    newSteps[index - 1] = temp;
    setFlowSteps(newSteps);
  };

  const handleMoveDown = (index: number) => {
    if (index === flowSteps.length - 1) return;
    const newSteps = [...flowSteps];
    const temp = newSteps[index];
    newSteps[index] = newSteps[index + 1];
    newSteps[index + 1] = temp;
    setFlowSteps(newSteps);
  };

  interface SignerOption {
    id: string;
    name: string;
    role: string;
    phone: string;
    source: string;
  }

  const signerOptions: SignerOption[] = [];

  // Helper: cari nilai nomor telepon/WA dari baris, cek semua kemungkinan nama kolom
  const resolvePhone = (row: Record<string, string>): string => {
    const candidates = [
      'No WhatsApp', 'No. WhatsApp', 'Nomor WhatsApp',
      'No Telepon', 'No. Telepon', 'Nomor Telepon',
      'No Telepon Karyawan', 'Nomor Telepon Karyawan',
      'No HP', 'No. HP', 'Nomor HP',
      'Phone', 'Telepon', 'WhatsApp', 'HP'
    ];
    for (const key of candidates) {
      if (row[key] && String(row[key]).trim()) return String(row[key]).trim();
    }
    return '';
  };

  const pejabatDb = databases?.find(db => db.id === 'db-pejabat');
  if (pejabatDb) {
    pejabatDb.rows.forEach(row => {
      const name = row['Nama Penandatangan'] || '';
      const role = row['Jabatan Penandatangan'] || '';
      const phone = resolvePhone(row);
      if (name) {
        signerOptions.push({
          id: row.id || `pejabat-${name}`,
          name,
          role,
          phone,
          source: 'Pejabat Penandatangan'
        });
      }
    });
  }

  const karyawanDb = databases?.find(db => db.id === 'db-karyawan');
  if (karyawanDb) {
    karyawanDb.rows.forEach(row => {
      const name = row['Nama Karyawan'] || '';
      const role = row['Jabatan Karyawan'] || '';
      const phone = resolvePhone(row);
      if (name) {
        signerOptions.push({
          id: row.id || `karyawan-${name}`,
          name,
          role,
          phone,
          source: 'Karyawan Aktif'
        });
      }
    });
  }

  // Auto-synchronize steps types: intermediate steps are 'paraf', the last step is 'ttd'
  useEffect(() => {
    if (flowSteps.length > 0) {
      const updated = flowSteps.map((step, idx) => ({
        ...step,
        type: (idx === flowSteps.length - 1) ? 'ttd' as const : 'paraf' as const
      }));
      if (JSON.stringify(updated) !== JSON.stringify(flowSteps)) {
        setFlowSteps(updated);
      }
    }
  }, [flowSteps]);

  const handlePaperClick = (e: React.MouseEvent<HTMLDivElement>) => {
    // Paper is 210mm × 297mm — click coords in mm relative to top-left corner
    const rect = e.currentTarget.getBoundingClientRect();
    // Convert click px to % of paper (which is always 210mm × 297mm)
    const x = ((e.clientX - rect.left) / rect.width) * 100;
    const y = ((e.clientY - rect.top) / rect.height) * 100;
    const newX = Math.round(x * 10) / 10;
    const newY = Math.round(y * 10) / 10;
    setSignatureX(newX);
    setSignatureY(newY);
    setPositionChanged(true);
  };

  const handleAddStep = () => {
    if (selectedSignerIndex === '') {
      alert('Silakan pilih orang terlebih dahulu.');
      return;
    }
    const selected = signerOptions[Number(selectedSignerIndex)];
    if (!selected.name.trim() || !selected.role.trim()) {
      alert('Data nama atau jabatan tidak lengkap.');
      return;
    }
    if (!selected.phone.trim()) {
      alert('Nomor WhatsApp orang ini belum diatur di Pengaturan / Database.');
      return;
    }
    // Clean phone number to WhatsApp format (numbers only)
    let cleanedPhone = selected.phone.replace(/\D/g, '');
    if (cleanedPhone.startsWith('0')) {
      cleanedPhone = '62' + cleanedPhone.slice(1);
    }

    const newStep: SignatureStep = {
      id: `step-${Date.now()}-${Math.random()}`,
      role: selected.role.trim(),
      name: selected.name.trim(),
      phone: cleanedPhone,
      status: 'pending',
      type: 'paraf'
    };

    setFlowSteps([...flowSteps, newStep]);
    setSelectedSignerIndex('');
  };

  const handleDeleteStep = (id: string) => {
    setFlowSteps(flowSteps.filter(s => s.id !== id));
  };

  const handleSave = () => {
    if (flowSteps.length === 0) {
      alert('Mohon tambahkan minimal satu step persetujuan.');
      return;
    }
    onSaveWorkflow(documentData.id, signatureX, signatureY, flowSteps);
    setPositionChanged(false);
  };

  const handleSavePositionOnly = () => {
    // Save only the position without requiring workflow steps
    onSaveWorkflow(documentData.id, signatureX, signatureY, flowSteps);
    setPositionChanged(false);
  };

  const getWhatsAppLink = (step: SignatureStep, index: number) => {
    const approvalLink = `${window.location.origin}/?approve=${documentData.id}&step=${index}`;
    const textMessage = `Halo ${step.name}, mohon periksa dan ${step.type === 'paraf' ? 'paraf' : 'tanda tangani'} dokumen "${documentData.title}".\n\nSilakan klik tautan berikut untuk memproses:\n${approvalLink}`;
    return `https://wa.me/${step.phone}?text=${encodeURIComponent(textMessage)}`;
  };

  const activeStepIndex = documentData.currentStepIndex ?? 0;
  const isWorkflowFinished = documentData.isSigned;

  return (
    <div className="fixed inset-0 bg-slate-950/70 backdrop-blur-xs flex items-center justify-center p-4 z-[999] animate-in fade-in duration-300">
      <div className="bg-white rounded-3xl border border-slate-150 shadow-2xl max-w-6xl w-full h-[90vh] flex flex-col overflow-hidden animate-in zoom-in-95 duration-250">
        
        {/* Header */}
        <div className="px-6 py-4 bg-slate-50 border-b border-slate-200 flex items-center justify-between">
          <div>
            <h2 className="text-lg font-black text-slate-800 tracking-tight">
              Alur Tanda Tangan & Paraf: {documentData.title}
            </h2>
            <p className="text-xs text-slate-500 font-semibold mt-0.5">
              Tentukan posisi QR Code TTD pada kertas dan buat alur persetujuan bertingkat.
            </p>
          </div>
          <button 
            type="button" 
            onClick={onClose} 
            className="p-2 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded-full transition-colors cursor-pointer"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 flex flex-col md:flex-row overflow-hidden">
          
          {/* Left Pane: A4 Preview & Coordinate Selector */}
          <div className="flex-1 bg-slate-100 p-5 flex flex-col items-center justify-start overflow-y-auto border-r border-slate-200 gap-3">
            <div className="text-[10px] text-slate-400 font-extrabold uppercase text-center select-none tracking-wider">
              Klik area kertas untuk memindahkan posisi QR Code TTD
            </div>

            {/* Paper Preview — same physical size as editor, centered, with horizontal scroll if needed */}
            <div className="w-full overflow-x-auto flex justify-center">
              <div
                onClick={handlePaperClick}
                className="bg-white cursor-crosshair select-none shadow-md border border-slate-200 rounded flex-shrink-0"
                style={{
                  // Exact physical size — identical coordinate system to the editor
                  width: documentData.paperSize === 'F4' ? '215mm' : '210mm',
                  minHeight: documentData.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 */}
                {documentData.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="/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: documentData.fontFamily || 'Times New Roman',
                    fontSize: documentData.fontSize || '11pt',
                    lineHeight: documentData.lineHeight || '1.5',
                  }}
                  dangerouslySetInnerHTML={{ __html: documentData.content }}
                />

                {/* Digital Footer */}
                {documentData.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="/kop-bawah.jpg" alt="Kop Bawah" className="w-full h-auto object-contain" />
                  </div>
                )}

                {/* QR Position Indicator — in mm, same as editor */}
                {(() => {
                  const paperW = documentData.paperSize === 'F4' ? 215 : 210;
                  const paperH = documentData.paperSize === 'F4' ? 330 : 297;
                  const xMm = (signatureX / 100) * paperW;
                  const yMm = (signatureY / 100) * paperH;
                  return (
                    <div
                      className={`absolute border-2 border-dashed rounded flex flex-col items-center justify-center pointer-events-none z-30 ${
                        positionChanged ? 'border-emerald-500 bg-emerald-50/90 text-emerald-700 animate-pulse' : 'border-blue-500 bg-blue-50/85 text-blue-700 animate-pulse'
                      }`}
                      style={{
                        left: `${xMm}mm`,
                        top: `${yMm}mm`,
                        transform: 'translate(-50%, -50%)',
                        width: '21mm',
                        height: '24mm',
                        padding: '1mm',
                      }}
                    >
                      <span style={{ fontSize: '2mm', fontWeight: 900, textAlign: 'center', lineHeight: 1 }}>POSISI QR TTD</span>
                      <span style={{ fontSize: '1.6mm', marginTop: '0.5mm' }}>X: {xMm.toFixed(1)}mm</span>
                      <span style={{ fontSize: '1.6mm', fontWeight: 700 }}>Y: {yMm.toFixed(1)}mm</span>
                    </div>
                  );
                })()}
              </div>
            </div>

            {/* Save Position Button — appears when position is changed */}
            <div className={`w-full max-w-[210mm] transition-all duration-300 ${
              positionChanged ? 'opacity-100 translate-y-0' : 'opacity-0 pointer-events-none translate-y-2'
            }`}>
              <div className="bg-emerald-50 border border-emerald-200 rounded-xl p-3 flex items-center justify-between gap-3">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse flex-shrink-0" />
                  <span className="text-[11px] font-bold text-emerald-700">
                    Posisi QR diubah
                  </span>
                </div>
                <button
                  type="button"
                  onClick={handleSavePositionOnly}
                  className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-white text-[11px] font-extrabold rounded-lg transition-all cursor-pointer shadow-sm flex items-center gap-1"
                >
                  <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" /></svg>
                  Simpan Posisi
                </button>
              </div>
            </div>
          </div>

          {/* Right Pane: Settings & Steps Builder */}
          <div className="w-full md:w-[420px] p-6 flex flex-col justify-between overflow-y-auto bg-white">
            <div className="space-y-6">
              
              {/* Info Alur */}
              <div>
                <h3 className="text-xs font-extrabold text-slate-400 uppercase tracking-wider mb-2">
                  1. Rancang Alur Persetujuan
                </h3>
                <p className="text-[11px] text-slate-500 leading-relaxed font-semibold">
                  Alur diproses dari atas ke bawah. Langkah terakhir otomatis bertipe <strong>Tanda Tangan QR Code</strong>, sedangkan langkah sebelumnya bertipe <strong>Paraf Keterangan</strong>.
                </p>
              </div>

              {/* Form Input Step */}
              <div className="bg-slate-50 border border-slate-200 rounded-2xl p-4 space-y-3.5">
                <div>
                  <label className="text-[10px] text-slate-500 font-extrabold uppercase block mb-1">
                    Pilih Orang / Pemaraf
                  </label>
                  <select
                    value={selectedSignerIndex}
                    onChange={e => setSelectedSignerIndex(e.target.value)}
                    className="w-full border border-slate-200 rounded-lg px-2.5 py-1.5 text-xs bg-white focus:outline-none focus:border-blue-500 font-semibold cursor-pointer"
                  >
                    <option value="">-- Pilih Orang --</option>
                    {signerOptions.map((opt, idx) => (
                      <option key={opt.id || idx} value={idx}>
                        {opt.name} ({opt.role})
                      </option>
                    ))}
                  </select>
                </div>

                {selectedSignerIndex !== '' && (
                  <div className="text-[10px] text-slate-600 bg-white border border-slate-150 rounded-xl p-3 space-y-1 select-text">
                    <div>
                      <span className="font-bold text-slate-400">NAMA:</span>{' '}
                      <span className="font-bold text-slate-800">{signerOptions[Number(selectedSignerIndex)].name}</span>
                    </div>
                    <div>
                      <span className="font-bold text-slate-400">JABATAN/ROLE:</span>{' '}
                      <span className="font-bold text-slate-700">{signerOptions[Number(selectedSignerIndex)].role}</span>
                    </div>
                    <div>
                      <span className="font-bold text-slate-400">NO. WHATSAPP:</span>{' '}
                      <span className="font-bold text-slate-700">
                        {signerOptions[Number(selectedSignerIndex)].phone ? (
                          signerOptions[Number(selectedSignerIndex)].phone
                        ) : (
                          <em className="text-red-500 font-normal">Belum diatur di Pengaturan</em>
                        )}
                      </span>
                    </div>
                  </div>
                )}

                {editingStepId ? (
                  <div className="flex gap-2">
                    <button
                      type="button"
                      onClick={handleSaveStep}
                      className="flex-1 py-2 bg-blue-650 hover:bg-blue-600 text-white text-xs font-bold rounded-lg transition-all cursor-pointer flex items-center justify-center space-x-1.5"
                    >
                      <span>Simpan Edit</span>
                    </button>
                    <button
                      type="button"
                      onClick={handleCancelEdit}
                      className="py-2 px-3 bg-slate-200 hover:bg-slate-300 text-slate-700 text-xs font-bold rounded-lg transition-all cursor-pointer"
                    >
                      Batal
                    </button>
                  </div>
                ) : (
                  <button
                    type="button"
                    onClick={handleAddStep}
                    className="w-full py-2 bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold rounded-lg transition-all cursor-pointer flex items-center justify-center space-x-1.5"
                  >
                    <Plus className="w-3.5 h-3.5" />
                    <span>Tambahkan Langkah</span>
                  </button>
                )}
              </div>

              {/* Steps List */}
              <div className="space-y-2.5">
                <h3 className="text-xs font-extrabold text-slate-400 uppercase tracking-wider">
                  2. Urutan Alur & Status
                </h3>
                
                {flowSteps.length === 0 ? (
                  <div className="text-center py-6 text-slate-400 border border-dashed border-slate-200 rounded-2xl text-xs font-semibold">
                    Belum ada alur persetujuan.
                  </div>
                ) : (
                  <div className="space-y-2 max-h-[220px] overflow-y-auto pr-1">
                    {flowSteps.map((step, idx) => {
                      const isActive = idx === activeStepIndex && !isWorkflowFinished;
                      const isApproved = step.status === 'approved';
                      
                      return (
                        <div 
                          key={step.id} 
                          className={`border rounded-2xl p-3 flex flex-col gap-2.5 transition-all ${
                            isApproved 
                              ? 'bg-emerald-50/50 border-emerald-100' 
                              : isActive 
                              ? 'bg-blue-50/30 border-blue-200 shadow-xs' 
                              : 'bg-white border-slate-200'
                          }`}
                        >
                          <div className="flex items-center justify-between min-w-0">
                            <div className="flex items-center space-x-2.5 min-w-0">
                              <span className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-black shrink-0 ${
                                isApproved 
                                  ? 'bg-emerald-600 text-white' 
                                  : isActive 
                                  ? 'bg-blue-650 text-white animate-pulse' 
                                  : 'bg-slate-200 text-slate-600'
                              }`}>
                                {idx + 1}
                              </span>
                              <div className="min-w-0">
                                <p className="text-[11px] font-black text-slate-800 truncate">
                                  {step.name}
                                </p>
                                <p className="text-[9.5px] text-slate-500 font-semibold truncate">
                                  {step.role} • {step.type === 'paraf' ? 'Paraf' : 'Tanda Tangan QR'}
                                </p>
                              </div>
                            </div>

                            <div className="flex items-center space-x-1 shrink-0">
                              {isApproved ? (
                                <CheckCircle className="w-4 h-4 text-emerald-600 font-bold" title="Disetujui" />
                              ) : (
                                <a 
                                  href={getWhatsAppLink(step, idx)}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className={`px-2.5 py-1.5 text-[10px] font-black rounded-lg transition-all flex items-center space-x-1 shadow-sm cursor-pointer ${
                                    isActive 
                                      ? 'bg-emerald-600 hover:bg-emerald-555 text-white' 
                                      : 'border border-slate-200 text-slate-655 hover:bg-slate-50'
                                  }`}
                                  title={isActive ? "Kirim link persetujuan utama via WhatsApp" : "Kirim link/nudge via WhatsApp"}
                                >
                                  <Send className="w-3 h-3" />
                                  <span>Kirim WA</span>
                                </a>
                              )}
                            </div>
                          </div>

                          {/* Reordering, Editing, and Deletion Buttons for Non-Approved Steps */}
                          {!isApproved && !isWorkflowFinished && (
                            <div className="flex items-center justify-between border-t border-slate-100 pt-2 text-[10px]">
                              <div className="flex items-center space-x-1.5">
                                <button 
                                  type="button"
                                  disabled={idx === 0 || flowSteps[idx - 1].status === 'approved'}
                                  onClick={() => handleMoveUp(idx)}
                                  className="p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded disabled:opacity-30 disabled:pointer-events-none transition-colors cursor-pointer"
                                  title="Pindahkan Ke Atas"
                                >
                                  <ArrowUp className="w-3.5 h-3.5" />
                                </button>
                                <button 
                                  type="button"
                                  disabled={idx === flowSteps.length - 1 || flowSteps[idx + 1].status === 'approved'}
                                  onClick={() => handleMoveDown(idx)}
                                  className="p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded disabled:opacity-30 disabled:pointer-events-none transition-colors cursor-pointer"
                                  title="Pindahkan Ke Bawah"
                                >
                                  <ArrowDown className="w-3.5 h-3.5" />
                                </button>
                              </div>

                              <div className="flex items-center space-x-2">
                                <button 
                                  type="button"
                                  onClick={() => handleEditClick(step)}
                                  className={`px-2 py-1 rounded text-[9.5px] font-bold transition-all cursor-pointer flex items-center space-x-1 ${
                                    editingStepId === step.id 
                                      ? 'text-blue-600 bg-blue-50 font-black' 
                                      : 'text-slate-500 hover:text-blue-600 hover:bg-blue-50'
                                  }`}
                                >
                                  <Edit2 className="w-3 h-3" />
                                  <span>Edit</span>
                                </button>
                                <button 
                                  type="button"
                                  onClick={() => handleDeleteStep(step.id)}
                                  className="px-2 py-1 text-slate-500 hover:text-red-650 hover:bg-red-50 rounded text-[9.5px] font-bold transition-all cursor-pointer flex items-center space-x-1"
                                >
                                  <Trash2 className="w-3 h-3" />
                                  <span>Hapus</span>
                                </button>
                              </div>
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>

            {/* Footer Actions */}
            <div className="border-t border-slate-200 pt-4 mt-6 flex items-center justify-between gap-3">
              <button
                type="button"
                onClick={onClose}
                className="flex-1 py-2.5 border border-slate-200 text-slate-600 text-xs font-bold rounded-xl hover:bg-slate-50 transition-all cursor-pointer"
              >
                Kembali
              </button>
              
              {!isWorkflowFinished ? (
                <button
                  type="button"
                  onClick={handleSave}
                  className="flex-1 py-2.5 bg-blue-650 hover:bg-blue-600 text-white text-xs font-black rounded-xl transition-all cursor-pointer shadow-md shadow-blue-100"
                >
                  {documentData.signatureFlow && documentData.signatureFlow.length > 0 ? 'Simpan Perubahan Alur' : 'Simpan & Mulai Alur'}
                </button>
              ) : (
                <div className="flex-1 text-center py-2 px-1 text-[10px] font-bold text-slate-500 bg-slate-50 rounded-xl border border-slate-200">
                  ✓ Alur Persetujuan Selesai
                </div>
              )}
            </div>
            
          </div>
        </div>

      </div>
    </div>
  );
}
