import React, { useEffect, useState, useRef } from "react";
import { User, Users, Baby, Settings, Plus, X, Scan, CheckCircle, AlertTriangle, FolderOpen } from "lucide-react";
import { useNavigate } from "react-router-dom";
import styles from "./Dashboard.module.css"; // Import Dashboard CSS
import expetationStyles from "./Expetation.module.css"; // Import Expetation CSS

/* ============================
   Helpers
============================ */
const getCleanToken = () => {
  let raw = localStorage.getItem("token") || "";
  try { raw = JSON.parse(raw); } catch {}
  return String(raw).replace(/^"+|"+$/g, "");
};

// BACA org dari localStorage: utamakan 'selected_organization', fallback 'select_organization'
const getSelectedOrganization = () => {
  let raw =
    localStorage.getItem("selected_organization") ??
    localStorage.getItem("select_organization");
  if (!raw) return null;
  try { return JSON.parse(raw); } catch { return raw; }
};

// Ambil organization_id aktif (string atau object)
const getActiveOrgId = () => {
  const sel = getSelectedOrganization();
  if (!sel) return "";
  if (typeof sel === "object" && sel?.organization_id) return String(sel.organization_id);
  return String(sel);
};

// Header auth standar (ikutkan X-Organization-Id juga)
const authHeaders = () => {
  const token = getCleanToken();
  const orgId = getActiveOrgId();
  return {
    "Content-Type": "application/json",
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
    ...(orgId ? { "X-Organization-Id": orgId } : {}),
  };
};

