import React, { useState, useEffect, useMemo } from "react";
import { DataTable } from "../ui/DataTable";
import { Pagination } from "../ui/Pagination";
import { Filters } from "../ui/Filters";
import { usePagination } from "../hooks/usePagination";
import { cn } from "../../../lib/utils";
import { fetchManagedAccounts } from "../../../services/accountsService";
import { getActiveAccountId, setActiveAccountId, getAccountDisplayName } from "../../../services/accountService";
import { getAuthUser } from "../../../lib/appwrite";

export const AccountsSection = ({ onJumpToSection, activeAccountId }) => {
  const [platformFilter, setPlatformFilter] = useState("all");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [accounts, setAccounts] = useState([]);

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

        const loadedAccounts = await fetchManagedAccounts(authUser.$id);
        setAccounts(loadedAccounts);
      } catch (e) {
        console.error("Fehler beim Laden der Accounts:", e);
        setError(e.message || "Fehler beim Laden der Accounts");
      } finally {
        setLoading(false);
      }
    }

    loadAccounts();
  }, []);

  const filteredAccounts = useMemo(() => {
    return accounts.filter((a) => {
      if (platformFilter !== "all" && a.account_platform !== platformFilter) return false;
      return true;
    });
  }, [accounts, platformFilter]);

  const { currentPage, totalPages, currentPageItems, nextPage, prevPage, resetPage } =
    usePagination(filteredAccounts, 8);

  const filters = [
    {
      id: "platform",
      type: "select",
      value: platformFilter,
      options: [
        { value: "all", label: "Platform: all" },
        { value: "amazon", label: "Platform: amazon" },
        { value: "ebay", label: "Platform: ebay" },
      ],
    },
  ];

  const handleFilterChange = (id, value) => {
    if (id === "platform") {
      setPlatformFilter(value);
    }
    resetPage();
  };

  const handleQuickSwitch = (accountId) => {
    setActiveAccountId(accountId);
    // Event wird automatisch durch setActiveAccountId getriggert
  };

  const currentActiveId = getActiveAccountId();

  return (
    <section
      id="s2"
      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)" }}
    >
      <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)]">Accounts</h1>
          <span className="rounded-full border border-[var(--line)] bg-white/3 px-2.5 py-1.5 text-xs text-[var(--muted)]">
            snap page
          </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={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]"
            )}
          >
            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="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]"
          >
            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)]">Accounts</h2>
          <p className="mt-1.5 mb-0 text-xs text-[var(--muted)]">
            Managed vs scanned accounts, with quick drill-down.
          </p>
        </div>
        <Filters filters={filters} onChange={handleFilterChange} />
      {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="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">
            <div className="mb-4 px-0 pb-0 pt-0">
              <p className="mb-2 text-xs text-[var(--muted)]">Managed accounts</p>
            </div>
            <div className="px-0 pb-4 pt-0">
              {loading ? (
                <div className="py-8 text-center text-xs text-[var(--muted)]">Loading...</div>
              ) : error ? (
                <div className="py-8 text-center text-xs text-red-400">{error}</div>
              ) : accounts.length === 0 ? (
                <div className="py-8 text-center text-xs text-[var(--muted)]">No accounts yet</div>
              ) : (
                <>
                  <DataTable
                    columns={["Shop", "Platform", "Market", "Action"]}
                    data={currentPageItems}
                    renderCell={(col, row) => {
                      if (col === "Action") {
                        const accountId = row.$id || row.id;
                        const isActive = accountId === currentActiveId;
                        return (
                          <button
                            onClick={() => handleQuickSwitch(accountId)}
                            className={cn(
                              "rounded-xl border px-3 py-2 text-xs text-[var(--text)] transition-all active:translate-y-[1px]",
                              isActive
                                ? "border-[rgba(106,166,255,0.7)] bg-[rgba(106,166,255,0.12)] hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)]"
                                : "border-[var(--line)] bg-white/3 hover:border-[rgba(106,166,255,0.55)] hover:bg-[rgba(106,166,255,0.08)]"
                            )}
                          >
                            {isActive ? "Active" : "Switch"}
                          </button>
                        );
                      }
                      if (col === "Shop") {
                        return getAccountDisplayName(row);
                      }
                      if (col === "Platform") {
                        return row.account_platform || "-";
                      }
                      if (col === "Market") {
                        return row.account_platform_market || "-";
                      }
                      return row[col.toLowerCase()] || "-";
                    }}
                  />
                  <Pagination
                    currentPage={currentPage}
                    totalPages={totalPages}
                    onPrev={prevPage}
                    onNext={nextPage}
                    info={`Page ${currentPage} / ${totalPages} - ${filteredAccounts.length} accounts`}
                  />
                </>
              )}
            </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)]">Account management</p>
            <div className="mb-4 text-xs text-[var(--muted)]">
              {currentActiveId
                ? `Active account: ${getAccountDisplayName(accounts.find((a) => (a.$id || a.id) === currentActiveId)) || currentActiveId}`
                : "No account selected. Use 'Switch' to activate an account."}
            </div>
            <div className="flex items-center justify-between border-t border-[var(--line)] pt-3">
              <button
                onClick={() => onJumpToSection("s3")}
                className="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]"
              >
                View Products
              </button>
              <div className="text-xs text-[var(--muted)]">{filteredAccounts.length} accounts</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};
