/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useEffect, useRef } from 'react';
import { 
  Database, Trash2, Edit3, Plus, PlusCircle, Check, X, 
  Info, ArrowRight, Settings, FileSpreadsheet, Sparkles
} from 'lucide-react';
import { ReferenceDatabase } from '../types';

interface DashboardSettingsTabProps {
  databases: ReferenceDatabase[];
  onSaveDatabases: (newDbs: ReferenceDatabase[]) => void;
  searchQuery: string;
}

export default function DashboardSettingsTab({
  databases = [],
  onSaveDatabases,
  searchQuery = '',
}: DashboardSettingsTabProps) {
  // Current active database ID
  const [selectedDbId, setSelectedDbId] = useState<string>('db-karyawan');

  // Local state for database addition & column edits
  const [newDbName, setNewDbName] = useState('');
  const [isAddingDb, setIsAddingDb] = useState(false);

  const [renamingDbId, setRenamingDbId] = useState<string | null>(null);
  const [renamingDbVal, setRenamingDbVal] = useState('');

  const [editingColIdx, setEditingColIdx] = useState<{ dbId: string; colName: string } | null>(null);
  const [editingColVal, setEditingColVal] = useState('');

  const [newColName, setNewColName] = useState('');
  const [isAddingCol, setIsAddingCol] = useState(false);

  const isFirstDbMount = useRef(true);
  const [dbSavingState, setDbSavingState] = useState<'saved' | 'saving'>('saved');

  // Custom modals/dialogs states for iframe compatibility
  const [customConfirm, setCustomConfirm] = useState<{
    message: string;
    description?: string;
    onConfirm: () => void;
  } | null>(null);

  const [customAlert, setCustomAlert] = useState<{
    message: string;
    description?: string;
  } | null>(null);

  const triggerConfirm = (message: string, description: string | undefined, onConfirm: () => void) => {
    setCustomConfirm({ message, description, onConfirm });
  };

  const triggerAlert = (message: string, description?: string) => {
    setCustomAlert({ message, description });
  };

  useEffect(() => {
    if (isFirstDbMount.current) {
      isFirstDbMount.current = false;
      return;
    }
    setDbSavingState('saving');
    const timer = setTimeout(() => {
      setDbSavingState('saved');
    }, 600);
    return () => clearTimeout(timer);
  }, [databases]);

  // Active DB object
  const activeDb = databases.find(db => db.id === selectedDbId) || databases[0] || null;

  // Handle cell edit save
  const handleCellChange = (rowIndex: number, colName: string, newValue: string) => {
    if (!activeDb) return;
    const updated = databases.map(db => {
      if (db.id === activeDb.id) {
        const updatedRows = [...db.rows];
        updatedRows[rowIndex] = {
          ...updatedRows[rowIndex],
          [colName]: newValue
        };
        return { ...db, rows: updatedRows };
      }
      return db;
    });
    onSaveDatabases(updated);
  };

  // Add row
  const handleAddRow = () => {
    if (!activeDb) return;
    const updated = databases.map(db => {
      if (db.id === activeDb.id) {
        const newRow: any = { id: `row-${Date.now()}-${Math.random()}` };
        db.columns.forEach(col => {
          newRow[col] = '';
        });
        return { ...db, rows: [...db.rows, newRow] };
      }
      return db;
    });
    onSaveDatabases(updated);
  };

  // Delete row
  const handleDeleteRow = (rowId: string) => {
    if (!activeDb) return;
    const rowObj = activeDb.rows.find(r => r.id === rowId);
    const rowName = rowObj ? (Object.values(rowObj)[1] || Object.values(rowObj)[0] || 'data') : 'baris';
    
    triggerConfirm(
      `Hapus baris data?`,
      `Apakah Anda yakin ingin menghapus baris data "${rowName}"? Tindakan ini bersifat permanen dan tidak dapat dibatalkan.`,
      () => {
        const updated = databases.map(db => {
          if (db.id === activeDb.id) {
            return {
              ...db,
              rows: db.rows.filter(r => r.id !== rowId)
            };
          }
          return db;
        });
        onSaveDatabases(updated);
        setCustomConfirm(null);
      }
    );
  };

  // Add Column
  const handleAddColumnSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!activeDb || !newColName.trim()) return;
    const cleanColName = newColName.trim();
    
    if (activeDb.columns.includes(cleanColName)) {
      triggerAlert('Nama Kolom Sudah Digunakan', 'Silakan pilih nama kolom lain yang belum ada di basis data referensi ini.');
      return;
    }

    const updated = databases.map(db => {
      if (db.id === activeDb.id) {
        const updatedRows = db.rows.map(row => ({
          ...row,
          [cleanColName]: ''
        }));
        return {
          ...db,
          columns: [...db.columns, cleanColName],
          rows: updatedRows
        };
      }
      return db;
    });

    onSaveDatabases(updated);
    setNewColName('');
    setIsAddingCol(false);
  };

  // Rename Column
  const handleRenameColumnSubmit = (oldColName: string) => {
    if (!activeDb || !editingColVal.trim() || oldColName === editingColVal.trim()) {
      setEditingColIdx(null);
      return;
    }
    const cleanNewName = editingColVal.trim();
    if (activeDb.columns.includes(cleanNewName)) {
      triggerAlert('Nama Kolom Sudah Ada', 'Nama kolom tersebut sudah terdaftar di basis data referensi ini.');
      return;
    }

    const updated = databases.map(db => {
      if (db.id === activeDb.id) {
        const updatedCols = db.columns.map(c => c === oldColName ? cleanNewName : c);
        const updatedRows = db.rows.map(row => {
          const newRow = { ...row };
          newRow[cleanNewName] = row[oldColName] || '';
          delete newRow[oldColName];
          return newRow;
        });
        return { ...db, columns: updatedCols, rows: updatedRows };
      }
      return db;
    });

    onSaveDatabases(updated);
    setEditingColIdx(null);
  };

  // Delete Column
  const handleDeleteColumn = (colName: string) => {
    if (!activeDb) return;
    if (activeDb.columns.length <= 1) {
      triggerAlert('Hapus Kolom Gagal', 'Kotak database harus memiliki setidaknya 1 kolom konten agar tabel valid!');
      return;
    }
    
    triggerConfirm(
      `Hapus kolom "${colName}"?`,
      'Seluruh data sel di kolom ini akan dihapus secara permanen. Tindakan ini tidak dapat dibatalkan.',
      () => {
        const updated = databases.map(db => {
          if (db.id === activeDb.id) {
            const updatedCols = db.columns.filter(c => c !== colName);
            const updatedRows = db.rows.map(row => {
              const newRow = { ...row };
              delete newRow[colName];
              return newRow;
            });
            return { ...db, columns: updatedCols, rows: updatedRows };
          }
          return db;
        });

        onSaveDatabases(updated);
        setCustomConfirm(null);
      }
    );
  };

  // Add Database
  const handleAddDatabaseSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newDbName.trim()) return;
    const cleanName = newDbName.trim();

    const newDb: ReferenceDatabase = {
      id: `db-${Date.now()}`,
      name: cleanName,
      columns: ['Nama Baru', 'Keterangan'],
      rows: [
        {
          id: `row-${Date.now()}-1`,
          'Nama Baru': '',
          'Keterangan': ''
        }
      ]
    };

    onSaveDatabases([...databases, newDb]);
    setNewDbName('');
    setIsAddingDb(false);
    setSelectedDbId(newDb.id);
  };

  // Rename Database
  const handleRenameDatabaseSave = (dbId: string) => {
    if (!renamingDbVal.trim()) {
      setRenamingDbId(null);
      return;
    }
    const updated = databases.map(db => {
      if (db.id === dbId) {
        return { ...db, name: renamingDbVal.trim() };
      }
      return db;
    });
    onSaveDatabases(updated);
    setRenamingDbId(null);
  };

  // Delete Database
  const handleDeleteDatabase = (dbId: string, name: string) => {
    if (dbId === 'db-karyawan' || dbId === 'db-pejabat') {
      triggerAlert('Database Bawaan Sistem', 'Basis data ini penting untuk menjaga integritas template dokumen dan tidak dapat dihapus.');
      return;
    }
    
    triggerConfirm(
      `Hapus basis data "${name}"?`,
      'Tindakan ini bersifat permanen. Seluruh skema kolom dan data baris di dalamnya akan segera dihapus selamanya.',
      () => {
        const updated = databases.filter(db => db.id !== dbId);
        onSaveDatabases(updated);
        if (selectedDbId === dbId) {
          setSelectedDbId('db-karyawan');
        }
        setCustomConfirm(null);
      }
    );
  };

  // Filter rows based on search
  const filteredRows = activeDb 
    ? activeDb.rows.filter(row => {
        if (!searchQuery) return true;
        const query = searchQuery.toLowerCase();
        return Object.keys(row).some(key => {
          if (key === 'id') return false;
          return String(row[key]).toLowerCase().includes(query);
        });
      })
    : [];

  return (
    <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 select-none max-w-7xl mx-auto w-full animate-in fade-in duration-200">
      
      {/* 1. LEFT PANEL: DATABASE SELECTOR SIDEBAR */}
      <div className="lg:col-span-1 bg-white border border-slate-200 p-4 rounded-2xl shadow-sm flex flex-col h-fit">
        <div className="flex items-center space-x-2 pb-3 mb-3 border-b border-slate-100">
          <Database className="w-4 h-4 text-blue-600 shrink-0" />
          <h3 className="text-xs font-bold text-slate-800 uppercase tracking-widest font-sans">Basis Referensi</h3>
        </div>

        {/* Database List */}
        <div className="space-y-1.5 flex-1 mb-4">
          {databases.map(db => {
            const isActive = db.id === selectedDbId;
            const isSystem = db.id === 'db-karyawan' || db.id === 'db-pejabat';
            const isRenaming = renamingDbId === db.id;

            return (
              <div 
                key={db.id}
                onClick={() => { if (!isRenaming) setSelectedDbId(db.id); }}
                className={`group flex flex-col p-2.5 rounded-xl border text-left cursor-pointer transition-all ${
                  isActive 
                    ? 'bg-blue-50/75 border-blue-200 text-blue-800 shadow-sm' 
                    : 'bg-white hover:bg-slate-50 border-slate-150 text-slate-650 hover:text-slate-800'
                }`}
              >
                {isRenaming ? (
                  <div className="flex items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
                    <input 
                      type="text"
                      value={renamingDbVal}
                      onChange={(e) => setRenamingDbVal(e.target.value)}
                      className="flex-1 bg-white border border-slate-300 rounded px-1.5 py-1 text-xs font-bold text-slate-800 outline-none focus:ring-1 focus:ring-blue-500"
                      autoFocus
                    />
                    <button 
                      onClick={() => handleRenameDatabaseSave(db.id)}
                      className="p-1 hover:bg-blue-105 rounded text-blue-600"
                    >
                      <Check className="w-3.5 h-3.5" />
                    </button>
                    <button 
                      onClick={() => setRenamingDbId(null)}
                      className="p-1 hover:bg-slate-100 rounded text-slate-500"
                    >
                      <X className="w-3.5 h-3.5" />
                    </button>
                  </div>
                ) : (
                  <div className="flex items-center justify-between min-w-0">
                    <span className="text-[11.5px] font-bold truncate pr-2">
                      {db.name}
                    </span>
                    <span className={`text-[9.5px] px-1.5 py-0.5 rounded-full font-bold shadow-xs shrink-0 ${
                      isActive ? 'bg-blue-600 text-white' : 'bg-slate-100 text-slate-500'
                    }`}>
                      {db.rows.length}
                    </span>
                  </div>
                )}

                {!isRenaming && (
                  <div className="flex items-center justify-between mt-2.5 pt-2 border-t border-dashed border-slate-150/50 opacity-0 group-hover:opacity-100 transition-opacity">
                    <span className="text-[8.5px] text-slate-400 font-bold uppercase tracking-wider">
                      {isSystem ? 'Sistem Bawaan' : 'Kustom User'}
                    </span>
                    <div className="flex items-center space-x-1" onClick={(e) => e.stopPropagation()}>
                      <button
                        title="Ubah nama database"
                        onClick={() => {
                          setRenamingDbId(db.id);
                          setRenamingDbVal(db.name);
                        }}
                        className="p-1 hover:bg-slate-200/50 text-slate-500 hover:text-blue-600 rounded transition-colors"
                      >
                        <Edit3 className="w-3 h-3" />
                      </button>
                      {!isSystem && (
                        <button
                          title="Hapus database"
                          onClick={() => handleDeleteDatabase(db.id, db.name)}
                          className="p-1 hover:bg-red-50 text-slate-400 hover:text-red-600 rounded transition-colors"
                        >
                          <Trash2 className="w-3 h-3" />
                        </button>
                      )}
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>

        {/* Create Database Form */}
        <div className="border-t border-slate-100 pt-3">
          {isAddingDb ? (
            <form onSubmit={handleAddDatabaseSubmit} className="space-y-2">
              <input
                type="text"
                placeholder="cth: Database Cabang"
                value={newDbName}
                onChange={(e) => setNewDbName(e.target.value)}
                className="w-full bg-slate-50 border border-slate-200 rounded-lg px-2.5 py-1.5 text-xs font-semibold outline-none text-slate-700 focus:border-blue-500 focus:bg-white"
                autoFocus
              />
              <div className="flex justify-end space-x-1.5">
                <button
                  type="button"
                  onClick={() => setIsAddingDb(false)}
                  className="bg-slate-100 text-slate-600 text-[10px] font-bold px-2 py-1 rounded-md"
                >
                  Batal
                </button>
                <button
                  type="submit"
                  className="bg-blue-600 text-white text-[10px] font-bold px-2 py-1 rounded-md hover:bg-blue-550"
                >
                  Simpan
                </button>
              </div>
            </form>
          ) : (
            <button
              onClick={() => setIsAddingDb(true)}
              className="w-full py-2 border border-dashed border-slate-250 hover:border-blue-400 text-slate-400 hover:text-blue-600 rounded-lg text-[11px] font-bold flex items-center justify-center space-x-1 transition-all cursor-pointer"
            >
              <Plus className="w-3.5 h-3.5" />
              <span>Tambah Referensi</span>
            </button>
          )}
        </div>
      </div>

      {/* 2. RIGHT PANEL: SPREADSHEET EDITOR VIEW */}
      <div className="lg:col-span-3 bg-white border border-slate-200 rounded-2xl shadow-sm flex flex-col overflow-hidden min-h-[500px]">
        {activeDb ? (
          <div className="flex flex-col flex-1 p-5">
            {/* Header info */}
            <div className="flex flex-col md:flex-row md:items-center justify-between pb-4 border-b border-slate-100 gap-3 mb-4 shrink-0">
              <div>
                <div className="flex items-center space-x-2">
                  <div className="flex items-center space-x-1.5">
                    <FileSpreadsheet className="w-5 h-5 text-emerald-600" />
                    <h2 className="text-sm font-bold text-slate-800">{activeDb.name}</h2>
                  </div>
                  
                  {/* Database Auto-save status indicator */}
                  <span className="text-slate-300 text-xs select-none">•</span>
                  <div className="inline-flex items-center space-x-1 rounded-full bg-slate-50 px-2 py-0.5 border border-slate-100">
                    <span className={`w-1.5 h-1.5 rounded-full ${dbSavingState === 'saving' ? 'bg-amber-550 animate-ping' : 'bg-emerald-500'}`} />
                    <span className={`text-[9.5px] font-bold ${dbSavingState === 'saving' ? 'text-amber-600' : 'text-emerald-605'} uppercase tracking-wide`}>
                      {dbSavingState === 'saving' ? 'Menyimpan...' : 'Autosave Aktif'}
                    </span>
                  </div>
                </div>
                <p className="text-[11px] text-slate-400 font-semibold mt-1">
                  Kertas kerja spreadsheet. Klik langsung pada sel konten untuk mengedit isi data secara instan (inline edit).
                </p>
              </div>

              {/* Top Controls */}
              <div className="flex items-center space-x-2 shrink-0">
                {/* Column creation widget */}
                {isAddingCol ? (
                  <form onSubmit={handleAddColumnSubmit} className="flex gap-1 items-center bg-slate-50 border border-slate-200 rounded-lg p-1">
                    <input
                      type="text"
                      placeholder="Nama Kolom..."
                      value={newColName}
                      onChange={(e) => setNewColName(e.target.value)}
                      className="bg-white border-0 text-[10px] rounded px-1.5 py-1 text-slate-700 outline-none w-28 font-bold focus:ring-1 focus:ring-blue-500"
                      autoFocus
                    />
                    <button type="submit" className="text-emerald-600 p-1 hover:bg-emerald-50 rounded">
                      <Check className="w-3.5 h-3.5 animate-pulse" />
                    </button>
                    <button type="button" onClick={() => setIsAddingCol(false)} className="text-slate-400 p-1 hover:bg-slate-100 rounded">
                      <X className="w-3.5 h-3.5" />
                    </button>
                  </form>
                ) : (
                  <button
                    onClick={() => setIsAddingCol(true)}
                    className="px-2.5 py-1.5 border border-slate-200 hover:border-blue-400 hover:text-blue-600 text-slate-500 text-[11px] font-bold rounded-lg transition-all flex items-center space-x-1 cursor-pointer"
                  >
                    <PlusCircle className="w-3.5 h-3.5 text-blue-500" />
                    <span>Kolom</span>
                  </button>
                )}

                {/* Add standard row */}
                <button
                  onClick={handleAddRow}
                  className="px-3 py-1.5 bg-blue-600 hover:bg-blue-500 active:bg-blue-720 text-white text-[11px] font-bold rounded-lg transition-all flex items-center space-x-1.5 cursor-pointer shadow-sm shadow-blue-100"
                >
                  <Plus className="w-3.5 h-3.5" />
                  <span>Baris</span>
                </button>
              </div>
            </div>

            {/* Helper Alert Banner */}
            <div className="mb-4 px-3 py-2 bg-emerald-50 border border-emerald-100/60 rounded-xl flex items-start space-x-2">
              <Sparkles className="w-3.5 h-3.5 text-emerald-600 mt-0.5 shrink-0 animate-pulse" />
              <p className="text-[10px] text-emerald-800 leading-normal font-semibold">
                Setiap nama kolom di basis data ini secara otomatis terdaftar sebagai variabel di Rich Editor. 
                Misal, jika ada kolom <span className="font-bold underline">"Nomor Telepon Karyawan"</span>, 
                Anda bisa mengetik <span className="font-mono font-bold bg-white px-1 py-0.5 rounded text-emerald-600 shadow-xs border border-emerald-100">(Nomor Telepon Karyawan)</span> di lembar dokumen untuk menyisipkannya!
              </p>
            </div>

            {/* Grid Container with explicit Horizontal & Vertical scrolling requested by user */}
            <div className="flex-1 min-h-[350px] relative max-h-[500px]">
              <div 
                className="absolute inset-0 overflow-x-auto overflow-y-auto border border-slate-150 rounded-xl"
                id="spreadsheet-scroll-box"
              >
                <table className="min-w-full text-left text-xs bg-white border-collapse font-sans table-auto">
                  <thead className="bg-slate-55 sticky top-0 z-10 border-b border-slate-200 select-none">
                    <tr>
                      {/* Fixed column: No / action */}
                      <th className="px-3 py-2.5 text-center bg-slate-100 font-bold text-slate-400 w-12 border-r border-slate-200">
                        No
                      </th>

                      {/* Content Headers representation */}
                      {activeDb.columns.map((col, cIdx) => {
                        const isColRenaming = editingColIdx?.dbId === activeDb.id && editingColIdx?.colName === col;

                        return (
                          <th 
                            key={cIdx} 
                            className="px-3.5 py-2.5 font-bold text-slate-600 border-r border-slate-200 min-w-[160px] bg-slate-50/90 relative group/col"
                          >
                            {isColRenaming ? (
                              <div className="flex items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
                                <input 
                                  type="text"
                                  value={editingColVal}
                                  onChange={(e) => setEditingColVal(e.target.value)}
                                  className="w-full bg-white border border-slate-300 rounded px-1.5 py-0.5 text-xs font-bold text-slate-800 outline-none"
                                  autoFocus
                                />
                                <button 
                                  onClick={() => handleRenameColumnSubmit(col)}
                                  className="text-blue-600 p-0.5 hover:bg-blue-50 rounded"
                                >
                                  <Check className="w-3.5 h-3.5" />
                                </button>
                                <button 
                                  onClick={() => setEditingColIdx(null)}
                                  className="text-slate-450 p-0.5 hover:bg-slate-100 rounded"
                                >
                                  <X className="w-3.5 h-3.5" />
                                </button>
                              </div>
                            ) : (
                              <div className="flex items-center justify-between gap-1.5 w-full">
                                <span className="truncate" title="Klik tombol opsi di samping untuk mengedit atau menghapus kolom">
                                  {col}
                                </span>
                                
                                {/* Permanently visible column actions */}
                                <div className="flex items-center space-x-1 shrink-0 bg-slate-100 border border-slate-200/60 p-0.5 rounded select-none">
                                  <button
                                    title="Ubah nama kolom"
                                    onClick={() => {
                                      setEditingColIdx({ dbId: activeDb.id, colName: col });
                                      setEditingColVal(col);
                                    }}
                                    className="p-1 text-slate-500 hover:text-blue-600 hover:bg-white rounded transition-colors cursor-pointer"
                                  >
                                    <Edit3 className="w-3.5 h-3.5" />
                                  </button>
                                  <button
                                    title="Hapus kolom ini"
                                    onClick={() => handleDeleteColumn(col)}
                                    className="p-1 text-slate-500 hover:text-red-550 hover:bg-white rounded transition-colors cursor-pointer"
                                  >
                                    <Trash2 className="w-3.5 h-3.5" />
                                  </button>
                                </div>
                              </div>
                            )}
                          </th>
                        );
                      })}
                    </tr>
                  </thead>
                  
                  <tbody className="divide-y divide-slate-150">
                    {filteredRows.length === 0 ? (
                      <tr>
                        <td 
                          colSpan={activeDb.columns.length + 1} 
                          className="text-center py-12 px-4 bg-slate-50 text-slate-400 font-bold"
                        >
                          {searchQuery ? 'Data tidak ditemukan untuk kata kunci pencarian tersebut.' : 'Tidak ada baris data. Klik "+ Baris" untuk menambahkan.'}
                        </td>
                      </tr>
                    ) : (
                      filteredRows.map((row, rIdx) => (
                        <tr key={row.id} className="hover:bg-slate-50/40 group/row transition-all divide-x divide-slate-150">
                          {/* Row Indicator with delete action button */}
                          <td className="px-2.5 py-1 text-center bg-slate-55/75 font-bold font-mono text-[10px] text-slate-400 select-none relative w-12 shrink-0">
                            <span className="group-hover/row:opacity-0 transition-opacity">
                              {rIdx + 1}
                            </span>
                            <button
                              onClick={() => handleDeleteRow(row.id)}
                              className="absolute inset-x-0 inset-y-0 m-auto flex items-center justify-center opacity-0 group-hover/row:opacity-100 text-red-500 hover:text-red-700 bg-red-50 hover:bg-red-100 rounded transition-all"
                              title="Hapus baris data"
                            >
                              <Trash2 className="w-3 h-3 pointer-events-none" />
                            </button>
                          </td>

                          {/* Data cells spreadsheet render */}
                          {activeDb.columns.map((col) => (
                            <td key={col} className="p-0 min-w-[160px] relative">
                              <input 
                                type="text"
                                key={`${selectedDbId}-${row.id}-${col}-${row[col] || ''}`}
                                defaultValue={row[col] || ''}
                                onBlur={(e) => handleCellChange(rIdx, col, e.target.value)}
                                className="w-full bg-transparent hover:bg-slate-55/40 focus:bg-white text-[11px] border border-transparent focus:border-blue-500 focus:ring-1 focus:ring-blue-500 rounded px-2.5 py-2 outline-none font-medium text-slate-800 transition-all font-sans"
                              />
                            </td>
                          ))}
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </div>

            {/* Bottom Controls Panel */}
            <div className="flex md:items-center justify-between border-t border-slate-100 pt-3 mt-3 shrink-0 text-[10.5px] font-bold text-slate-400">
              <div className="flex items-center space-x-1.5">
                <Info className="w-3.5 h-3.5 text-blue-500 shrink-0" />
                <span>Tekan tombol <span className="bg-slate-100 px-1 py-0.5 rounded text-slate-600 font-mono">TAB</span> untuk berpindah kolom sel secara mendatar di keyboard Anda.</span>
              </div>
              <span className="shrink-0 text-slate-400">
                Total data: {filteredRows.length} Baris
              </span>
            </div>
          </div>
        ) : (
          <div className="flex-1 flex flex-col items-center justify-center bg-slate-50 text-center p-12">
            <Database className="w-10 h-10 text-slate-350 mx-auto mb-3" />
            <p className="text-xs text-slate-500 font-bold">Harap Pilih atau Tambahkan Basis Data Referensi Baru</p>
          </div>
        )}
      </div>

      {/* CUSTOM CONFIRM DIALOG FOR IFRAMES (SWEETALERT FLAVOR) */}
      {customConfirm && (
        <div className="fixed inset-0 bg-slate-950/65 backdrop-blur-xs flex items-center justify-center p-4 z-[999]" id="custom-confirm-modal">
          <div className="bg-white rounded-2xl border border-slate-150 shadow-2xl max-w-sm w-full p-6 text-center animate-in zoom-in-95 duration-200">
            {/* Animated Swal Danger Icon */}
            <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-7 h-7" />
            </div>
            
            <h3 className="text-base font-black text-slate-800 leading-snug tracking-tight">
              {customConfirm.message}
            </h3>
            
            {customConfirm.description && (
              <p className="text-xs text-slate-500 font-semibold mt-2.5 leading-relaxed">
                {customConfirm.description}
              </p>
            )}

            <div className="flex items-center justify-center gap-3 mt-6">
              <button
                type="button"
                onClick={() => setCustomConfirm(null)}
                className="flex-1 py-2.5 bg-white border border-slate-250 hover:bg-slate-55 text-slate-600 rounded-xl text-xs font-bold transition-all cursor-pointer"
              >
                Batal
              </button>
              <button
                type="button"
                onClick={customConfirm.onConfirm}
                className="flex-1 py-2.5 bg-red-600 hover:bg-red-500 text-white rounded-xl text-xs font-black shadow-sm shadow-red-100 transition-all cursor-pointer hover:scale-[1.01]"
              >
                Ya, Hapus
              </button>
            </div>
          </div>
        </div>
      )}

      {/* CUSTOM ALERT DIALOG FOR IFRAMES (SWEETALERT FLAVOR) */}
      {customAlert && (
        <div className="fixed inset-0 bg-slate-950/60 backdrop-blur-xs flex items-center justify-center p-4 z-[999]" id="custom-alert-modal">
          <div className="bg-white rounded-2xl border border-slate-150 shadow-2xl max-w-sm w-full p-6 text-center animate-in zoom-in-95 duration-200">
            {/* Animated Swal Info Icon */}
            <div className="w-16 h-16 bg-blue-50 border border-blue-100 text-blue-650 rounded-full flex items-center justify-center mx-auto mb-4">
              <Info className="w-7 h-7" />
            </div>
            
            <h3 className="text-base font-black text-slate-800 leading-snug tracking-tight">
              {customAlert.message}
            </h3>
            
            {customAlert.description && (
              <p className="text-xs text-slate-500 font-semibold mt-2.5 leading-relaxed">
                {customAlert.description}
              </p>
            )}

            <div className="mt-6 flex justify-center">
              <button
                type="button"
                onClick={() => setCustomAlert(null)}
                className="min-w-[120px] py-2.5 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-xs font-bold shadow-md shadow-blue-100 transition-all cursor-pointer hover:scale-[1.01]"
              >
                Mengerti
              </button>
            </div>
          </div>
        </div>
      )}

    </div>
  );
}
