import React, { useState, useEffect } from "react";
import { OverviewSection } from "./sections/OverviewSection";
import { AccountsSection } from "./sections/AccountsSection";
import { ProductsSection } from "./sections/ProductsSection";
import { InsightsSection } from "./sections/InsightsSection";
import { useScrollSnap } from "./hooks/useScrollSnap";
import { getAuthUser } from "../../lib/appwrite";
import { fetchManagedAccounts } from "../../services/accountsService";
import { resolveActiveAccount } from "../../services/accountService";
import { useHashRoute } from "../../lib/routing";

export const Dashboard = () => {
  const { navigate } = useHashRoute();
  const [productFilters, setProductFilters] = useState({});
  const [activeAccountId, setActiveAccountId] = useState(null);
  const [hasAccounts, setHasAccounts] = useState(false);
  const [loadingAccounts, setLoadingAccounts] = useState(true);

  const sectionIds = ["s1", "s2", "s3", "s4"];
  const { scrollToSection } = useScrollSnap(sectionIds);

  // Accounts laden und aktiven Account auflösen beim Mount und nach Updates
  useEffect(() => {
    async function loadAccountsAndResolveActive() {
      setLoadingAccounts(true);
      try {
        const authUser = await getAuthUser();
        if (!authUser) {
          setHasAccounts(false);
          setActiveAccountId(null);
          return;
        }

        const accounts = await fetchManagedAccounts(authUser.$id);
        setHasAccounts(accounts.length > 0);

        const activeAccount = resolveActiveAccount(accounts);
        if (activeAccount) {
          const accountId = activeAccount.$id || activeAccount.id;
          setActiveAccountId(accountId);
        } else {
          setActiveAccountId(null);
        }
      } catch (e) {
        console.error("Fehler beim Laden der Accounts:", e);
        setHasAccounts(false);
        setActiveAccountId(null);
      } finally {
        setLoadingAccounts(false);
      }
    }

    loadAccountsAndResolveActive();
    
    // Listen for accounts update events (e.g., after onboarding)
    const handleAccountsUpdated = () => {
      loadAccountsAndResolveActive();
    };
    
    window.addEventListener('accountsUpdated', handleAccountsUpdated);
    
    return () => {
      window.removeEventListener('accountsUpdated', handleAccountsUpdated);
    };
  }, []);

  // Event-Listener für Account-Wechsel
  useEffect(() => {
    function handleActiveAccountChanged(event) {
      const { accountId } = event.detail;
      setActiveAccountId(accountId);
      // Dashboard-Daten würden hier neu geladen werden (später, wenn Products-Service existiert)
    }

    window.addEventListener("activeAccountChanged", handleActiveAccountChanged);
    return () => {
      window.removeEventListener("activeAccountChanged", handleActiveAccountChanged);
    };
  }, []);

  const handleJumpToSection = (sectionId) => {
    scrollToSection(sectionId);
  };

  const handleFilterProducts = (filters) => {
    setProductFilters(filters);
  };

  // Empty-State wenn kein Account vorhanden
  if (!loadingAccounts && !hasAccounts) {
    return (
      <div className="flex flex-1">
        <div className="flex h-full w-full flex-1 flex-col gap-4 rounded-2xl border border-neutral-200 bg-white p-4 dark:border-neutral-700 dark:bg-neutral-900">
          <div className="flex flex-col items-center justify-center py-20 text-center">
            <h2 className="mb-2 text-xl font-semibold text-[var(--text)]">
              No account connected
            </h2>
            <p className="mb-6 text-sm text-[var(--muted)]">
              Du musst zuerst einen Account hinzufügen, um das Dashboard zu nutzen.
            </p>
            <button
              onClick={() => navigate("/accounts")}
              className="rounded-xl border border-[var(--line)] bg-white/3 px-4 py-2.5 text-sm font-medium 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]"
            >
              Add Account
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-1">
      <div className="flex h-full w-full flex-1 flex-col gap-2 rounded-2xl border border-neutral-200 bg-white p-2 md:p-4 dark:border-neutral-700 dark:bg-neutral-900">
        <div
          className="h-full w-full overflow-y-scroll hide-scrollbar"
          style={{
            scrollSnapType: "y mandatory",
            scrollBehavior: "smooth",
          }}
        >
          <div className="min-h-screen">
            <OverviewSection
              onJumpToSection={handleJumpToSection}
              activeAccountId={activeAccountId}
            />
            <AccountsSection
              onJumpToSection={handleJumpToSection}
              activeAccountId={activeAccountId}
            />
            <ProductsSection
              onJumpToSection={handleJumpToSection}
              activeAccountId={activeAccountId}
            />
            <InsightsSection
              onJumpToSection={handleJumpToSection}
              onFilterProducts={handleFilterProducts}
              activeAccountId={activeAccountId}
            />
          </div>
        </div>
      </div>
    </div>
  );
};
