import React, { useState, useEffect } from "react";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
import styles from "./FileListComponent.module.css";

const FileListComponent = ({
  setOfficerPerformanceData,   // optional: kirim seri ke parent (compat)
  onTypesLoaded,               // NEW: kirim daftar tipe & seri agregat per tipe
  onPerformanceReady,          // NEW: kirim seri per-bulan saat tipe dibuka
}) => {
  const [files, setFiles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedType, setSelectedType] = useState(null);
  const [entries, setEntries] = useState([]);
  const [loadingEntries, setLoadingEntries] = useState(false);
  const [selectedEntry, setSelectedEntry] = useState(null);
  const [showModal, setShowModal] = useState(false);

  const getOrganizationId = () => {
    try {
      const orgData = localStorage.getItem("selected_organization");
      if (!orgData) return null;
      const parsed = JSON.parse(orgData);
      return parsed.organization_id || null;
    } catch (e) {
      console.error("Gagal membaca organization_id:", e);
      return null;
    }
  };

  // 👉 Download Excel dari daftar entries yang sedang dibuka
  const downloadExcel = () => {
    if (!entries.length) {
      alert("Tidak ada data untuk diunduh.");
      return;
    }

    const flattened = entries.map((e) => ({
      nama_tipe: e.nama_tipe,
      ...e.data,
    }));

    const worksheet = XLSX.utils.json_to_sheet(flattened);

    // Auto width kolom
    const objectMaxLength = [];
    flattened.forEach((row) => {
      Object.keys(row).forEach((key, colIndex) => {
        const value = row[key] ? row[key].toString() : "";
        objectMaxLength[colIndex] = Math.max(
          objectMaxLength[colIndex] || key.length,
          value.length
        );
      });
    });
    worksheet["!cols"] = objectMaxLength.map((w) => ({ wch: w + 2 }));

    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Data");
    const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
    const blob = new Blob([excelBuffer], { type: "application/octet-stream" });
    saveAs(blob, `data_${selectedType?.nama || "dokumen"}.xlsx`);
  };

  // Fetch daftar tipe dari webhook /files
  useEffect(() => {
    const fetchFiles = async () => {
      const token = localStorage.getItem("token");
      const orgId = getOrganizationId();

      try {
        const response = await fetch(
          "https://bot.kediritechnopark.com/webhook/solid-data/files",
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              ...(token ? { Authorization: `Bearer ${token}` } : {}),
            },
            body: JSON.stringify({ organization_id: orgId }),
          }
        );

        const text = await response.text();
        if (!text) {
          setFiles([]);
          return;
        }

        let data;
        try {
          data = JSON.parse(text);
        } catch (err) {
          console.error("Respons bukan JSON valid:", text);
          setFiles([]);
          return;
        }

        const fileData = Array.isArray(data) ? data : data?.data || [];
        setFiles(fileData);

        // === Kirim daftar tipe & seri agregat per tipe ke parent ===
        const typeOptions = fileData.map((f) => ({
          id: f.data_type_id,
          name: f.nama_tipe,
        }));

        const byTypeSeries = fileData.map((f) => ({
          label: f.nama_tipe,                   // sumbu X
          count: Number(f.total_entries || 0),  // tinggi bar
        }));

        if (typeof onTypesLoaded === "function") {
          onTypesLoaded(typeOptions, byTypeSeries);
        }
        // (opsional) kompatibel: tampilkan juga langsung di grafik
        if (typeof setOfficerPerformanceData === "function") {
          setOfficerPerformanceData(byTypeSeries);
        }
      } catch (e) {
        console.error("Gagal fetch files:", e);
        setFiles([]);
      } finally {
        setLoading(false);
      }
    };

    fetchFiles();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Fetch entries per data_type_id (saat user klik suatu tipe)
  const fetchEntries = async (dataTypeId, nama_tipe, entryName, expectation) => {
    let resolvedEntryName = entryName;
    if (!resolvedEntryName && expectation && Object.keys(expectation).length > 0) {
      resolvedEntryName = Object.keys(expectation)[0];
    }

    setSelectedType({ id: dataTypeId, nama: nama_tipe, entryName: resolvedEntryName });
    setEntries([]);
    setLoadingEntries(true);

    try {
      const token = localStorage.getItem("token");
      const response = await fetch(
        "https://bot.kediritechnopark.com/webhook/solid-data/files/entry",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            ...(token ? { Authorization: `Bearer ${token}` } : {}),
          },
          body: JSON.stringify({ data_type_id: dataTypeId }),
        }
      );

      if (!response.ok) throw new Error("Gagal ambil entries");

      const text = await response.text();
      let data;
      try {
        data = JSON.parse(text);
      } catch (e) {
        console.error("Respons bukan JSON valid:", text);
        data = [];
      }

      const entryList = Array.isArray(data) ? data : data?.data || [];

      // Fallback nama field untuk judul kartu
      if (!resolvedEntryName && entryList.length > 0) {
        resolvedEntryName = Object.keys(entryList[0].data || {})[0] || null;
        setSelectedType({ id: dataTypeId, nama: nama_tipe, entryName: resolvedEntryName });
      }

      setEntries(entryList);

      // ====== Hitung seri per-bulan utk tipe yang dibuka ======
      const parseDate = (v) => {
        if (!v) return null;
        const d = new Date(v);
        return isNaN(d) ? null : d;
      };
      const pickDate = (entry) => {
        const cands = [
          entry.created_at,
          entry.updated_at,
          entry.data?.tanggal,
          entry.data?.tgl,
          entry.data?.date,
          entry.data?.created_at,
        ];
        for (const c of cands) {
          const d = parseDate(c);
          if (d) return d;
        }
        return null;
      };
      const mmKey = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;

      const counts = new Map();
      for (const e of entryList) {
        const d = pickDate(e);
        if (!d) continue;
        const k = mmKey(d);
        counts.set(k, (counts.get(k) || 0) + 1);
      }

      const monthlySeries = Array.from(counts.entries())
        .sort((a, b) => (a[0] < b[0] ? -1 : 1))
        .map(([k, v]) => ({ label: k, count: v })); // "label" = YYYY-MM

      if (typeof onPerformanceReady === "function") {
        onPerformanceReady(nama_tipe, monthlySeries);
      }
      // (opsional) bila ingin langsung tampilkan seri bulanan ini
      // if (typeof setOfficerPerformanceData === "function") {
      //   setOfficerPerformanceData(monthlySeries);
      // }
    } catch (err) {
      console.error("Gagal fetch entries:", err);
      setEntries([]);
    } finally {
      setLoadingEntries(false);
    }
  };

  const openEntryModal = (entry) => {
    setSelectedEntry(entry);
    setShowModal(true);
  };

  const closeModal = () => {
    setShowModal(false);
    setSelectedEntry(null);
  };

  const backToTypes = () => {
    setSelectedType(null);
    setEntries([]);
  };

  return (
    <div className={styles.container}>
      <h2 className={styles.title}>📑 Daftar Jenis Dokumen</h2>

      {!selectedType ? (
        <>
          {loading ? (
            <div className={styles.loading}>
              <div className={styles.spinner}></div>
              <p>Sedang memuat...</p>
            </div>
          ) : files.length === 0 ? (
            <div className={styles.emptyState}>
              <div className={styles.emptyStateTitle}>Belum ada data</div>
              <p className={styles.emptyStateText}>
                Tidak ada jenis dokumen yang tersedia saat ini.
              </p>
            </div>
          ) : (
            <ul className={styles.typeList}>
              {files.map((file, index) => (
                <li
                  key={file.data_type_id}
                  className={styles.typeItem}
                  onClick={() =>
                    fetchEntries(
                      file.data_type_id,
                      file.nama_tipe,
                      file.entry_name,
                      file.expectation
                    )
                  }
                >
                  <div className={styles.typeInfo}>
                    <div className={styles.typeNumber}>{index + 1}</div>
                    <div className={styles.typeDetails}>
                      <div className={styles.typeName}>{file.nama_tipe}</div>
                      <div className={styles.typeCount}>
                        {file.total_entries} data tersedia
                      </div>
                    </div>
                  </div>
                  <div className={styles.typeArrow}>→</div>
                </li>
              ))}
            </ul>
          )}
        </>
      ) : (
        <div className={styles.entrySection}>
          <button className={styles.backButton} onClick={backToTypes}>
            ← Kembali ke Daftar Jenis
          </button>

          <h3 className={styles.entryTitle}>
            📂 Isi Dokumen: {selectedType.nama}
          </h3>

          {/* 👉 Tombol Download Excel */}
          {entries.length > 0 && (
            <button className={styles.downloadButton} onClick={downloadExcel}>
              ⬇️ Download Excel
            </button>
          )}

          {loadingEntries ? (
            <div className={styles.loading}>
              <div className={styles.spinner}></div>
              <p>Sedang memuat data...</p>
            </div>
          ) : entries.length === 0 ? (
            <div className={styles.emptyState}>
              <div className={styles.emptyStateTitle}>Belum ada entry</div>
              <p className={styles.emptyStateText}>
                Belum ada entry untuk dokumen ini.
              </p>
            </div>
          ) : (
            <ul className={styles.entryList}>
              {entries.map((entry, index) => (
                <li
                  key={entry.data_id}
                  className={styles.entryItem}
                  onClick={() => openEntryModal(entry)}
                >
                  <div className={styles.entryInfo}>
                    <div className={styles.entryNumber}>{index + 1}</div>
                    <div className={styles.entryDetails}>
                      <div className={styles.entryName}>
                        {entry.data?.[selectedType.entryName] || "Data tidak tersedia"}
                      </div>
                      <div className={styles.entryHint}>
                        Klik untuk melihat detail lengkap
                      </div>
                    </div>
                  </div>
                  <div className={styles.entryArrow}>→</div>
                </li>
              ))}
            </ul>
          )}
        </div>
      )}

      {/* Modal untuk detail entry */}
      {showModal && selectedEntry && (
        <div className={styles.modalOverlay} onClick={closeModal}>
          <div className={styles.modal} onClick={(e) => e.stopPropagation()}>
            <div className={styles.modalHeader}>
              <h3 className={styles.modalTitle}>
                Detail Data:{" "}
                {selectedEntry.data?.[selectedType.entryName] ||
                  selectedEntry.data?.nama ||
                  selectedEntry.data?.name ||
                  "Data"}
              </h3>
              <button className={styles.closeButton} onClick={closeModal}>
                ×
              </button>
            </div>

            <div className={styles.modalContent}>
              <div className={styles.detailGrid}>
                {Object.entries(selectedEntry.data || {}).map(([key, value]) => (
                  <div key={key} className={styles.detailItem}>
                    <div className={styles.detailLabel}>
                      {key
                        .replace(/_/g, " ")
                        .replace(/\b\w/g, (l) => l.toUpperCase())}
                    </div>
                    <div className={styles.detailValue}>{value || "-"}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default FileListComponent;
