import React, { useState, useRef, useEffect } from "react";
import styles from "./Dashboard.module.css";
import { useNavigate, useParams } from "react-router-dom";
import FileListComponent from "./FileListComponent";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
} from "recharts";

// Konsistenkan base URL (tanpa tanda minus)
const API_BASE = "https://bot.kediritechnopark.com/webhook/soliddata";

const Dashboard = () => {
  const navigate = useNavigate();

  // Ambil org dari URL, lalu sediakan fallback ke localStorage
  const { organization_id: orgParam } = useParams();
  const [organizationId, setOrganizationId] = useState(
    orgParam || localStorage.getItem("organization_id") || ""
  );

  useEffect(() => {
    if (orgParam) {
      localStorage.setItem("organization_id", orgParam);
      setOrganizationId(orgParam);
    }
  }, [orgParam]);

  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const menuRef = useRef(null);

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [successMessage, setSuccessMessage] = useState("");
  const [errorMessage, setErrorMessage] = useState("");

  const [user, setUser] = useState({});
  const [totalFilesSentToday, setTotalFilesSentToday] = useState(0);
  const [totalFilesSentMonth, setTotalFilesSentMonth] = useState(0);
  const [totalFileSentYear, setTotalFileSentYear] = useState(0);
  const [totalFilesSentOverall, setTotalFilesSentOverall] = useState(0);

  // === Grafik ===
  const [officerPerformanceData, setOfficerPerformanceData] = useState([]); // data yang sedang ditampilkan di chart
  const [byTypeSeries, setByTypeSeries] = useState([]);           // dari /files: [{ label: nama_tipe, count }]
  const [typeOptions, setTypeOptions] = useState([]);              // daftar tipe untuk dropdown: [{id, name}]
  const [performanceByType, setPerformanceByType] = useState({});  // { [nama_tipe]: monthlySeries [{label: 'YYYY-MM', count}] }
  const [chartKey, setChartKey] = useState("");                    // "" = semua tipe (agregat), selain itu = nama_tipe (tren bulanan)
  const [officers, setOfficers] = useState([]);

  // Terima daftar tipe + seri per-tipe dari FileListComponent (/files)
  const handleTypesLoaded = (options, series) => {
    setTypeOptions(options || []);
    setByTypeSeries(series || []);
    // Default grafik: tampilkan agregat per-tipe
    setOfficerPerformanceData(series || []);
    setChartKey(""); // mode "Semua tipe"
  };

  // Terima seri bulanan saat tipe dibuka di FileListComponent
  const handlePerformanceReady = (typeName, monthlySeries) => {
    setPerformanceByType((prev) => ({ ...prev, [typeName]: monthlySeries }));
    // Jika user sedang memilih tipe ini → langsung update grafik
    if (chartKey === typeName) {
      setOfficerPerformanceData(monthlySeries || []);
    }
  };

  // Header auth + optional X-Organization-Id
  const authHeaders = (extra = {}) => {
    const token = localStorage.getItem("token");
    const headers = {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
      ...extra,
    };
    return headers;
  };

  // Pastikan login
  useEffect(() => {
    const token = localStorage.getItem("token");
    if (!token) {
      navigate("/login");
      return;
    }
    // Opsional: jika org kosong, arahkan user ke pemilihan organisasi
    if (!organizationId) {
      setErrorMessage("Organisasi tidak terdeteksi. Silakan akses dashboard melalui tautan organisasi.");
    }
  }, [organizationId, navigate]);

  // Verifikasi token & fetch ringkasan dashboard org aktif
  useEffect(() => {
    const verifyTokenAndFetchData = async () => {
      const token = localStorage.getItem("token");
      if (!token || !organizationId) return;

      const toNum = (v) => {
        const n = typeof v === "number" ? v : Number(v ?? 0);
        return Number.isFinite(n) ? n : 0;
      };

      try {
        // Fetch total scans data (pakai API_BASE yang konsisten)
        const totalScansRes = await fetch(
          `${API_BASE}/total-scans?organization_id=${encodeURIComponent(
            organizationId
          )}`,
          { method: "GET", headers: authHeaders() }
        );
        const totalScansRaw = await totalScansRes.json();
        console.log("RAW total-scans payload:", totalScansRaw);

        if (!totalScansRes.ok) {
          console.error("Total Scans error:", totalScansRaw);
        } else {
          const totalScansPayload = Array.isArray(totalScansRaw)
            ? totalScansRaw[0]
            : totalScansRaw;
          setTotalFilesSentToday(toNum(totalScansPayload?.total_today));
          setTotalFilesSentMonth(toNum(totalScansPayload?.total_month));
          setTotalFileSentYear(toNum(totalScansPayload?.total_year));
          setTotalFilesSentOverall(toNum(totalScansPayload?.total_overall));
        }

        // Fetch dashboard (user, officer performance default)
        const res = await fetch(
          `${API_BASE}/dashboard?organization_id=${encodeURIComponent(
            organizationId
          )}`,
          { method: "GET", headers: authHeaders() }
        );
        const raw = await res.json();
        console.log("RAW dashboard payload:", raw);
        if (!res.ok) {
          console.error("Dashboard error:", raw);
        }

        const payload = Array.isArray(raw) ? raw[0] : raw;
        if (payload?.user) setUser(payload.user);

        // Kalau backend kirim default "officerPerformance", tetap tampilkan (akan ditimpa saat /files datang)
        if (Array.isArray(payload?.officerPerformance)) {
          setOfficerPerformanceData(payload.officerPerformance);
          setChartKey(""); // mode umum
        }
      } catch (err) {
        console.error("Token/Fetch dashboard gagal:", err);
      }
    };

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

  // Ambil daftar officer (khusus admin)
  const fetchOfficers = async () => {
    if (!organizationId) return;

    try {
      const res = await fetch(
        `${API_BASE}/list-user?organization_id=${encodeURIComponent(
          organizationId
        )}`,
        { method: "GET", headers: authHeaders() }
      );
      const data = await res.json();
      setOfficers(Array.isArray(data) ? data : []);
    } catch (err) {
      console.error("Gagal memuat daftar officer:", err);
    }
  };

  useEffect(() => {
    if (user?.role === "admin") {
      fetchOfficers();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.role]);

  const handleLogout = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("user");
    localStorage.removeItem("organization_id"); // bersihkan juga orgId
    window.location.reload();
  };

  const handleAddOfficer = async (e) => {
    e.preventDefault();
    if (!organizationId) return;

    try {
      const res = await fetch(`${API_BASE}/add-officer`, {
        method: "POST",
        headers: authHeaders(),
        body: JSON.stringify({
          username,
          password,
          organization_id: organizationId,
        }),
      });

      const data = await res.json();

      if (!res.ok || data.success === false) {
        throw new Error(data.message || "Gagal menambahkan officer");
      }

      setSuccessMessage("Officer berhasil ditambahkan");
      setUsername("");
      setPassword("");
      setErrorMessage("");

      await fetchOfficers();
    } catch (err) {
      setErrorMessage(err.message || "Gagal menambahkan officer");
      setSuccessMessage("");
    }
  };

  const handleDeleteOfficer = async (id) => {
    const confirmDelete = window.confirm(
      "Apakah Anda yakin ingin menghapus petugas ini?"
    );
    if (!confirmDelete) return;

    if (!organizationId) return;

    try {
      const res = await fetch(`${API_BASE}/delete-officer`, {
        method: "DELETE",
        headers: authHeaders(),
        body: JSON.stringify({
          id,
          organization_id: organizationId,
        }),
      });

      const data = await res.json();

      if (!res.ok || data.success === false) {
        throw new Error(data.message || "Gagal menghapus officer");
      }

      setOfficers((prev) => prev.filter((o) => o.id !== id));
    } catch (err) {
      alert("Gagal menghapus petugas: " + err.message);
    }
  };

  // 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);
  }, []);

  const { orgName } = {};

  // ====== WRAPPER SETTER untuk proteksi dari FileListComponent ======
  const safeSetToday = (v) => {
    const n = Number(v ?? 0);
    if (Number.isFinite(n)) setTotalFilesSentToday(n);
  };
  const safeSetMonth = (v) => {
    const n = Number(v ?? 0);
    if (Number.isFinite(n)) setTotalFilesSentMonth(n);
  };
  const safeSetYear = (v) => {
    const n = Number(v ?? 0);
    if (Number.isFinite(n)) setTotalFileSentYear(n);
  };
  const safeSetOverall = (v) => {
    const n = Number(v ?? 0);
    if (Number.isFinite(n)) setTotalFilesSentOverall(n);
  };

  return (
    <div className={styles.dashboardContainer}>
      <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}>
              {/* Static Organization */}
              <div className={styles.dropdownItemStatic}>
                <div className={styles.dropdownText}>
                  <strong>Organisasi</strong>
                  <div className={styles.orgName}>{orgName}</div>
                </div>
              </div>

              {/* Scan */}
              <button
                onClick={() => {
                  // Selalu bawa organizationId saat navigasi
                  if (organizationId) {
                    navigate(`/scan/${organizationId}`);
                  } else {
                    setErrorMessage("Organisasi tidak terdeteksi.");
                  }
                  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>

      {/* ... sisanya tetap sama persis */}
      <div className={styles.mainContent}>
        {errorMessage && (
          <div className={styles.error} style={{ marginBottom: 12 }}>
            {errorMessage}
          </div>
        )}

        <div className={styles.summaryCardsContainer}>
          <div className={styles.summaryCard}>
            <h3>Hari Ini</h3>
            <p>{totalFilesSentToday.toLocaleString()}</p>
          </div>
          <div className={styles.summaryCard}>
            <h3>Bulan Ini</h3>
            <p>{totalFilesSentMonth.toLocaleString()}</p>
          </div>
          <div className={styles.summaryCard}>
            <h3>Tahun Ini</h3>
            <p>{totalFileSentYear.toLocaleString()}</p>
          </div>
          <div className={styles.summaryCard}>
            <h3>Total Keseluruhan</h3>
            <p>{totalFilesSentOverall.toLocaleString()}</p>
          </div>
        </div>

        <div className={styles.dashboardGrid}>
          {user?.role === "admin" && (
            <div className={styles.formSection}>
              <h2>Daftar Petugas</h2>
              <div className={styles.officerListContainer}>
                <div className={styles.officerList}>
                  {officers.length > 0 ? (
                    officers.map((officer) => (
                      <div key={officer.id} className={styles.officerItem}>
                        <div className={styles.officerInfo}>
                          <span className={styles.officerIcon}>👤</span>
                          <div className={styles.officerDetails}>
                            <strong className={styles.officerName}>
                              {officer.username}
                            </strong>
                            <span className={styles.officerRole}>
                              {officer.role}
                            </span>
                          </div>
                        </div>
                        <button
                          onClick={() => handleDeleteOfficer(officer.id)}
                          className={styles.deleteButton}
                          title="Hapus Petugas"
                        >
                          ❌
                        </button>
                      </div>
                    ))
                  ) : (
                    <div className={styles.emptyState}>
                      <span>📋</span>
                      <p>Belum ada petugas terdaftar</p>
                    </div>
                  )}
                </div>
              </div>

              <hr className={styles.separator} />
              <h2>Tambah Petugas Baru</h2>
              <form onSubmit={handleAddOfficer} className={styles.form}>
                <label>
                  Username
                  <input
                    type="text"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    placeholder="Masukkan username"
                    required
                  />
                </label>
                <label>
                  Password
                  <input
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="Masukkan password"
                    required
                  />
                </label>
                <button type="submit" className={styles.submitButton}>
                  Tambah Officer
                </button>
              </form>

              {successMessage && (
                <p className={styles.success}>{successMessage}</p>
              )}
              {errorMessage && <p className={styles.error}>{errorMessage}</p>}
            </div>
          )}

          <div className={styles.chartSection}>
            <div className={styles.chartHeader}>
              <h2>Grafik Upload Dokumen</h2>

              <div className={styles.chartFilter}>
                <label htmlFor="chartTypeSelect">Filter tipe:&nbsp;</label>
                <select
                  id="chartTypeSelect"
                  value={chartKey}
                  onChange={(e) => {
                    const key = e.target.value;
                    setChartKey(key);
                    if (!key) {
                      // Semua tipe → pakai agregat per-tipe
                      setOfficerPerformanceData(byTypeSeries);
                      return;
                    }
                    // Jika sudah ada seri bulanan tipe tsb → pakai
                    if (performanceByType[key]?.length) {
                      setOfficerPerformanceData(performanceByType[key]);
                    } else {
                      // fallback sementara: 1 bar dari agregat tipe
                      const one = byTypeSeries.find((s) => s.label === key);
                      setOfficerPerformanceData(one ? [one] : []);
                    }
                  }}
                  disabled={typeOptions.length === 0}
                >
                  <option value="">Semua tipe</option>
                  {typeOptions.map((t) => (
                    <option key={t.id} value={t.name}>
                      {t.name}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {officerPerformanceData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={officerPerformanceData}>
                  <XAxis dataKey="label" /> {/* label = nama_tipe ATAU YYYY-MM */}
                  <YAxis allowDecimals={false} />
                  <Tooltip />
                  <Bar dataKey="count" fill="var(--brand-primary)" />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <div className={styles.warning}>
                📋 Belum ada data upload untuk ditampilkan
              </div>
            )}
          </div>
        </div>

        <FileListComponent
          organizationId={organizationId}
          // Gunakan wrapper agar nilai dari child selalu angka valid
          setTotalFilesSentToday={safeSetToday}
          setTotalFilesSentMonth={safeSetMonth}
          setTotalFileSentYear={safeSetYear}
          setTotalFilesSentOverall={safeSetOverall}
          // tampilkan agregat saat /files selesai
          setOfficerPerformanceData={setOfficerPerformanceData}
          // === baru: terima daftar tipe + agregat & seri bulanan
          onTypesLoaded={handleTypesLoaded}
          onPerformanceReady={handlePerformanceReady}
        />
      </div>

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

export default Dashboard;
