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

import React from 'react';
import { Table, PlusCircle } from 'lucide-react';

interface EditorModalsProps {
  showTableModal: boolean;
  setShowTableModal: (val: boolean) => void;
  tableRows: number;
  setTableRows: (val: number) => void;
  tableCols: number;
  setTableCols: (val: number) => void;
  onInsertTable: () => void;

  showVariableModal: boolean;
  setShowVariableModal: (val: boolean) => void;
  newVarName: string;
  setNewVarName: (val: string) => void;
  onInsertVariable: () => void;

  showMarginModal: boolean;
  setShowMarginModal: (val: boolean) => void;
  marginTop: number;
  setMarginTop: (val: number) => void;
  marginBottom: number;
  setMarginBottom: (val: number) => void;
  marginLeft: number;
  setMarginLeft: (val: number) => void;
  marginRight: number;
  setMarginRight: (val: number) => void;
  letterheadHeight: number;
  setLetterheadHeight: (val: number) => void;
  onApplyMargins: (top: number, bottom: number, left: number, right: number, lh: number) => void;
  showKopModal: boolean;
  setShowKopModal: (val: boolean) => void;
  customKopAtas: string;
  setCustomKopAtas: (val: string) => void;
  customKopBawah: string;
  setCustomKopBawah: (val: string) => void;
}

