"use client";
import React, { useState, useEffect, useRef } from "react";
import { IconChevronDown } from "@tabler/icons-react";
import { motion, AnimatePresence } from "motion/react";
import { cn } from "../../lib/utils";
import { useHashRoute } from "../../lib/routing";
import {
  getActiveAccountId,
  setActiveAccountId,
  resolveActiveAccount,
  getAccountDisplayName,
} from "../../services/accountService";
import { fetchManagedAccounts } from "../../services/accountsService";
import { getAuthUser } from "../../lib/appwrite";

export const SidebarHeader = () => {
  const { navigate } = useHashRoute();
  const [accounts, setAccounts] = useState([]);
  const [activeAccount, setActiveAccount] = useState(null);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [loading, setLoading] = useState(true);
  const dropdownRef = useRef(null);

  // Accounts laden
  useEffect(() => {
    async function loadAccounts() {
      setLoading(true);
      try {
        const authUser = await getAuthUser();
        if (!authUser) {
          setAccounts([]);
          setActiveAccount(null);
          return;
        }

        const loadedAccounts = await fetchManagedAccounts(authUser.$id);
        setAccounts(loadedAccounts);
        const active = resolveActiveAccount(loadedAccounts);
        setActiveAccount(active);
      } catch (e) {
        console.error("Fehler beim Laden der Accounts:", e);
        setAccounts([]);
        setActiveAccount(null);
      } finally {
        setLoading(false);
      }
    }

    loadAccounts();
  }, []);

  // Event-Listener für activeAccountChanged (wenn Account in anderer Komponente gewechselt wird)
  useEffect(() => {
    function handleActiveAccountChanged(event) {
      const { accountId } = event.detail;
      // Account aus aktueller Liste finden und als aktiv setzen
      const foundAccount = accounts.find(
        (acc) => acc.$id === accountId || acc.id === accountId
      );
      if (foundAccount) {
        setActiveAccount(foundAccount);
      }
    }

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

  // Click outside handler für Dropdown
  useEffect(() => {
    function handleClickOutside(event) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setDropdownOpen(false);
      }
    }

    if (dropdownOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      return () => {
        document.removeEventListener("mousedown", handleClickOutside);
      };
    }
  }, [dropdownOpen]);

  const handleHeaderClick = () => {
    if (accounts.length === 0) {
      // Keine Accounts: direkt zu /accounts navigieren
      navigate("/accounts");
    } else {
      // Accounts existieren: Dropdown öffnen/schließen
      setDropdownOpen(!dropdownOpen);
    }
  };

  const handleAccountSelect = (account) => {
    const accountId = account.$id || account.id;
    setActiveAccountId(accountId);
    setActiveAccount(account);
    setDropdownOpen(false);
  };

  const handleManageAccounts = () => {
    setDropdownOpen(false);
    navigate("/accounts");
  };

  const displayText =
    accounts.length === 0
      ? "Add Account"
      : activeAccount
      ? getAccountDisplayName(activeAccount)
      : "Add Account";

  return (
    <div className="relative mb-6" ref={dropdownRef}>
      <button
        onClick={handleHeaderClick}
        className={cn(
          "flex w-full items-center gap-3 rounded-xl bg-white/50 px-1.5 py-2.5 transition-all hover:bg-white/80 dark:bg-neutral-800/50 dark:hover:bg-neutral-800/80"
        )}
      >
        <img
          src="/assets/logos/logo-horizontal.png"
          alt="Logo"
          className="h-8 w-auto shrink-0 object-contain"
          style={{ maxWidth: '120px', marginLeft: '-4px' }}
        />
        <span className="flex-1 truncate text-left text-sm font-medium text-neutral-700 dark:text-neutral-200">
          {loading ? "Loading..." : displayText}
        </span>
        {accounts.length > 0 && (
          <IconChevronDown
            className={cn(
              "h-4 w-4 shrink-0 text-neutral-500 transition-transform dark:text-neutral-400",
              dropdownOpen && "rotate-180"
            )}
          />
        )}
      </button>

      <AnimatePresence>
        {dropdownOpen && accounts.length > 0 && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            transition={{ duration: 0.2 }}
            className="absolute left-0 right-0 top-full z-50 mt-2 overflow-hidden rounded-xl border border-neutral-200 bg-white shadow-lg dark:border-neutral-700 dark:bg-neutral-800"
          >
            <div className="max-h-64 overflow-y-auto">
              {accounts.map((account) => {
                const accountId = account.$id || account.id;
                const currentActiveId = getActiveAccountId();
                const isActive = accountId === currentActiveId;
                const displayName = getAccountDisplayName(account);

                return (
                  <button
                    key={accountId}
                    onClick={() => handleAccountSelect(account)}
                    className={cn(
                      "flex w-full items-center gap-3 px-3 py-2.5 text-left text-sm transition-colors hover:bg-neutral-100 dark:hover:bg-neutral-700",
                      isActive && "bg-blue-50 dark:bg-blue-900/20"
                    )}
                  >
                    <span
                      className={cn(
                        "flex-1 truncate",
                        isActive
                          ? "font-medium text-blue-600 dark:text-blue-400"
                          : "text-neutral-700 dark:text-neutral-200"
                      )}
                    >
                      {displayName}
                    </span>
                    {isActive && (
                      <span className="h-2 w-2 shrink-0 rounded-full bg-blue-600 dark:bg-blue-400" />
                    )}
                  </button>
                );
              })}

              <div className="border-t border-neutral-200 dark:border-neutral-700" />

              <button
                onClick={handleManageAccounts}
                className="flex w-full items-center gap-3 px-3 py-2.5 text-left text-sm font-medium text-neutral-700 transition-colors hover:bg-neutral-100 dark:text-neutral-200 dark:hover:bg-neutral-700"
              >
                Manage Accounts
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};