// ID generator aman
const safeUUID = () => {
  const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).slice(1);
  return `${Date.now().toString(16)}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;
};

// Ubah array fields -> object expectation dengan menjaga urutan
const fieldsToExpectationObject = (fields, forcedOrder = []) => {
  if (!Array.isArray(fields)) return {};
  const base = {};
  fields.forEach((f) => {
    const k = (f?.key || f?.label || "").toString().trim();
    const v = (f?.value || "text").toString().trim();
    if (k) base[k] = v || "text";
  });
  if (!forcedOrder?.length) return base;

  const ordered = {};
  forcedOrder.forEach((k) => {
    if (k in base) ordered[k] = base[k];
  });
  Object.keys(base).forEach((k) => {
    if (!(k in ordered)) ordered[k] = base[k];
  });
  return ordered;
};

const toSlug = (name) =>
  (name || "")
    .toString()
    .trim()
    .toLowerCase()
    .replace(/\s+/g, "_");

/* ============================
   Template Data (Default)
============================ */
const templates = {
  KTP: {
    icon: <User style={{ width: 24, height: 24 }} />,
    fields: [
      { key: "nik", value: "number" },
      { key: "nama", value: "text" },
      { key: "tempat_lahir", value: "text" },
      { key: "tanggal_lahir", value: "date" },
      { key: "jenis_kelamin", value: "selection" },
      { key: "alamat", value: "text" },
      { key: "agama", value: "selection" },
      { key: "status_perkawinan", value: "selection" },
      { key: "pekerjaan", value: "text" },
    ]
  },
  KK: {
    icon: <Users style={{ width: 24, height: 24 }} />,
    fields: [
      { key: "nomor_kk", value: "number" },
      { key: "kepala_keluarga", value: "text" },
      { key: "istri", value: "list" },
      { key: "anak", value: "list" },
      { key: "orang_tua", value: "list" },
      { key: "alamat", value: "text" },
      { key: "rt_rw", value: "text" },
      { key: "kelurahan", value: "text" },
      { key: "kecamatan", value: "text" },
      { key: "kabupaten_kota", value: "text" },
      { key: "provinsi", value: "text" },
    ]
  },
  "Akta Kelahiran": {
    icon: <Baby style={{ width: 24, height: 24 }} />,
    fields: [
      { key: "nomor_akta", value: "text" },
      { key: "nama_anak", value: "text" },
      { key: "jenis_kelamin", value: "selection" },
      { key: "tempat_lahir", value: "text" },
      { key: "tanggal_lahir", value: "date" },
      { key: "nama_ayah", value: "text" },
      { key: "nama_ibu", value: "text" },
    ]
  },
};

// Urutan paksa untuk payload "Akta Kelahiran"
const AKTA_KELAHIRAN_FORCED_ORDER = [
  "nomor_akta",
  "nama_anak",
  "jenis_kelamin",
  "tempat_lahir",
  "tanggal_lahir",
  "nama_ayah",
  "nama_ibu",
];

/* ============================
   ExpectationForm
============================ */
const ExpectationForm = ({ fields, setFields }) => {
  const safeFields = fields?.length ? fields : [{ key: "", value: "" }];

  const updateField = (index, key, value) => {
    const next = safeFields.map((f, i) => (i === index ? { ...f, [key]: value } : f));
    setFields(next);
  };

  const addField = () =>
    setFields([...(safeFields || []), { key: "", value: "" }]);

  const removeField = (index) => {
    const next = safeFields.filter((_, i) => i !== index);
    setFields(next);
  };

  return (
    <div className={expetationStyles.expectationFormContainer}>
      {safeFields.map((f, i) => (
        <div key={i} className={expetationStyles.fieldRow}>
          <input
            type="text"
            placeholder="Field name"
            value={f.key}
            onChange={(e) => updateField(i, "key", e.target.value)}
            className={expetationStyles.fieldInput}
          />
          <select
            value={f.value}
            onChange={(e) => updateField(i, "value", e.target.value)}
            className={expetationStyles.fieldSelect}
          >
            <option value="">Pilih Type</option>
            <option value="text">Text</option>
            <option value="number">Number</option>
            <option value="date">Date</option>
            <option value="boolean">Boolean</option>
            <option value="selection">Selection</option>
            <option value="list">List</option>
          </select>
          <button
            type="button"
            onClick={() => removeField(i)}
            className={expetationStyles.removeFieldButton}
            title="Hapus field"
          >
            <X style={{ width: 16, height: 16 }} />
          </button>
        </div>
      ))}
      <button
        type="button"
        onClick={addField}
        className={expetationStyles.addFieldButton}
      >
        <Plus style={{ width: 16, height: 16, marginRight: 8 }} />
        Tambah Field
      </button>
    </div>
  );
};

/* ============================
   Modal: New Document
============================ */
const NewDocumentModal = ({ isOpen, onClose, onSubmit }) => {
  const [selectedTemplate, setSelectedTemplate] = useState("");
  const [documentName, setDocumentName] = useState("");
  const [fields, setFields] = useState([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setSelectedTemplate("");
      setDocumentName("");
      setFields([]);
    }
  }, [isOpen]);

  const handleTemplateSelect = (templateName) => {
    setSelectedTemplate(templateName);

    if (templateName === "Custom") {
      setDocumentName("");
      setFields([{ key: "", value: "" }]);
    } else {
      const tpl = templates[templateName]?.fields || [];
      setDocumentName(templateName);
      setFields(tpl);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!documentName.trim()) return;

    const validFields = (fields || []).filter(f => f.key && f.key.trim() && f.value);
    if (validFields.length === 0) return;

    setIsSubmitting(true);
    try {
      const forcedOrder = documentName.trim() === "Akta Kelahiran"
        ? AKTA_KELAHIRAN_FORCED_ORDER
        : [];
      const expectationObj = fieldsToExpectationObject(validFields, forcedOrder);
      await onSubmit(documentName.trim(), expectationObj);

      setSelectedTemplate("");
      setDocumentName("");
      setFields([]);
      onClose();
    } catch (err) {
      console.error("Error submit new document type:", err);
      alert("Terjadi kesalahan saat membuat tipe dokumen baru.");
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!isOpen) return null;

  const validFields = (fields || []).filter(f => f.key && f.key.trim() && f.value);
  const isFormValid = documentName.trim() && validFields.length > 0;

  return (
    <div className={expetationStyles.modalOverlay}>
      <div className={expetationStyles.modal}>
        <div className={expetationStyles.modalHeader}>
          <h3 className={expetationStyles.modalTitle}>Tambah Jenis Dokumen Baru</h3>
          <button onClick={onClose} className={expetationStyles.modalCloseButton} disabled={isSubmitting}>×</button>
        </div>

        <form onSubmit={handleSubmit}>
          <div className={expetationStyles.modalContent}>
            {/* Template Selection */}
            <div className={expetationStyles.modalSection}>
              <label className={expetationStyles.sectionLabel}>Pilih Template</label>
              <div className={expetationStyles.templateGrid}>
                {Object.entries(templates).map(([templateName, template]) => (
                  <button
                    key={templateName}
                    type="button"
                    onClick={() => handleTemplateSelect(templateName)}
                    className={`${expetationStyles.templateCard} ${selectedTemplate === templateName ? expetationStyles.templateCardActive : ''}`}
                    disabled={isSubmitting}
                  >
                    <div className={expetationStyles.templateContent}>
                      <div className={`${expetationStyles.templateIconContainer} ${selectedTemplate === templateName ? expetationStyles.templateIconActive : ''}`}>
                        {template.icon}
                      </div>
                      <span className={expetationStyles.templateName}>{templateName}</span>
                    </div>
                  </button>
                ))}

                {/* Custom Template */}
                <button
                  type="button"
                  onClick={() => handleTemplateSelect("Custom")}
                  className={`${expetationStyles.templateCard} ${expetationStyles.customTemplateCard} ${selectedTemplate === "Custom" ? expetationStyles.customTemplateActive : ''}`}
                  disabled={isSubmitting}
                >
                  <div className={expetationStyles.templateContent}>
                    <div className={`${expetationStyles.templateIconContainer} ${selectedTemplate === "Custom" ? expetationStyles.customIconActive : ''}`}>
                      <Settings style={{ width: 24, height: 24 }} />
                    </div>
                    <span className={expetationStyles.templateName}>Custom</span>
                  </div>
                </button>
              </div>
            </div>

            {/* Form Section - hanya muncul jika template dipilih */}
            {selectedTemplate && (
              <>
                <div className={expetationStyles.modalSection}>
                  <label className={expetationStyles.modalLabel}>Nama Tipe Dokumen</label>
                  <input
                    type="text"
                    value={documentName}
                    onChange={(e) => setDocumentName(e.target.value)}
                    placeholder="Contoh: KTP, KK, Ijazah, dll"
                    className={expetationStyles.modalInput}
                    disabled={isSubmitting}
                    required
                  />
                </div>

                <div className={expetationStyles.modalSection}>
                  <label className={expetationStyles.modalLabel}>Fields</label>
                  <ExpectationForm
                    fields={fields}
                    setFields={setFields}
                  />
                </div>
              </>
            )}
          </div>

          {selectedTemplate && (
            <div className={expetationStyles.modalFooter}>
              <button type="button" onClick={onClose} className={expetationStyles.cancelButton} disabled={isSubmitting}>
                Batal
              </button>
              <button
                type="submit"
                className={expetationStyles.submitButton}
                disabled={isSubmitting || !isFormValid}
              >
                {isSubmitting ? "Mengirim..." : "Tambah"}
              </button>
            </div>
          )}
        </form>
      </div>
    </div>
  );
};

/* ============================
   Modal: Edit Document
============================ */
const EditDocumentModal = ({ isOpen, onClose, document, onSubmit }) => {
  const [documentName, setDocumentName] = useState("");
  const [fields, setFields] = useState([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    if (isOpen && document) {
      setDocumentName(document.display_name || document.nama_tipe || "");
      // expectation object -> array of { key, value }
      const initFields = Object.entries(document.expectation || {}).map(([k, v]) => ({
        key: k,
        value: v
      }));
      setFields(initFields.length ? initFields : [{ key: "", value: "" }]);
    }
  }, [isOpen, document]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!documentName.trim()) return;

    const validFields = (fields || []).filter(f => f.key && f.key.trim() && f.value);
    if (!validFields.length) return;

    setIsSubmitting(true);
    try {
      const expectationObj = fieldsToExpectationObject(validFields);
      await onSubmit(document.id, documentName.trim(), expectationObj);
      onClose();
    } catch (err) {
      console.error("Error update document type:", err);
      alert("Gagal memperbarui tipe dokumen.");
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!isOpen) return null;

  const validFields = (fields || []).filter(f => f.key && f.key.trim() && f.value);
  const isFormValid = documentName.trim() && validFields.length > 0;

  return (
    <div className={expetationStyles.modalOverlay}>
      <div className={expetationStyles.modal}>
        <div className={expetationStyles.modalHeader}>
          <h3 className={expetationStyles.modalTitle}>Edit Jenis Dokumen</h3>
          <button onClick={onClose} className={expetationStyles.modalCloseButton} disabled={isSubmitting}>×</button>
        </div>

        <form onSubmit={handleSubmit}>
          <div className={expetationStyles.modalContent}>
            <div className={expetationStyles.modalSection}>
              <label className={expetationStyles.modalLabel}>Nama Tipe Dokumen</label>
              <input
                type="text"
                value={documentName}
                onChange={(e) => setDocumentName(e.target.value)}
                className={expetationStyles.modalInput}
                disabled={isSubmitting}
                required
              />
            </div>

            <div className={expetationStyles.modalSection}>
              <label className={expetationStyles.modalLabel}>Fields</label>
              <ExpectationForm fields={fields} setFields={setFields} />
            </div>
          </div>

          <div className={expetationStyles.modalFooter}>
            <button type="button" onClick={onClose} className={expetationStyles.cancelButton} disabled={isSubmitting}>
              Batal
            </button>
            <button
              type="submit"
              className={expetationStyles.submitButton}
              disabled={isSubmitting || !isFormValid}
            >
              {isSubmitting ? "Menyimpan..." : "Simpan"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

/* ============================
   Komponen Utama: Expetation (Dashboard Style)
============================ */
const Expetation = ({ onSelect }) => {
  const navigate = useNavigate();
  const [documentTypes, setDocumentTypes] = useState([]);
  const [loadingDocumentTypes, setLoadingDocumentTypes] = useState(true);
  const [isEditMode, setIsEditMode] = useState(false);
  const [showNewDocumentModal, setShowNewDocumentModal] = useState(false);
  const [showEditDocumentModal, setShowEditDocumentModal] = useState(false);
  const [editingDocument, setEditingDocument] = useState(null);
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const menuRef = useRef(null);

  const getDocumentDisplayInfo = (doc) => {
    const base = (doc?.display_name ?? doc?.nama_tipe ?? "").toString();
    const pretty = base
      ? base.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase())
      : "Tanpa Nama";
    return { icon: "📄", name: pretty, fullName: pretty };
  };

  // Normalisasi data dari server "show"
  const normalizeItem = (doc) => {
    // UBAH: Prioritas nama_tipe > display_name > document_type
    const humanName = doc.nama_tipe ?? doc.display_name ?? doc.document_type ?? "";
    const slug = toSlug(humanName);

    let expectationObj = {};
    if (doc.expectation && typeof doc.expectation === "object" && !Array.isArray(doc.expectation)) {
      expectationObj = { ...doc.expectation };
    } else if (Array.isArray(doc.expectation)) {
      expectationObj = fieldsToExpectationObject(doc.expectation);
    } else if (Array.isArray(doc.fields)) {
      expectationObj = fieldsToExpectationObject(doc.fields);
    } else if (templates[humanName]) {
      expectationObj = fieldsToExpectationObject(templates[humanName].fields);
    }

    return {
      id: doc.id ?? doc.data_type_id ?? safeUUID(),
      nama_tipe: slug, // UBAH: pastikan selalu ada nama_tipe
      display_name: humanName,
      expectation: expectationObj,
      entry_name: doc.entry_name
    };
  };

  /* ============================
     Komunikasi dengan webhook
  ============================ */

  // Kirim org ke /solid-data/show (GET + query + header)
  const sendSelectedOrgToWebhook = async () => {
    try {
      const orgId = getActiveOrgId();
      const url = new URL("https://bot.kediritechnopark.com/webhook/solid-data/show");
      if (orgId) url.searchParams.set("organization_id", orgId);

      await fetch(url.toString(), {
        method: "GET",
        headers: authHeaders(),
      });
    } catch (err) {
      console.error("Gagal mengirim organization_id ke /solid-data/show:", err);
    }
  };

  // Ambil daftar tipe dokumen (ikutkan organization_id)
  const fetchDocumentTypes = async () => {
    try {
      setLoadingDocumentTypes(true);

      const orgId = getActiveOrgId();
      const url = new URL("https://bot.kediritechnopark.com/webhook/solid-data/show");
      if (orgId) url.searchParams.set("organization_id", orgId);

      const response = await fetch(url.toString(), {
        method: "GET",
        headers: authHeaders(),
      });

      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
      const data = await response.json();

      const normalized = (Array.isArray(data) ? data : [])
        // UBAH: filter berdasarkan nama_tipe dan document_type
        .filter((doc) => {
          const namaType = doc.nama_tipe ?? doc.document_type ?? "";
          return namaType !== "INACTIVE";
        })
        .map(normalizeItem);

      setDocumentTypes(normalized);
    } catch (error) {
      console.error("Error fetching document types:", error);
      // fallback dari templates lokal
      const fallback = Object.keys(templates).map((name) =>
        normalizeItem({
          id: safeUUID(),
          nama_tipe: toSlug(name),
          display_name: name,
          fields: templates[name].fields
        })
      );
      setDocumentTypes(fallback);
    } finally {
      setLoadingDocumentTypes(false);
    }
  };

  // Saat mount: 1) kirim organization_id  2) ambil list tipe dokumen
  useEffect(() => {
    (async () => {
      await sendSelectedOrgToWebhook();
      await fetchDocumentTypes();
    })();
  }, []);

  // Hapus tipe dokumen (POST body + header X-Organization-Id)
  const handleDeleteDocumentType = async (id, namaTipe) => {
    if (window.confirm(`Apakah Anda yakin ingin menghapus dokumen tipe "${namaTipe}"?`)) {
      try {
        const orgId = getActiveOrgId();
        const response = await fetch("https://bot.kediritechnopark.com/webhook/solid-data/delete-expetation-type", {
          method: "POST",
          headers: authHeaders(),
          body: JSON.stringify({
            id,
            nama_tipe: namaTipe, // UBAH: konsisten gunakan nama_tipe
            ...(orgId ? { organization_id: orgId } : {}),
          }),
        });
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        const result = await response.json();

        if (result.success) {
          setDocumentTypes((prev) => prev.filter((d) => d.id !== id));
          alert(`Dokumen tipe "${namaTipe}" berhasil dihapus.`);
        } else {
          console.error("Server reported failure:", result);
          alert(`Gagal menghapus dokumen tipe "${namaTipe}": ${result.message || "Respon tidak menunjukkan keberhasilan."}`);
        }
      } catch (error) {
        console.error("Error deleting document type:", error);
        alert(`Terjadi kesalahan saat menghapus dokumen tipe "${namaTipe}". Detail: ${error.message}`);
      } finally {
        setIsEditMode(false);
      }
    }
  };

  // Buat tipe dokumen baru (POST body + header X-Organization-Id)
  const handleNewDocumentSubmit = async (documentName, expectationObj) => {
    try {
      const orgId = getActiveOrgId();

      const resp = await fetch("https://bot.kediritechnopark.com/webhook/create-data-type", {
        method: "POST",
        headers: authHeaders(),
        body: JSON.stringify({
          nama_tipe: documentName,          // UBAH: konsisten gunakan nama_tipe
          expectation: expectationObj,
          ...(orgId ? { organization_id: orgId } : {}),
        }),
      });

      if (!resp.ok) {
        const text = await resp.text().catch(() => "");
        throw new Error(`HTTP ${resp.status} ${resp.statusText} - ${text}`);
      }

      await fetchDocumentTypes();
      alert(`Dokumen tipe "${documentName}" berhasil dibuat.`);
    } catch (error) {
      console.error("Error submitting new document type:", error);
      alert(`Terjadi kesalahan saat membuat dokumen tipe "${documentName}".`);
    }
  };

  // Edit tipe dokumen (POST body + header X-Organization-Id)
  const handleEditDocumentSubmit = async (id, documentName, expectationObj) => {
    try {
      const orgId = getActiveOrgId();
      const resp = await fetch("https://bot.kediritechnopark.com/webhook/edit-data-type", {
        method: "POST",
        headers: authHeaders(),
        body: JSON.stringify({
          id,
          nama_tipe: documentName,
          expectation: expectationObj,
          ...(orgId ? { organization_id: orgId } : {}),
        }),
      });
      if (!resp.ok) {
        const text = await resp.text().catch(() => "");
        throw new Error(`HTTP ${resp.status} ${resp.statusText} - ${text}`);
      }

      // Asumsi berhasil jika respons HTTP OK dan tidak ada error lain
      await resp.json(); // Tetap baca JSON untuk memastikan respons selesai
      await fetchDocumentTypes();
      alert(`Dokumen tipe "${documentName}" berhasil diperbarui.`);
      window.location.reload(); // Refresh halaman setelah berhasil
    } catch (err) {
      console.error("Error update:", err);
      alert(`Terjadi kesalahan saat update dokumen: ${err.message || "Silakan cek konsol untuk detail lebih lanjut."}`);
    }
  };

  const handleDocumentTypeSelection = (item) => {
    if (!item) return;
    if (item === "new") {
      setShowNewDocumentModal(true);
    } else {
      onSelect?.(item);
    }
  };

  const handleLogout = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("user");
    window.location.reload();
  };

  // Tutup menu ketika klik di luar
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (menuRef.current && !menuRef.current.contains(event.target)) {
        setIsMenuOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Colors for different document types
  const getDocumentColors = (index) => {
    const colors = [
      { bg: '#E8F4FF', icon: '#2563EB' },
      { bg: '#FFF7E6', icon: '#F59E0B' },
      { bg: '#F0FDF4', icon: '#10B981' },
      { bg: '#F3E8FF', icon: '#8B5CF6' },
      { bg: '#FEF2F2', icon: '#EF4444' },
      { bg: '#F0F9FF', icon: '#0EA5E9' },
      { bg: '#FDF4FF', icon: '#D946EF' },
      { bg: '#F7FEE7', icon: '#65A30D' },
    ];
    return colors[index % colors.length];
  };

  return (
    <div className={styles.dashboardContainer}>
      {/* Dashboard Header */}
      <div className={styles.dashboardHeader}>
        <div className={styles.logoAndTitle}>
          <img src="/ikasapta.png" alt="Bot Avatar" />
          <h1 className={styles.h1}>SOLID</h1>
          <h1 className={`${styles.h1} ${styles.h1Accent}`}>DATA</h1>
        </div>

        <div className={styles.dropdownContainer} ref={menuRef}>
          <button
            onClick={() => setIsMenuOpen(!isMenuOpen)}
            className={styles.dropdownToggle}
            aria-expanded={isMenuOpen ? "true" : "false"}
            aria-haspopup="true"
          >
            <svg
              width="15"
              height="20"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              aria-hidden="true"
            >
              <line x1="3" y1="6" x2="21" y2="6" />
              <line x1="3" y1="12" x2="21" y2="12" />
              <line x1="3" y1="18" x2="21" y2="18" />
            </svg>
          </button>
          {isMenuOpen && (
            <div className={styles.dropdownMenu}>
              {/* Dashboard */}
              <button
                onClick={() => {
                  navigate("/dashboard");
                  setIsMenuOpen(false);
                }}
                className={styles.dropdownItem}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="18"
                  height="18"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <rect x="3" y="3" width="7" height="7" />
                  <rect x="14" y="3" width="7" height="7" />
                  <rect x="14" y="14" width="7" height="7" />
                  <rect x="3" y="14" width="7" height="7" />
                </svg>
                <span>Dashboard</span>
              </button>

              {/* Scan */}
              <button
                onClick={() => {
                  navigate("/scan");
                  setIsMenuOpen(false);
                }}
                className={styles.dropdownItem}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="18"
                  height="18"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M3 7V5a2 2 0 0 1 2-2h2" />
                  <path d="M17 3h2a2 2 0 0 1 2 2v2" />
                  <path d="M21 17v2a2 2 0 0 1-2 2h-2" />
                  <path d="M7 21H5a2 2 0 0 1-2-2v-2" />
                  <rect x="7" y="7" width="10" height="10" rx="1" />
                </svg>
                <span>Scan</span>
              </button>

              {/* Logout */}
              <button
                onClick={() => {
                  handleLogout();
                  setIsMenuOpen(false);
                }}
                className={styles.dropdownItem}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="18"
                  height="18"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
                  <polyline points="16 17 21 12 16 7" />
                  <line x1="21" y1="12" x2="9" y2="12" />
                </svg>
                <span>Logout</span>
              </button>
            </div>
          )}
        </div>
      </div>

      {/* Main Content - Dashboard Style */}
      <div className={styles.mainContent}>
         
        <div className={expetationStyles.dashboardContainer}>
          {/* Header dengan Edit Button */}
          <div className={expetationStyles.dashboardHeaderWithEdit}>
            <div className={expetationStyles.dashboardHeaderText}>
              <h2 className={expetationStyles.dashboardHeader}>
                Document Types
              </h2>
              <p className={expetationStyles.paragraf}>
                Choose a document type to scan or create a new one
              </p>
            </div>
          </div>

          {/* Dashboard Grid */}
          <div className={expetationStyles.dashboardGrid}>
            {/* Add New Document Type Button */}
            <button
              onClick={() => setShowNewDocumentModal(true)}
              className={expetationStyles.dashboardCard}
            >
              <div className={`${expetationStyles.dashboardIconContainer} ${expetationStyles.dashboardIconAdd}`}>
                <Plus size={28} />
              </div>
              <div className={expetationStyles.dashboardCardText}>
                <div className={expetationStyles.dashboardCardTitle}>
                  Add New
                </div>
                <div className={expetationStyles.dashboardCardSubtitle}>
                  Document Type
                </div>
              </div>
            </button>

            {/* Loading State */}
            {loadingDocumentTypes ? (
              <div className={expetationStyles.dashboardCard}>
                <div className={expetationStyles.spinnerContainer}>
                  <div className={expetationStyles.spinner} />
                </div>
              </div>
            ) : (
              /* User Created Document Types */
              documentTypes.map((doc, index) => {
                const displayInfo = getDocumentDisplayInfo(doc);
                const colors = getDocumentColors(index);
                
                return (
                  <div key={doc.id} className={expetationStyles.documentCardWrapper}>
                    <button 
                      onClick={() => handleDocumentTypeSelection(doc)} 
                      className={expetationStyles.dashboardCard}
                    >
                      {/* Icon */}
                      <div 
                        className={expetationStyles.dashboardIconContainer}
                        style={{ 
                          backgroundColor: colors.bg,
                          color: colors.icon 
                        }}
                      >
                        <FolderOpen size={28} />
                      </div>
                      
                      {/* Text */}
                      <div className={expetationStyles.dashboardCardText}>
                        <div className={expetationStyles.dashboardCardTitle}>
                          {displayInfo.name}
                        </div>
                        <div className={expetationStyles.dashboardCardSubtitle}>
                          Document Type
                        </div>
                      </div>
                    </button>
                    
                    {/* Edit and Delete Buttons (only visible in edit mode) */}
                    {isEditMode && (
                      <div className={expetationStyles.editDeleteWrapper}>
                        <button
                          className={expetationStyles.editIcon}
                          onClick={() => {
                            setEditingDocument(doc);
                            setShowEditDocumentModal(true);
                          }}
                          title="Edit document type"
                        >
                          ✎
                        </button>
                        <button
                          className={expetationStyles.deleteIcon}
                          onClick={() => handleDeleteDocumentType(doc.id, doc.nama_tipe)}
                          title="Delete document type"
                        >
                          ×
                        </button>
                      </div>
                    )}
                    
                  </div>
                );
              })
            )}
            
          </div>

          {/* Edit Button - Positioned at Bottom */}
          <button 
            onClick={() => setIsEditMode(!isEditMode)} 
            className={expetationStyles.editButton}
          >
            {isEditMode ? "Done" : "Edit"}
          </button>
          </div>
        </div>

      {/* Footer */}
      <div className={styles.footer}>
        © 2025 Kediri Technopark • Dashboard SOLID DATA
      </div>

      {/* Modals */}
      <NewDocumentModal
        isOpen={showNewDocumentModal}
        onClose={() => setShowNewDocumentModal(false)}
        onSubmit={handleNewDocumentSubmit}
      />

      <EditDocumentModal
        isOpen={showEditDocumentModal}
        onClose={() => setShowEditDocumentModal(false)}
        document={editingDocument}
        onSubmit={handleEditDocumentSubmit}
      />
    </div>
  );
};

export default Expetation;
