import React, { useState, useEffect } from 'react';
import { CheckCircle2, AlertTriangle, Trash2, Info } from 'lucide-react';
import { HRTemplate, HRDocument, HREmployee, HRSigner, ReferenceDatabase, SignatureStep } from './types';
import { INITIAL_TEMPLATES } from './constants/initialTemplates';
import Dashboard from './components/Dashboard';
import RichEditor from './components/RichEditor';
import AppModals from './components/AppModals';
import SignatureModal from './components/SignatureModal';
import ApprovalVerificationViews from './components/ApprovalVerificationViews';

export default function App() {
  const [documents, setDocuments] = useState<HRDocument[]>([]);
  const [templates, setTemplates] = useState<HRTemplate[]>([]);
  const [databases, setDatabases] = useState<ReferenceDatabase[]>([]);
  
  // Navigation / Active View Systems: 'dashboard' | 'editor'
  const [activeScreen, setActiveScreen] = useState<'dashboard' | 'editor'>('dashboard');
  const [selectedTemplate, setSelectedTemplate] = useState<HRTemplate | null>(null);
  const [selectedDocument, setSelectedDocument] = useState<HRDocument | null>(null);
  const [isEditingTemplate, setIsEditingTemplate] = useState(false);

  // Modals Overlay state
  const [showCreateTplModal, setShowCreateTplModal] = useState(false);
  const [showSignatureModal, setShowSignatureModal] = useState(false);
  const [sigModalDocument, setSigModalDocument] = useState<HRDocument | null>(null);

  // URL parameters for Approval and Verification Mode
  const [approvalDocId, setApprovalDocId] = useState<string | null>(null);
  const [approvalStep, setApprovalStep] = useState<number | null>(null);
  const [verifyDocId, setVerifyDocId] = useState<string | null>(null);

  // SweetAlert state system
  const [swal, setSwal] = useState<{
    isOpen: boolean;
    type: 'success' | 'warning' | 'danger' | 'info';
    title: string;
    text: string;
    confirmText?: string;
    cancelText?: string;
    showCancel?: boolean;
    onConfirm?: () => void;
  } | null>(null);

  // New template metadata state
  const [newTplTitle, setNewTplTitle] = useState('');
  const [newTplCategory, setNewTplCategory] = useState<'Kontrak' | 'Surat Keputusan' | 'Surat Keterangan' | 'Surat Teguran' | 'Lainnya'>('Surat Keterangan');
  const [newTplDesc, setNewTplDesc] = useState('');

  // Toast notice systems
  const [toastMessage, setToastMessage] = useState<string | null>(null);

  // 1. On Mount: Check URL params and load lists from MySQL API
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const approve = params.get('approve');
    const step = params.get('step');
    const verify = params.get('verify');

    if (approve) {
      setApprovalDocId(approve);
      if (step !== null) setApprovalStep(parseInt(step, 10));
    } else if (verify) {
      setVerifyDocId(verify);
    }

    loadBackendData();
  }, []);

  async function loadBackendData() {
    try {
      const [docsRes, tplsRes, dbsRes] = await Promise.all([
        fetch('/api/documents'),
        fetch('/api/templates'),
        fetch('/api/databases')
      ]);
      const [docs, tpls, dbs] = await Promise.all([
        docsRes.json(),
        tplsRes.json(),
        dbsRes.json()
      ]);
      setDocuments(docs);
      setTemplates(tpls);
      setDatabases(dbs);
    } catch (e) {
      console.error('Error loading data from MySQL API:', e);
    }
  }

  const triggerSwal = (config: {
    type: 'success' | 'warning' | 'danger' | 'info';
    title: string;
    text: string;
    confirmText?: string;
    cancelText?: string;
    showCancel?: boolean;
    onConfirm?: () => void;
  }) => {
    setSwal({ isOpen: true, ...config });
  };

  const triggerToast = (msg: string) => {
    setToastMessage(msg);
    setTimeout(() => setToastMessage(null), 3500);
  };

  // REST API database storage helpers
  const handleSaveDocument = async (doc: HRDocument) => {
    try {
      const res = await fetch('/api/documents', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(doc)
      });
      const saved = await res.json();
      setDocuments(prev => {
        const exists = prev.some(d => d.id === saved.id);
        return exists ? prev.map(d => d.id === saved.id ? saved : d) : [saved, ...prev];
      });
      if (selectedDocument?.id === saved.id) {
        setSelectedDocument(saved);
      }
      return saved;
    } catch (e) {
      console.error('Error saving document:', e);
    }
  };

  const handleSaveTemplate = async (tpl: HRTemplate) => {
    try {
      const res = await fetch('/api/templates', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(tpl)
      });
      const saved = await res.json();
      setTemplates(prev => {
        const exists = prev.some(t => t.id === saved.id);
        return exists ? prev.map(t => t.id === saved.id ? saved : t) : [...prev, saved];
      });
      return saved;
    } catch (e) {
      console.error('Error saving template:', e);
    }
  };

  const handleSaveDatabases = async (newDbs: ReferenceDatabase[]) => {
    try {
      await fetch('/api/databases', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newDbs)
      });
      setDatabases(newDbs);
    } catch (e) {
      console.error('Error saving databases:', e);
    }
  };

  // Derive employees and signers reactively from databases
  const employees = databases.find(db => db.id === 'db-karyawan')?.rows.map(row => {
    const converted: any = { id: row.id };
    Object.keys(row).forEach(key => {
      if (key !== 'id') {
        converted[key] = row[key];
        converted[key.replace(/ /g, '_')] = row[key];
      }
    });
    converted.Nama_Karyawan = row['Nama Karyawan'] || '';
    converted.NIK = row['Nomor Induk Karyawan'] || '';
    converted.Jabatan = row['Jabatan Karyawan'] || '';
    converted.Departemen = row['Departemen'] || '';
    converted.No_Identitas_KTP = row['No Identitas KTP'] || '';
    return converted;
  }) || [];

  const signers = databases.find(db => db.id === 'db-pejabat')?.rows.map(row => {
    const converted: any = { id: row.id };
    Object.keys(row).forEach(key => {
      if (key !== 'id') {
        converted[key] = row[key];
        converted[key.replace(/ /g, '_')] = row[key];
      }
    });
    converted.Nama_Pimpinan = row['Nama Penandatangan'] || '';
    converted.Jabatan_Pimpinan = row['Jabatan Penandatangan'] || '';
    converted.Kota_Tanda_Tangan = row['Kota Tanda Tangan'] || '';
    return converted;
  }) || [];

  // Operations
  const handleUseTemplate = (template: HRTemplate) => {
    setSelectedTemplate(template);
    setIsEditingTemplate(false);
    const newDoc: HRDocument = {
      id: `doc-${Date.now()}`,
      title: `${template.title} Draft`,
      content: template.content,
      category: template.category,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    setSelectedDocument(newDoc);
    setActiveScreen('editor');
  };

  const handleEditDocument = (doc: HRDocument) => {
    setSelectedDocument(doc);
    setIsEditingTemplate(false);
    setActiveScreen('editor');
  };

  const handleCloneDocument = async (doc: HRDocument) => {
    const cloned: HRDocument = {
      ...doc,
      id: `doc-${Date.now()}`,
      title: `${doc.title} (Salinan)`,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      signatureFlow: undefined,
      currentStepIndex: 0,
      isSigned: false
    };
    await handleSaveDocument(cloned);
    triggerSwal({
      type: 'success',
      title: 'Draf Disalin!',
      text: `Surat "${doc.title}" berhasil disalin menjadi "${cloned.title}".`,
      confirmText: 'Selesai'
    });
  };

  const handleCloneTemplate = async (tpl: HRTemplate) => {
    const cloned: HRTemplate = {
      ...tpl,
      id: `tpl-${Date.now()}`,
      title: `${tpl.title} (Salinan)`,
      isCustom: true,
      createdAt: new Date().toISOString()
    };
    await handleSaveTemplate(cloned);
    triggerSwal({
      type: 'success',
      title: 'Templat Disalin!',
      text: `Master templat "${tpl.title}" berhasil disalin menjadi "${cloned.title}".`,
      confirmText: 'Selesai'
    });
  };

  const handleDeleteDocument = (id: string, title: string) => {
    triggerSwal({
      type: 'danger',
      title: 'Hapus Draf Surat?',
      text: `Apakah Anda yakin ingin menghapus draf surat "${title}"? Tindakan ini bersifat permanen dan tidak dapat dibatalkan.`,
      confirmText: 'Ya, Hapus',
      cancelText: 'Batal',
      showCancel: true,
      onConfirm: async () => {
        try {
          await fetch(`/api/documents/${id}`, { method: 'DELETE' });
          setDocuments(prev => prev.filter(d => d.id !== id));
          setSwal(null);
          triggerSwal({
            type: 'success',
            title: 'Draf Terhapus!',
            text: `Draf surat "${title}" berhasil dihapus dari database MySQL.`,
            confirmText: 'Selesai'
          });
        } catch (e) { console.error(e); }
      }
    });
  };

  const handleDeleteTemplate = (id: string, title: string) => {
    triggerSwal({
      type: 'danger',
      title: 'Hapus Master Templat?',
      text: `Apakah Anda yakin ingin menghapus templat master kustom "${title}"? Tindakan ini bersifat permanen dan tidak dapat dibatalkan.`,
      confirmText: 'Ya, Hapus',
      cancelText: 'Batal',
      showCancel: true,
      onConfirm: async () => {
        try {
          await fetch(`/api/templates/${id}`, { method: 'DELETE' });
          setTemplates(prev => prev.filter(t => t.id !== id));
          setSwal(null);
          triggerSwal({
            type: 'success',
            title: 'Templat Terhapus!',
            text: `Master templat "${title}" telah dihapus dengan sukses dari database MySQL.`,
            confirmText: 'Oke'
          });
        } catch (e) { console.error(e); }
      }
    });
  };

  const handleResetDefaultsWithSwal = () => {
    triggerSwal({
      type: 'warning',
      title: 'Pulihkan Setelan Templat?',
      text: 'Semua templat master kustom buatan Anda akan terhapus. Daftar templat akan dikembalikan sepenuhnya ke kondisi awal bawaan pabrik.',
      confirmText: 'Ya, Pulihkan',
      cancelText: 'Batal',
      showCancel: true,
      onConfirm: async () => {
        try {
          for (const t of templates) {
            await fetch(`/api/templates/${t.id}`, { method: 'DELETE' });
          }
          for (const tpl of INITIAL_TEMPLATES) {
            await handleSaveTemplate(tpl);
          }
          setSwal(null);
          triggerSwal({
            type: 'success',
            title: 'Setelan Dipulihkan!',
            text: 'Toko templat master Anda telah berhasil dikembalikan ke sediaan pabrik.',
            confirmText: 'Luar Biasa'
          });
        } catch (e) { console.error(e); }
      }
    });
  };

  const handleBackupImport = async (importedData: { documents: any[]; templates: any[] }) => {
    try {
      if (importedData.documents && Array.isArray(importedData.documents)) {
        for (const doc of importedData.documents) {
          await handleSaveDocument(doc);
        }
      }
      if (importedData.templates && Array.isArray(importedData.templates)) {
        for (const tpl of importedData.templates) {
          await handleSaveTemplate(tpl);
        }
      }
      triggerSwal({
        type: 'success',
        title: 'Backup Berhasil Dipulihkan!',
        text: 'Berkas draf surat dan master templat kustom telah berhasil digabungkan ke database MySQL.',
        confirmText: 'Luar Biasa'
      });
    } catch (e) { console.error(e); }
  };
  
  const handleEditTemplate = (tpl: HRTemplate) => {
    setSelectedTemplate(tpl);
    setIsEditingTemplate(true);
    const tempDoc: HRDocument = {
      id: tpl.id,
      title: tpl.title,
      content: tpl.content,
      category: tpl.category,
      createdAt: tpl.createdAt,
      updatedAt: tpl.createdAt
    };
    setSelectedDocument(tempDoc);
    setActiveScreen('editor');
  };

  const handleCreateNewTemplateProperty = async () => {
    if (!newTplTitle.trim()) {
      triggerSwal({
        type: 'warning',
        title: 'Judul Kosong',
        text: 'Judul templat master wajib diisi terlebih dahulu untuk validasi kearsipan.',
        confirmText: 'Mengerti'
      });
      return;
    }

    const defaultContent = `<div style="font-family: 'Times New Roman', Times, serif; font-size: 12pt; line-height: 1.6; color: #000; padding: 20px;">
      <div style="text-align: center; border-bottom: 2px solid #000; padding-bottom: 8px; margin-bottom: 20px;">
        <h2 style="margin: 0; font-size: 18px; text-transform: uppercase;">PT. NAMA PERUSAHAAN</h2>
        <p style="margin: 4px 0 0 0; font-size: 11px;">Alamat Kantor Lengkap | Telp: (021) 555-1234</p>
      </div>
      <h3 style="text-align: center; text-decoration: underline; text-transform: uppercase;">SURAT PERSETUJUAN</h3>
      <p style="margin-bottom: 15px; text-indent: 40px;">
        Menerangkan bahwasanya karyawan bernama <strong>(Nama Karyawan)</strong> dengan jabatan (Jabatan) berhak menerima...
      </p>
    </div>`;

    const newTpl: HRTemplate = {
      id: `tpl-${Date.now()}`,
      title: newTplTitle.trim(),
      category: newTplCategory,
      description: newTplDesc.trim() || 'Deskripsi templat buatan sendiri.',
      content: defaultContent,
      createdAt: new Date().toISOString(),
      isCustom: true
    };

    await handleSaveTemplate(newTpl);
    setShowCreateTplModal(false);
    setNewTplTitle('');
    setNewTplCategory('Surat Keterangan');
    setNewTplDesc('');

    handleEditTemplate(newTpl);
    triggerToast('✓ Templat baru dibuat! Silakan tulis draf layout Anda.');
  };

  // Route to Approval/Verification view if params set
  if (approvalDocId || verifyDocId) {
    return (
      <ApprovalVerificationViews 
        approvalDocId={approvalDocId}
        approvalStep={approvalStep}
        verifyDocId={verifyDocId}
        onBackToHome={async () => {
          window.history.replaceState({}, '', window.location.pathname);
          setApprovalDocId(null);
          setApprovalStep(null);
          setVerifyDocId(null);
          await loadBackendData();
        }}
      />
    );
  }

  return (
    <div className={`bg-slate-100 flex flex-col text-slate-800 ${activeScreen === 'editor' ? 'h-screen overflow-hidden' : 'min-h-screen'}`}>
      {/* GLOBAL TOAST NOTICE */}
      {toastMessage && (
        <div className="fixed top-6 left-1/2 -translate-x-1/2 bg-slate-950 text-white px-5 py-3 rounded-xl shadow-2xl flex items-center space-x-3 transition-all z-50 select-none animate-in fade-in slide-in-from-top-4 duration-300">
          <CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0" />
          <p className="text-sm font-semibold">{toastMessage}</p>
        </div>
      )}

      {/* CORE ROUTER */}
      {activeScreen === 'dashboard' && (
        <Dashboard 
          documents={documents}
          templates={templates}
          employees={employees}
          signers={signers}
          databases={databases}
          onSaveEmployees={() => {}}
          onSaveSigners={() => {}}
          onSaveDatabases={handleSaveDatabases}
          onUseTemplate={handleUseTemplate}
          onEditDocument={handleEditDocument}
          onCloneDocument={handleCloneDocument}
          onDeleteDocument={handleDeleteDocument}
          onEditTemplate={handleEditTemplate}
          onCreateTemplate={() => setShowCreateTplModal(true)}
          onCloneTemplate={handleCloneTemplate}
          onDeleteTemplate={handleDeleteTemplate}
          onBackupImport={handleBackupImport}
          onResetDefaults={handleResetDefaultsWithSwal}
          onSignatureWorkflow={(doc) => {
            setSigModalDocument(doc);
            setShowSignatureModal(true);
          }}
        />
      )}

      {activeScreen === 'editor' && selectedDocument && (
        <RichEditor 
          documentData={selectedDocument}
          employees={employees}
          signers={signers}
          databases={databases}
          onSave={async (updated) => {
            if (isEditingTemplate) {
              const tpl = templates.find(t => t.id === updated.id);
              if (tpl) {
                await handleSaveTemplate({ ...tpl, title: updated.title, category: updated.category as any, content: updated.content });
              }
              setActiveScreen('dashboard');
              triggerSwal({
                type: 'success',
                title: 'Templat Diperbarui!',
                text: `Master templat "${updated.title}" berhasil disimpan ke sistem utama.`,
                confirmText: 'Kembali Ke Dashboard'
              });
            } else {
              await handleSaveDocument(updated);
              setActiveScreen('dashboard');
              triggerSwal({
                type: 'success',
                title: 'Draf Surat Disimpan!',
                text: `Draf surat ketenagakerjaan "${updated.title}" Anda berhasil disimpan dengan aman.`,
                confirmText: 'Kembali Ke Dashboard'
              });
            }
          }}
          onAutosave={async (updated) => {
            if (isEditingTemplate) {
              const tpl = templates.find(t => t.id === updated.id);
              if (tpl) {
                await handleSaveTemplate({ ...tpl, title: updated.title, category: updated.category as any, content: updated.content });
              }
            } else {
              await handleSaveDocument(updated);
            }
          }}
          onBack={() => {
            setActiveScreen('dashboard');
            setSelectedDocument(null);
            setSelectedTemplate(null);
          }}
        />
      )}

      <AppModals
        showCreateTplModal={showCreateTplModal}
        onCancelCreateTpl={() => setShowCreateTplModal(false)}
        newTplTitle={newTplTitle}
        setNewTplTitle={setNewTplTitle}
        newTplCategory={newTplCategory}
        setNewTplCategory={setNewTplCategory}
        newTplDesc={newTplDesc}
        setNewTplDesc={setNewTplDesc}
        onCreateNewTemplateProperty={handleCreateNewTemplateProperty}
      />

      {/* SIGNATURE CONFIG MODAL */}
      {showSignatureModal && sigModalDocument && (
        <SignatureModal 
          documentData={sigModalDocument}
          databases={databases}
          onClose={() => {
            setShowSignatureModal(false);
            setSigModalDocument(null);
          }}
          onSaveWorkflow={async (docId, x, y, flow) => {
            const firstPendingIdx = flow.findIndex(s => s.status === 'pending');
            const activeIdx = firstPendingIdx === -1 ? Math.max(0, flow.length - 1) : firstPendingIdx;
            const isSigned = flow.length > 0 && firstPendingIdx === -1;

            const updatedDoc = {
              ...sigModalDocument,
              signatureX: x,
              signatureY: y,
              signatureFlow: flow,
              currentStepIndex: activeIdx,
              isSigned: isSigned,
              updatedAt: new Date().toISOString()
            };
            await handleSaveDocument(updatedDoc);
            setShowSignatureModal(false);
            setSigModalDocument(null);
            triggerSwal({
              type: 'success',
              title: 'Alur Ttd Disimpan!',
              text: 'Alur persetujuan dan paraf berhasil disimpan. Anda sekarang dapat mengirimkan tautan persetujuan via WhatsApp.',
              confirmText: 'Selesai'
            });
          }}
        />
      )}

      {/* GLOBAL SWEETALERT DIALOG OVERLAY */}
      {swal && swal.isOpen && (
        <div className="fixed inset-0 bg-slate-950/70 backdrop-blur-xs flex items-center justify-center p-4 z-[9999] animate-in fade-in duration-300" id="global-swal-modal">
          <div className="bg-white rounded-3xl border border-slate-150 shadow-2xl max-w-sm w-full p-7 text-center animate-in zoom-in-95 duration-250 flex flex-col select-none">
            {swal.type === 'success' && (
              <div className="w-16 h-16 bg-emerald-50 border border-emerald-100 text-emerald-600 rounded-full flex items-center justify-center mx-auto mb-4 animate-bounce duration-1000">
                <CheckCircle2 className="w-8 h-8" />
              </div>
            )}
            {swal.type === 'warning' && (
              <div className="w-16 h-16 bg-amber-50 border border-amber-100 text-amber-600 rounded-full flex items-center justify-center mx-auto mb-4">
                <AlertTriangle className="w-8 h-8" />
              </div>
            )}
            {swal.type === 'danger' && (
              <div className="w-16 h-16 bg-red-50 border border-red-100 text-red-650 rounded-full flex items-center justify-center mx-auto mb-4">
                <Trash2 className="w-8 h-8" />
              </div>
            )}
            {swal.type === 'info' && (
              <div className="w-16 h-16 bg-blue-50 border border-blue-100 text-blue-600 rounded-full flex items-center justify-center mx-auto mb-4">
                <Info className="w-8 h-8" />
              </div>
            )}

            <h3 className="text-base font-black text-slate-800 leading-snug tracking-tight mx-1">
              {swal.title}
            </h3>
            
            <p className="text-xs text-slate-500 font-semibold mt-2.5 leading-relaxed mx-1">
              {swal.text}
            </p>

            <div className="flex items-center justify-center gap-3 mt-6">
              {swal.showCancel && (
                <button
                  type="button"
                  onClick={() => setSwal(null)}
                  className="flex-1 py-2.5 bg-white border border-slate-250 hover:bg-slate-50 text-slate-650 rounded-xl text-xs font-bold transition-all cursor-pointer shadow-sm"
                >
                  {swal.cancelText || 'Batal'}
                </button>
              )}
              <button
                type="button"
                onClick={() => {
                  if (swal.onConfirm) {
                    swal.onConfirm();
                  } else {
                    setSwal(null);
                  }
                }}
                className={`py-2.5 rounded-xl text-xs font-black transition-all cursor-pointer hover:scale-[1.01] ${
                  swal.showCancel ? 'flex-1' : 'min-w-[130px] px-6 mx-auto'
                } ${
                  swal.type === 'danger'
                    ? 'bg-red-600 hover:bg-red-500 text-white shadow-md shadow-red-100'
                    : swal.type === 'success'
                    ? 'bg-emerald-600 hover:bg-emerald-500 text-white shadow-md shadow-emerald-100'
                    : swal.type === 'warning'
                    ? 'bg-amber-500 hover:bg-amber-400 text-white shadow-md shadow-amber-100'
                    : 'bg-blue-600 hover:bg-blue-500 text-white shadow-md shadow-blue-100'
                }`}
              >
                {swal.confirmText || 'Oke'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