export default function EditorModals({
  showTableModal,
  setShowTableModal,
  tableRows,
  setTableRows,
  tableCols,
  setTableCols,
  onInsertTable,
  showVariableModal,
  setShowVariableModal,
  newVarName,
  setNewVarName,
  onInsertVariable,
  showMarginModal,
  setShowMarginModal,
  marginTop,
  setMarginTop,
  marginBottom,
  setMarginBottom,
  marginLeft,
  setMarginLeft,
  marginRight,
  setMarginRight,
  letterheadHeight,
  setLetterheadHeight,
  onApplyMargins,
  showKopModal,
  setShowKopModal,
  customKopAtas,
  setCustomKopAtas,
  customKopBawah,
  setCustomKopBawah,
}: EditorModalsProps) {
  return (
    <>
      {/* INSERT TABLE POPUP MODAL -- Hidden in Native Print */}
      {showTableModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 print:hidden select-none">
          <div className="bg-white rounded-xl shadow-xl border border-slate-200 p-6 max-w-sm w-full mx-4 animate-in zoom-in-95 duration-150">
            <h3 className="text-lg font-bold text-slate-800 mb-4 flex items-center space-x-2">
              <Table className="w-5 h-5 text-blue-600" />
              <span>Sisipkan Tabel Baru</span>
            </h3>
            
            <div className="grid grid-cols-2 gap-4 mb-5">
              <div>
                <label className="block text-xs font-semibold text-slate-500 mb-1">Baris (Rows)</label>
                <input 
                  id="table-rows-input"
                  type="number" 
                  min="1" 
                  max="15" 
                  value={tableRows} 
                  onChange={(e) => setTableRows(Math.max(1, parseInt(e.target.value) || 1))}
                  className="w-full border border-slate-300 rounded-lg p-2 text-sm focus:outline-none focus:border-blue-500 font-semibold"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-500 mb-1">Kolom (Columns)</label>
                <input 
                  id="table-cols-input"
                  type="number" 
                  min="1" 
                  max="10" 
                  value={tableCols} 
                  onChange={(e) => setTableCols(Math.max(1, parseInt(e.target.value) || 1))}
                  className="w-full border border-slate-300 rounded-lg p-2 text-sm focus:outline-none focus:border-blue-500 font-semibold"
                />
              </div>
            </div>

            <div className="flex space-x-3 justify-end text-xs">
              <button 
                id="table-cancel-btn"
                type="button"
                onClick={() => setShowTableModal(false)}
                className="px-4 py-2 text-slate-600 hover:bg-slate-100 rounded-lg font-bold cursor-pointer"
              >
                Batal
              </button>
              <button 
                id="table-confirm-btn"
                type="button"
                onClick={onInsertTable}
                className="px-4 py-2 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 cursor-pointer shadow-sm shadow-blue-100"
              >
                Terapkan
              </button>
            </div>
          </div>
        </div>
      )}

      {/* INSERT VARIABLE POPUP MODAL -- Hidden in Native Print */}
      {showVariableModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 print:hidden select-none">
          <div className="bg-white rounded-xl shadow-xl border border-slate-200 p-6 max-w-sm w-full mx-4 animate-in zoom-in-95 duration-150">
            <h3 className="text-lg font-bold text-slate-800 mb-1 flex items-center space-x-2">
              <PlusCircle className="w-5 h-5 text-blue-600" />
              <span>Sisipkan Variabel</span>
            </h3>
            <p className="text-xs text-slate-400 mb-4 font-semibold">
              Variabel ini akan diekstrak menjadi isian formulir otomatis saat surat ini digandakan atau diclone.
            </p>
            
            <div className="mb-5">
              <label className="block text-xs font-semibold text-slate-500 mb-1">Nama Variabel (Gunakan huruf/angka/garis bawah)</label>
              <input 
                id="var-name-input"
                type="text" 
                placeholder="cth: Nama_Karyawan, Jabatan_Baru"
                value={newVarName} 
                onChange={(e) => setNewVarName(e.target.value)}
                className="w-full border border-slate-300 rounded-lg p-2 text-sm focus:outline-none focus:border-blue-500 font-bold"
              />
              <span className="text-[10px] text-slate-400 mt-1 block">Spasi otomatis dikonversi menjadi garis bawah (_).</span>
            </div>

            <div className="flex space-x-3 justify-end text-xs">
              <button 
                id="var-cancel-btn"
                type="button"
                onClick={() => setShowVariableModal(false)}
                className="px-4 py-2 text-slate-600 hover:bg-slate-100 rounded-lg font-bold cursor-pointer"
              >
                Batal
              </button>
              <button 
                id="var-confirm-btn"
                type="button"
                onClick={onInsertVariable}
                className="px-4 py-2 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 cursor-pointer shadow-sm shadow-blue-100"
              >
                Sisipkan
              </button>
            </div>
          </div>
        </div>
      )}
      {/* CUSTOM MARGIN POPUP MODAL -- Hidden in Native Print */}
      {showMarginModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 print:hidden select-none">
          <div className="bg-white rounded-xl shadow-xl border border-slate-200 p-6 max-w-sm w-full mx-4 animate-in zoom-in-95 duration-150">
            <h3 className="text-lg font-bold text-slate-800 mb-1 flex items-center space-x-2">
              <span className="text-blue-600">📐</span>
              <span>Pengaturan Margin Kustom</span>
            </h3>
            <p className="text-xs text-slate-400 mb-4 font-semibold">
              Atur batas margin halaman dokumen dalam satuan sentimeter (cm).
            </p>
            
            {/* Margin Inputs Grid */}
            <div className="grid grid-cols-2 gap-4 mb-4">
              <div>
                <label className="block text-xs font-semibold text-slate-500 mb-1">Margin Atas (cm)</label>
                <input 
                  id="margin-top-input"
                  type="number" 
                  step="0.1"
                  min="0" 
                  max="10" 
                  defaultValue={marginTop} 
                  className="w-full border border-slate-300 rounded-lg p-2 text-sm focus:outline-none focus:border-blue-500 font-semibold"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-500 mb-1">Margin Bawah (cm)</label>
                <input 
                  id="margin-bottom-input"
                  type="number" 
                  step="0.1"
                  min="0" 
                  max="10" 
                  defaultValue={marginBottom} 
                  className="w-full border border-slate-300 rounded-lg p-2 text-sm focus:outline-none focus:border-blue-500 font-semibold"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-500 mb-1">Margin Kiri (cm)</label>
                <input 
                  id="margin-left-input"
                  type="number" 
                  step="0.1"
                  min="0" 
                  max="10" 
                  defaultValue={marginLeft} 
                  className="w-full border border-slate-300 rounded-lg p-2 text-sm focus:outline-none focus:border-blue-500 font-semibold"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-500 mb-1">Margin Kanan (cm)</label>
                <input 
                  id="margin-right-input"
                  type="number" 
                  step="0.1"
                  min="0" 
                  max="10" 
                  defaultValue={marginRight} 
                  className="w-full border border-slate-300 rounded-lg p-2 text-sm focus:outline-none focus:border-blue-500 font-semibold"
                />
              </div>
            </div>

            {/* Letterhead height inputs */}
            <div className="border-t border-slate-100 pt-3 mb-5">
              <label className="block text-xs font-bold text-slate-700 mb-1">Tinggi Kop Surat Fisik (cm)</label>
              <p className="text-[10px] text-slate-400 mb-2 font-medium">
                Tinggi area kosong di bagian atas kertas berkop Anda (digunakan saat Mode Kop Fisik aktif).
              </p>
              <input 
                id="margin-lh-input"
                type="number" 
                step="0.1"
                min="0" 
                max="15" 
                defaultValue={letterheadHeight} 
                className="w-full border border-slate-300 rounded-lg p-2 text-sm focus:outline-none focus:border-blue-500 font-bold"
              />
            </div>

            <div className="flex space-x-3 justify-end text-xs">
              <button 
                id="margin-cancel-btn"
                type="button"
                onClick={() => setShowMarginModal(false)}
                className="px-4 py-2 text-slate-600 hover:bg-slate-100 rounded-lg font-bold cursor-pointer"
              >
                Batal
              </button>
              <button 
                id="margin-confirm-btn"
                type="button"
                onClick={() => {
                  const getVal = (id: string, fallback: number) => {
                    const val = parseFloat((document.getElementById(id) as HTMLInputElement).value);
                    return isNaN(val) ? fallback : val;
                  };
                  const top = getVal('margin-top-input', 2.5);
                  const bottom = getVal('margin-bottom-input', 2.5);
                  const left = getVal('margin-left-input', 2.5);
                  const right = getVal('margin-right-input', 2.5);
                  const lh = getVal('margin-lh-input', 5.0);
                  onApplyMargins(top, bottom, left, right, lh);
                }}
                className="px-4 py-2 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 cursor-pointer shadow-sm shadow-blue-100"
              >
                Terapkan
              </button>
            </div>
          </div>
        </div>
      )}

      {/* UPLOAD KOP SURAT POPUP MODAL -- Hidden in Native Print */}
      {showKopModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 print:hidden select-none">
          <div className="bg-white rounded-xl shadow-xl border border-slate-200 p-6 max-w-lg w-full mx-4 animate-in zoom-in-95 duration-150 overflow-y-auto max-h-[90vh]">
            <h3 className="text-lg font-bold text-slate-800 mb-1 flex items-center space-x-2">
              <span className="text-blue-600">🖼️</span>
              <span>Pengaturan Kop Surat Digital</span>
            </h3>
            <p className="text-xs text-slate-400 mb-4 font-semibold">
              Unggah berkas gambar kustom untuk menggantikan gambar Kop Atas dan Kop Bawah default.
            </p>
            
            <div className="space-y-6 mb-6">
              {/* Kop Atas (Header) */}
              <div className="border border-slate-100 rounded-lg p-4 bg-slate-50/50">
                <label className="block text-xs font-bold text-slate-700 mb-2">Kop Atas (Header)</label>
                <div className="mb-3">
                  <div className="text-[10px] text-slate-400 mb-1 font-semibold">Pratinjau Saat Ini:</div>
                  <img 
                    src={customKopAtas || "/kop-atas.jpg"} 
                    alt="Pratinjau Kop Atas" 
                    className="w-full max-h-20 object-contain border border-slate-200 rounded p-1 bg-white" 
                  />
                </div>
                <div className="flex items-center justify-between space-x-2">
                  <input 
                    type="file" 
                    accept="image/*"
                    onChange={(e) => {
                      const file = e.target.files?.[0];
                      if (!file) return;
                      if (file.size > 1.5 * 1024 * 1024) {
                        alert("Ukuran berkas gambar terlalu besar! Batas maksimal adalah 1.5 MB untuk mencegah penyimpanan browser penuh.");
                        return;
                      }
                      const reader = new FileReader();
                      reader.onload = (event) => {
                        setCustomKopAtas(event.target?.result as string);
                      };
                      reader.readAsDataURL(file);
                    }}
                    className="text-xs text-slate-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-xs file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 file:cursor-pointer"
                  />
                  {customKopAtas && (
                    <button
                      type="button"
                      onClick={() => setCustomKopAtas('')}
                      className="px-2 py-1 text-[10px] bg-red-50 text-red-650 hover:bg-red-100 font-bold rounded transition-all cursor-pointer"
                    >
                      Hapus Custom
                    </button>
                  )}
                </div>
              </div>

              {/* Kop Bawah (Footer) */}
              <div className="border border-slate-100 rounded-lg p-4 bg-slate-50/50">
                <label className="block text-xs font-bold text-slate-700 mb-2">Kop Bawah (Footer)</label>
                <div className="mb-3">
                  <div className="text-[10px] text-slate-400 mb-1 font-semibold">Pratinjau Saat Ini:</div>
                  <img 
                    src={customKopBawah || "/kop-bawah.jpg"} 
                    alt="Pratinjau Kop Bawah" 
                    className="w-full max-h-20 object-contain border border-slate-200 rounded p-1 bg-white" 
                  />
                </div>
                <div className="flex items-center justify-between space-x-2">
                  <input 
                    type="file" 
                    accept="image/*"
                    onChange={(e) => {
                      const file = e.target.files?.[0];
                      if (!file) return;
                      if (file.size > 1.5 * 1024 * 1024) {
                        alert("Ukuran berkas gambar terlalu besar! Batas maksimal adalah 1.5 MB untuk mencegah penyimpanan browser penuh.");
                        return;
                      }
                      const reader = new FileReader();
                      reader.onload = (event) => {
                        setCustomKopBawah(event.target?.result as string);
                      };
                      reader.readAsDataURL(file);
                    }}
                    className="text-xs text-slate-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-xs file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 file:cursor-pointer"
                  />
                  {customKopBawah && (
                    <button
                      type="button"
                      onClick={() => setCustomKopBawah('')}
                      className="px-2 py-1 text-[10px] bg-red-50 text-red-650 hover:bg-red-100 font-bold rounded transition-all cursor-pointer"
                    >
                      Hapus Custom
                    </button>
                  )}
                </div>
              </div>
            </div>

            <div className="flex space-x-3 justify-between items-center text-xs">
              <div>
                {(customKopAtas || customKopBawah) && (
                  <button 
                    type="button"
                    onClick={() => {
                      setCustomKopAtas('');
                      setCustomKopBawah('');
                    }}
                    className="px-4 py-2 text-red-650 hover:bg-red-50 rounded-lg font-bold cursor-pointer"
                  >
                    Reset Semua ke Default IKI
                  </button>
                )}
              </div>
              <div className="flex space-x-2">
                <button 
                  id="kop-close-btn"
                  type="button"
                  onClick={() => setShowKopModal(false)}
                  className="px-4 py-2 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 cursor-pointer shadow-sm shadow-blue-100"
                >
                  Selesai
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
