import { useEffect, useMemo, useState } from "react";
import {
  Users,
  Eye,
  Activity,
  CalendarDays,
  RefreshCw,
  BarChart3,
  MousePointerClick,
  ShieldCheck,
} from "lucide-react";

const SUMMARY_API = "http://localhost/api/visitor/summary.php";

const formatNumber = (value) => Number(value || 0).toLocaleString("id-ID");

const formatDateShort = (value) => {
  if (!value) return "-";

  return new Date(value).toLocaleDateString("id-ID", {
    day: "2-digit",
    month: "short",
  });
};

const cardConfig = [
  {
    key: "total_pengunjung",
    label: "Total Pengunjung",
    icon: Users,
    color: "text-blue-700",
    bg: "bg-blue-50",
  },
  {
    key: "pengunjung_hari_ini",
    label: "Pengunjung Hari Ini",
    icon: CalendarDays,
    color: "text-emerald-700",
    bg: "bg-emerald-50",
  },
  {
    key: "sedang_online",
    label: "Sedang Online",
    icon: Activity,
    color: "text-cyan-700",
    bg: "bg-cyan-50",
  },
  {
    key: "halaman_dibuka_hari_ini",
    label: "Halaman Dibuka Hari Ini",
    icon: Eye,
    color: "text-amber-700",
    bg: "bg-amber-50",
  },
];

