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

export const InsightsSection = ({ onJumpToSection, onFilterProducts, activeAccountId }) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [insights, setInsights] = useState(null);

  // Lade Insights wenn activeAccountId sich ändert
  useEffect(() => {
    if (!activeAccountId) {
      setInsights(null);
      setLoading(false);
      setError(null);
      return;
    }

    setLoading(true);
    setError(null);

    getInsights(activeAccountId)
      .then((data) => {
        setInsights(data);
      })
      .catch((e) => {
        console.error("Fehler beim Laden der Insights:", e);
        setError(e.message || "Fehler beim Laden der Daten");
      })
      .finally(() => {
        setLoading(false);
      });
  }, [activeAccountId]);


  return (
    <section
      id="s4"
      className="flex min-h-screen w-auto flex-col gap-[18px] rounded-2xl px-4 py-4"
      style={{ 
        color: "var(--text)",
        scrollSnapAlign: "start",
        scrollSnapStop: "normal"
      }}
    >
      <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)]">Insights</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("s1")}
            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]"
          >
            Overview
          </button>
          <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]"
          >
            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]"
          >
            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]"
            )}
          >
            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)]">Winning / Intelligence</h2>
          <p className="mt-1.5 mb-0 text-xs text-[var(--muted)]">
            Preset insights that jump back into Products.
          </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>
      )}

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

      {activeAccountId && !loading && !error && insights && (
        <>
          <div className="grid grid-cols-2 gap-3.5 max-[1100px]:grid-cols-1">
            <InsightCard
              title="Trending products"
              value={`${insights.trending.length}`}
              subtitle={`Recent products (last ${insights.trending.length})`}
              items={insights.trending.slice(0, 5).map((item) => ({
                label: item.label,
                value: item.value,
              }))}
              actionButton={{
                element: (
                  <button
                    onClick={() => {
                      if (onFilterProducts) {
                        onFilterProducts({});
                      }
                      onJumpToSection("s3");
                    }}
                    className={cn(
                      "rounded-xl border border-[rgba(106,166,255,0.7)] bg-[rgba(106,166,255,0.12)] 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]"
                    )}
                  >
                    Open in Products
                  </button>
                ),
                info: "View all",
              }}
            />

            <InsightCard
              title="High price spread"
              value={insights.priceSpread.length > 0 ? `${insights.priceSpread.length} groups` : "0"}
              subtitle="Price variations for similar items"
              items={insights.priceSpread.slice(0, 5).map((item) => ({
                label: item.label,
                value: item.value,
              }))}
              actionButton={{
                element: (
                  <button
                    onClick={() => {
                      if (onFilterProducts) {
                        onFilterProducts({ search: insights.priceSpread[0]?.title });
                      }
                      onJumpToSection("s3");
                    }}
                    disabled={insights.priceSpread.length === 0}
                    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] disabled:cursor-not-allowed disabled:opacity-45"
                  >
                    Open Products
                  </button>
                ),
                info: insights.priceSpread.length > 0 ? "Top spread" : "No data",
              }}
            />
          </div>

          <div className="grid grid-cols-2 gap-3.5 max-[1100px]:grid-cols-1">
            <InsightCard
              title="Category share"
              value={`${insights.categoryShare.length} categories`}
              subtitle="Top categories by product count"
              items={insights.categoryShare.map((item) => ({
                label: item.label,
                value: item.value,
              }))}
              actionButton={{
                element: (
                  <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>
                ),
                info: "Top 5",
              }}
            />

            <InsightCard
              title="Active products"
              value={insights.trending.filter((t) => t.product?.product_status === "active").length}
              subtitle="Currently active from recent products"
              items={insights.trending
                .filter((t) => t.product?.product_status === "active")
                .slice(0, 5)
                .map((item) => ({
                  label: item.label,
                  value: item.value,
                }))}
              actionButton={{
                element: (
                  <button
                    onClick={() => {
                      if (onFilterProducts) {
                        onFilterProducts({ status: "active" });
                      }
                      onJumpToSection("s3");
                    }}
                    className={cn(
                      "rounded-xl border border-[rgba(106,166,255,0.7)] bg-[rgba(106,166,255,0.12)] 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]"
                    )}
                  >
                    Open Active
                  </button>
                ),
                info: "Filter: active",
              }}
            />
          </div>
        </>
      )}

      {activeAccountId && !loading && !error && insights && 
        insights.trending.length === 0 && 
        insights.priceSpread.length === 0 && 
        insights.categoryShare.length === 0 && (
        <div className="rounded-xl border border-[var(--line)] bg-white/3 p-8 text-center">
          <p className="text-sm text-[var(--muted)]">No insights available yet</p>
        </div>
      )}
    </section>
  );
};
