import React, { useState, useEffect } from "react";
import { KPICard } from "../ui/KPICard";
import { cn } from "../../../lib/utils";
import { getOverviewKPIs } from "../../../services/dashboardService";

export const OverviewSection = ({ onJumpToSection, activeAccountId }) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [kpis, setKpis] = useState(null);
  const [newestProducts, setNewestProducts] = useState([]);

  // Lade KPIs wenn activeAccountId sich ändert
  useEffect(() => {
    if (!activeAccountId) {
      setKpis(null);
      setNewestProducts([]);
      setLoading(false);
      setError(null);
      return;
    }

    setLoading(true);
    setError(null);

    getOverviewKPIs(activeAccountId)
      .then((data) => {
        setKpis(data);
        setNewestProducts(data.newestProducts || []);
      })
      .catch((e) => {
        console.error("Fehler beim Laden der KPIs:", e);
        setError(e.message || "Fehler beim Laden der Daten");
      })
      .finally(() => {
        setLoading(false);
      });
  }, [activeAccountId]);

  return (
    <section
      id="s1"
      className="flex min-h-screen w-auto flex-col gap-[18px] rounded-2xl px-4 py-4"
      style={{ 
        scrollSnapAlign: "start", 
        scrollSnapStop: "normal", 
        color: "var(--text)",
        background: "transparent"
      }}
    >
      <div className="flex items-center justify-between gap-4">
        <div className="flex items-baseline gap-2.5">
          <h1 className="m-0 text-lg font-medium tracking-wide text-[var(--text)]">Dashboard</h1>
          {loading && (
            <span className="rounded-full border border-[var(--line)] bg-white/3 px-2.5 py-1.5 text-xs text-[var(--muted)]">
              loading...
            </span>
          )}
        </div>
        <div className="flex flex-wrap items-center justify-end gap-2.5">
          <button
            onClick={() => onJumpToSection("s2")}
            className="rounded-xl border border-[var(--line)] bg-white/3 px-3 py-2.5 text-xs text-[var(--text)] transition-all hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)] active:translate-y-[1px]"
          >
            Go to Accounts
          </button>
          <button
            onClick={() => onJumpToSection("s3")}
            className="rounded-xl border border-[var(--line)] bg-white/3 px-3 py-2.5 text-xs text-[var(--text)] transition-all hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)] active:translate-y-[1px]"
          >
            Go to Products
          </button>
          <button
            onClick={() => onJumpToSection("s4")}
            className={cn(
              "rounded-xl border border-[rgba(106,166,255,0.7)] bg-[rgba(106,166,255,0.12)] px-3 py-2.5 text-xs text-[var(--text)] transition-all hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)] active:translate-y-[1px]"
            )}
          >
            Go to Insights
          </button>
        </div>
      </div>

      <div className="flex items-end justify-between gap-4">
        <div>
          <h2 className="m-0 text-xl tracking-wide text-[var(--text)]">Overview</h2>
          <p className="mt-1.5 mb-0 text-xs text-[var(--muted)]">
            System health and high-level metrics.
          </p>
        </div>
      </div>

      {error && (
        <div className="rounded-xl border border-red-500/30 bg-red-500/10 p-4 text-sm text-red-400">
          Fehler: {error}
        </div>
      )}

      {!activeAccountId && !loading && (
        <div className="rounded-xl border border-[var(--line)] bg-white/3 p-8 text-center">
          <p className="text-sm text-[var(--muted)]">No account selected</p>
        </div>
      )}

      {activeAccountId && loading && (
        <div className="grid grid-cols-6 gap-3.5 max-[1100px]:grid-cols-3">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <div key={i} className="h-24 animate-pulse rounded-[18px] border border-[var(--line)] bg-white/2" />
          ))}
        </div>
      )}

      {activeAccountId && !loading && !error && kpis && (
        <>
          <div className="grid grid-cols-6 gap-3.5 max-[1100px]:grid-cols-3">
            <KPICard
              title="Products (total)"
              value={kpis.totalProducts}
              sub={`Active: ${kpis.activeProducts} | Ended: ${kpis.endedProducts}`}
            />
            <KPICard
              title="Active Products"
              value={kpis.activeProducts}
              sub="Currently active"
            />
            <KPICard
              title="Ended Products"
              value={kpis.endedProducts}
              sub="No longer active"
            />
            <KPICard
              title="Avg price"
              value={kpis.avgPrice ? `EUR ${kpis.avgPrice.toFixed(2)}` : "N/A"}
              sub="Across active products"
            />
            <KPICard
              title="Newest"
              value={newestProducts.length}
              sub="Latest products"
            />
            <KPICard
              title="Status"
              value={kpis.totalProducts > 0 ? "Active" : "Empty"}
              sub={kpis.totalProducts > 0 ? "Account has products" : "No products yet"}
            />
          </div>
        </>
      )}

      {activeAccountId && !loading && !error && kpis && kpis.totalProducts === 0 && (
        <div className="rounded-xl border border-[var(--line)] bg-white/3 p-8 text-center">
          <p className="text-sm text-[var(--muted)]">No products yet for this account.</p>
        </div>
      )}

      <div className="grid grid-cols-2 gap-3.5 max-[1100px]:grid-cols-1">
        <div className="relative overflow-hidden rounded-[18px] border border-[var(--line)] bg-gradient-to-b from-white/4 to-white/2 p-4 shadow-[0_10px_30px_rgba(0,0,0,0.35)]">
          <div
            className="pointer-events-none absolute inset-[-1px] opacity-55"
            style={{
              background: "radial-gradient(600px 280px at 20% 0%, rgba(106,166,255,0.14), transparent 60%)",
            }}
          />
          <div className="relative">
            <p className="mb-2 text-xs text-[var(--muted)]">Product overview</p>
            <div className="mb-3 text-xs text-[var(--muted)]">
              {loading ? "Loading..." : kpis ? `${kpis.totalProducts} total products` : "No data"}
            </div>
            <div className="flex items-center justify-between border-t border-[var(--line)] pt-3">
              <button
                onClick={() => onJumpToSection("s3")}
                className="rounded-xl border border-[var(--line)] bg-white/3 px-3 py-2 text-xs text-[var(--text)] transition-all hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)] active:translate-y-[1px]"
              >
                Explore products
              </button>
            </div>
          </div>
        </div>

        <div className="relative overflow-hidden rounded-[18px] border border-[var(--line)] bg-gradient-to-b from-white/4 to-white/2 p-4 shadow-[0_10px_30px_rgba(0,0,0,0.35)]">
          <div
            className="pointer-events-none absolute inset-[-1px] opacity-55"
            style={{
              background: "radial-gradient(600px 280px at 20% 0%, rgba(106,166,255,0.14), transparent 60%)",
            }}
          />
          <div className="relative">
            <p className="mb-2 text-xs text-[var(--muted)]">Newest items</p>
            {loading ? (
              <div className="mb-3 text-xs text-[var(--muted)]">Loading...</div>
            ) : newestProducts.length > 0 ? (
              <div className="mb-3 text-xs text-[var(--muted)] whitespace-pre-line">
                {newestProducts.map((p) => `- ${p.product_title || p.$id}${p.product_price ? ` EUR ${p.product_price}` : ""}`).join("\n")}
              </div>
            ) : (
              <div className="mb-3 text-xs text-[var(--muted)]">No products yet</div>
            )}
            <div className="flex items-center justify-between border-t border-[var(--line)] pt-3">
              <button
                onClick={() => onJumpToSection("s3")}
                className="rounded-xl border border-[var(--line)] bg-white/3 px-3 py-2 text-xs text-[var(--text)] transition-all hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)] active:translate-y-[1px]"
              >
                View products
              </button>
              <div className="text-xs text-[var(--muted)]">Top 5</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};