export default function VisitorStats({ mode = "full", title = "Statistik Pengunjung" }) {
  const [data, setData] = useState({
    summary: {
      total_pengunjung: 0,
      pengunjung_hari_ini: 0,
      sedang_online: 0,
      halaman_dibuka_hari_ini: 0,
    },
    grafik_7_hari: [],
    halaman_populer: [],
    role_aktif: [],
  });

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const loadData = async () => {
    try {
      setLoading(true);
      setError("");

      const res = await fetch(SUMMARY_API);

      if (!res.ok) {
        throw new Error(`HTTP Error ${res.status}`);
      }

      const result = await res.json();

      if (!result.success) {
        setError(result.message || "Gagal mengambil statistik pengunjung");
        return;
      }

      setData({
        summary: result.data?.summary || data.summary,
        grafik_7_hari: Array.isArray(result.data?.grafik_7_hari)
          ? result.data.grafik_7_hari
          : [],
        halaman_populer: Array.isArray(result.data?.halaman_populer)
          ? result.data.halaman_populer
          : [],
        role_aktif: Array.isArray(result.data?.role_aktif)
          ? result.data.role_aktif
          : [],
      });
    } catch (err) {
      console.error("Gagal mengambil statistik pengunjung:", err);
      setError("Gagal mengambil statistik pengunjung dari server.");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();

    const interval = setInterval(loadData, 30000);
    return () => clearInterval(interval);
  }, []);

  const maxGrafik = useMemo(() => {
    const values = data.grafik_7_hari.map((item) => Number(item.pengunjung) || 0);
    return Math.max(...values, 1);
  }, [data.grafik_7_hari]);

  const maxRole = useMemo(() => {
    const values = data.role_aktif.map((item) => Number(item.total_aktivitas) || 0);
    return Math.max(...values, 1);
  }, [data.role_aktif]);

  const showDetail = mode !== "compact";

  return (
    <section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
      <div className="mb-5 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <div className="inline-flex items-center gap-2 rounded-full bg-blue-50 px-3 py-1 text-xs font-bold text-blue-700">
            <BarChart3 className="h-3.5 w-3.5" />
            Real-time
          </div>

          <h2 className="mt-3 text-2xl font-black text-slate-950">
            {title}
          </h2>

          <p className="mt-1 text-sm text-slate-500">
            Data pengunjung dihitung otomatis dari aktivitas website.
          </p>
        </div>

        <button
          type="button"
          onClick={loadData}
          className="inline-flex w-fit items-center gap-2 rounded-xl border border-blue-100 bg-white px-3 py-2 text-xs font-bold text-blue-700 shadow-sm transition hover:bg-blue-50"
        >
          <RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
          Refresh
        </button>
      </div>

      {error && (
        <div className="mb-5 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-semibold text-amber-700">
          {error}
        </div>
      )}

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {cardConfig.map((item) => {
          const Icon = item.icon;

          return (
            <div
              key={item.key}
              className="rounded-2xl border border-slate-200 bg-slate-50 p-5"
            >
              <div className="mb-4 flex items-center justify-between gap-3">
                <p className="text-sm font-semibold text-slate-500">
                  {item.label}
                </p>

                <div className={`flex h-11 w-11 items-center justify-center rounded-2xl ${item.bg} ${item.color}`}>
                  <Icon className="h-5 w-5" />
                </div>
              </div>

              <p className={`text-3xl font-black ${item.color}`}>
                {loading ? "..." : formatNumber(data.summary[item.key])}
              </p>
            </div>
          );
        })}
      </div>

      {showDetail && (
        <div className="mt-6 grid grid-cols-1 gap-6 xl:grid-cols-[1.1fr_0.9fr]">
          <div className="rounded-2xl border border-slate-200 bg-slate-50 p-5">
            <div className="mb-4 flex items-center gap-2">
              <BarChart3 className="h-5 w-5 text-blue-700" />
              <h3 className="font-black text-slate-900">
                Grafik Pengunjung 7 Hari Terakhir
              </h3>
            </div>

            <div className="flex h-52 items-end gap-3">
              {data.grafik_7_hari.map((item) => {
                const height = Math.max((Number(item.pengunjung) / maxGrafik) * 100, 6);

                return (
                  <div key={item.tanggal} className="flex flex-1 flex-col items-center justify-end gap-2">
                    <div className="text-xs font-bold text-slate-500">
                      {formatNumber(item.pengunjung)}
                    </div>

                    <div className="flex h-36 w-full items-end rounded-xl bg-white p-1">
                      <div
                        className="w-full rounded-lg bg-gradient-to-t from-blue-700 to-cyan-400 transition-all"
                        style={{ height: `${height}%` }}
                      />
                    </div>

                    <div className="text-[11px] font-semibold text-slate-500">
                      {formatDateShort(item.tanggal)}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="space-y-6">
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-5">
              <div className="mb-4 flex items-center gap-2">
                <MousePointerClick className="h-5 w-5 text-blue-700" />
                <h3 className="font-black text-slate-900">
                  Halaman Paling Sering Dikunjungi
                </h3>
              </div>

              <div className="space-y-3">
                {data.halaman_populer.length === 0 ? (
                  <p className="text-sm text-slate-500">Belum ada data halaman.</p>
                ) : (
                  data.halaman_populer.slice(0, 5).map((item) => (
                    <div key={item.page_url} className="rounded-xl bg-white px-4 py-3">
                      <div className="flex items-center justify-between gap-3">
                        <p className="truncate text-sm font-bold text-slate-800">
                          {item.page_url}
                        </p>
                        <span className="text-sm font-black text-blue-700">
                          {formatNumber(item.total_dibuka)}
                        </span>
                      </div>
                      <p className="mt-1 text-xs text-slate-500">
                        {formatNumber(item.total_pengunjung)} pengunjung unik
                      </p>
                    </div>
                  ))
                )}
              </div>
            </div>

            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-5">
              <div className="mb-4 flex items-center gap-2">
                <ShieldCheck className="h-5 w-5 text-blue-700" />
                <h3 className="font-black text-slate-900">
                  Role Paling Aktif
                </h3>
              </div>

              <div className="space-y-3">
                {data.role_aktif.length === 0 ? (
                  <p className="text-sm text-slate-500">Belum ada aktivitas role.</p>
                ) : (
                  data.role_aktif.map((item) => {
                    const width = Math.max((Number(item.total_aktivitas) / maxRole) * 100, 5);

                    return (
                      <div key={item.role} className="rounded-xl bg-white px-4 py-3">
                        <div className="mb-2 flex items-center justify-between gap-3">
                          <p className="text-sm font-bold text-slate-800">
                            {item.label}
                          </p>
                          <span className="text-xs font-black text-blue-700">
                            {formatNumber(item.total_aktivitas)} aktivitas
                          </span>
                        </div>

                        <div className="h-2 overflow-hidden rounded-full bg-slate-100">
                          <div
                            className="h-full rounded-full bg-blue-600"
                            style={{ width: `${width}%` }}
                          />
                        </div>
                      </div>
                    );
                  })
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}
