"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import type { CSSProperties } from "react";
import {
  Building2,
  Briefcase,
  Eye,
  EyeOff,
  Plus,
  Trash2,
  User,
  Wallet,
  X,
} from "lucide-react";
import { cn } from "@/lib/utils";

const STORAGE_KEY = "mindavio-finance-accounts";

export interface FinanceAccount {
  id: string;
  name: string;
  color: string;
  icon: string;
  categories: string[];
  active: boolean;
}

const ICON_MAP: Record<string, React.ComponentType<{ className?: string; style?: CSSProperties }>> = {
  user: User,
  building: Building2,
  briefcase: Briefcase,
  wallet: Wallet,
};

const DEFAULT_ACCOUNTS: FinanceAccount[] = [
  {
    id: "personal",
    name: "Persönlich",
    color: "#6366f1",
    icon: "user",
    categories: [
      "Gehalt",
      "Nebeneinkommen",
      "Lebensmittel",
      "Essen gehen",
      "Abonnements",
      "Transport",
      "Shopping",
      "Sport & Fitness",
      "Gesundheit",
      "Versicherung",
      "Bildung",
      "Reise",
      "Freizeit",
      "Sparen",
      "Geschenk",
      "Sonstiges",
    ],
    active: true,
  },
  {
    id: "immobilien",
    name: "Immobilien",
    color: "#10b981",
    icon: "building",
    categories: ["Mieteinnahmen", "Miete", "Nebenkosten", "Instandhaltung", "Hausverwaltung"],
    active: true,
  },
  {
    id: "business",
    name: "Business",
    color: "#f59e0b",
    icon: "briefcase",
    categories: ["Freelance", "Business", "Investments"],
    active: true,
  },
];

function generateId() {
  return Math.random().toString(36).slice(2, 10);
}

function loadAccounts(): FinanceAccount[] {
  if (typeof window === "undefined") return DEFAULT_ACCOUNTS;
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) return JSON.parse(raw) as FinanceAccount[];
  } catch {
    // ignore
  }
  return DEFAULT_ACCOUNTS;
}

function saveAccounts(accounts: FinanceAccount[]) {
  if (typeof window === "undefined") return;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(accounts));
}

function formatMoney(cents: number) {
  return new Intl.NumberFormat("de-DE", {
    style: "currency",
    currency: "EUR",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(cents / 100);
}

interface AccountFilterProps {
  /** All unique categories found in transactions + recurring */
  allCategories: string[];
  /** Called whenever active filter changes. Passes null = show all, or Set of active categories */
  onFilterChange: (activeCategories: Set<string> | null) => void;
  /** Summary per category for showing amounts on account cards: Map<category, { income, expenses }> */
  categorySummary: Map<string, { income: number; expenses: number }>;
}

export function AccountFilter({
  allCategories,
  onFilterChange,
  categorySummary,
}: AccountFilterProps) {
  const [accounts, setAccounts] = useState<FinanceAccount[]>(loadAccounts);
  const [editing, setEditing] = useState(false);
  const [newName, setNewName] = useState("");
  const [newColor, setNewColor] = useState("#8b5cf6");
  const [newCategories, setNewCategories] = useState<string[]>([]);

  const COLORS = ["#6366f1", "#10b981", "#f59e0b", "#ef4444", "#ec4899", "#8b5cf6", "#06b6d4", "#3b82f6"];

  // Persist
  useEffect(() => {
    saveAccounts(accounts);
  }, [accounts]);

  // Emit filter
  useEffect(() => {
    const allActive = accounts.every((a) => a.active);
    if (allActive) {
      onFilterChange(null);
    } else {
      const cats = new Set<string>();
      accounts.filter((a) => a.active).forEach((a) => a.categories.forEach((c) => cats.add(c)));
      onFilterChange(cats);
    }
  }, [accounts, onFilterChange]);

  const toggle = useCallback((id: string) => {
    setAccounts((prev) => prev.map((a) => (a.id === id ? { ...a, active: !a.active } : a)));
  }, []);

  const removeAccount = useCallback((id: string) => {
    setAccounts((prev) => prev.filter((a) => a.id !== id));
  }, []);

  const addAccount = useCallback(() => {
    if (!newName.trim()) return;
    setAccounts((prev) => [
      ...prev,
      {
        id: generateId(),
        name: newName.trim(),
        color: newColor,
        icon: "wallet",
        categories: newCategories,
        active: true,
      },
    ]);
    setNewName("");
    setNewCategories([]);
    setEditing(false);
  }, [newName, newColor, newCategories]);

  // Find categories that aren't assigned to any account
  const unassigned = useMemo(() => {
    const assigned = new Set(accounts.flatMap((a) => a.categories));
    return allCategories.filter((c) => !assigned.has(c));
  }, [accounts, allCategories]);

  // Calculate totals per account
  const accountTotals = useMemo(() => {
    const map = new Map<string, { income: number; expenses: number; net: number }>();
    for (const acc of accounts) {
      let income = 0;
      let expenses = 0;
      for (const cat of acc.categories) {
        const s = categorySummary.get(cat);
        if (s) {
          income += s.income;
          expenses += s.expenses;
        }
      }
      map.set(acc.id, { income, expenses, net: income - expenses });
    }
    return map;
  }, [accounts, categorySummary]);

  const allActive = accounts.every((a) => a.active);
  const noneActive = accounts.every((a) => !a.active);

  return (
    <div className="rounded-2xl border border-border/60 bg-card p-5">
      <div className="flex flex-wrap items-center justify-between gap-3 mb-4">
        <div className="flex items-center gap-2.5">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-gradient-to-br from-indigo-500 to-blue-600">
            <Wallet className="h-4 w-4 text-white" />
          </div>
          <div>
            <h2 className="text-sm font-semibold">Konten</h2>
            <p className="text-xs text-muted-foreground">
              {allActive ? "Alle Konten aktiv" : noneActive ? "Keine Konten aktiv" : `${accounts.filter((a) => a.active).length} von ${accounts.length} aktiv`}
              {" · "}Klicke zum Ein-/Ausblenden
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {!allActive && (
            <button
              onClick={() => setAccounts((prev) => prev.map((a) => ({ ...a, active: true })))}
              className="text-xs text-muted-foreground hover:text-foreground transition-colors"
            >
              Alle einblenden
            </button>
          )}
          <button
            onClick={() => setEditing(!editing)}
            className={cn(
              "flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-all border",
              editing
                ? "border-foreground/20 bg-foreground/5 text-foreground"
                : "border-border/60 text-muted-foreground hover:text-foreground hover:border-border"
            )}
          >
            {editing ? <X className="h-3 w-3" /> : <Plus className="h-3 w-3" />}
            {editing ? "Fertig" : "Konto"}
          </button>
        </div>
      </div>

      {/* Account cards */}
      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {accounts.map((acc) => {
          const Icon = ICON_MAP[acc.icon] || Wallet;
          const totals = accountTotals.get(acc.id);
          return (
            <div
              key={acc.id}
              onClick={() => toggle(acc.id)}
              className={cn(
                "group relative cursor-pointer rounded-xl border p-4 transition-all",
                acc.active
                  ? "border-border bg-background/80 hover:shadow-md"
                  : "border-border/30 bg-background/30 opacity-50 hover:opacity-75"
              )}
            >
              {/* Color accent */}
              <div
                className="absolute top-0 left-0 w-1 h-full rounded-l-xl transition-opacity"
                style={{ backgroundColor: acc.color, opacity: acc.active ? 1 : 0.3 }}
              />

              <div className="flex items-start justify-between gap-2 pl-2">
                <div className="flex items-center gap-2.5">
                  <div
                    className="flex h-8 w-8 items-center justify-center rounded-lg transition-colors"
                    style={{
                      backgroundColor: `${acc.color}15`,
                    }}
                  >
                    <Icon className="h-4 w-4" style={{ color: acc.color }} />
                  </div>
                  <div>
                    <p className="text-sm font-semibold">{acc.name}</p>
                    <p className="text-[10px] text-muted-foreground">
                      {acc.categories.length} Kategorien
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-1">
                  {acc.active ? (
                    <Eye className="h-3.5 w-3.5 text-muted-foreground" />
                  ) : (
                    <EyeOff className="h-3.5 w-3.5 text-muted-foreground" />
                  )}
                  {editing && (
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        removeAccount(acc.id);
                      }}
                      className="rounded-lg p-1 text-muted-foreground hover:text-destructive hover:bg-accent transition-colors"
                    >
                      <Trash2 className="h-3 w-3" />
                    </button>
                  )}
                </div>
              </div>

              {/* Totals */}
              {totals && (totals.income > 0 || totals.expenses > 0) && (
                <div className="flex items-center gap-4 mt-3 pl-2">
                  {totals.income > 0 && (
                    <span className="text-xs font-medium text-emerald-500">
                      +{formatMoney(totals.income)}
                    </span>
                  )}
                  {totals.expenses > 0 && (
                    <span className="text-xs font-medium text-rose-500">
                      -{formatMoney(totals.expenses)}
                    </span>
                  )}
                  <span
                    className={cn(
                      "text-xs font-bold",
                      totals.net >= 0 ? "text-emerald-500" : "text-rose-500"
                    )}
                  >
                    = {formatMoney(totals.net)}
                  </span>
                </div>
              )}

              {/* Categories pills (in edit mode) */}
              {editing && (
                <div className="flex flex-wrap gap-1 mt-2 pl-2">
                  {acc.categories.slice(0, 5).map((c) => (
                    <span
                      key={c}
                      className="rounded-md bg-muted px-1.5 py-0.5 text-[9px] text-muted-foreground"
                    >
                      {c}
                    </span>
                  ))}
                  {acc.categories.length > 5 && (
                    <span className="rounded-md bg-muted px-1.5 py-0.5 text-[9px] text-muted-foreground">
                      +{acc.categories.length - 5}
                    </span>
                  )}
                </div>
              )}
            </div>
          );
        })}

        {/* Unassigned categories card */}
        {unassigned.length > 0 && (
          <div
            onClick={() => {
              // Show all when clicking unassigned — they're always visible
            }}
            className="rounded-xl border border-dashed border-border/60 p-4 opacity-60"
          >
            <div className="flex items-center gap-2.5 pl-2">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-muted">
                <Wallet className="h-4 w-4 text-muted-foreground" />
              </div>
              <div>
                <p className="text-sm font-medium text-muted-foreground">Nicht zugeordnet</p>
                <p className="text-[10px] text-muted-foreground">{unassigned.length} Kategorien</p>
              </div>
            </div>
            {editing && (
              <div className="flex flex-wrap gap-1 mt-2 pl-2">
                {unassigned.slice(0, 5).map((c) => (
                  <span key={c} className="rounded-md bg-muted px-1.5 py-0.5 text-[9px] text-muted-foreground">{c}</span>
                ))}
                {unassigned.length > 5 && (
                  <span className="rounded-md bg-muted px-1.5 py-0.5 text-[9px] text-muted-foreground">+{unassigned.length - 5}</span>
                )}
              </div>
            )}
          </div>
        )}
      </div>

      {/* Add account form */}
      {editing && (
        <div className="mt-4 rounded-xl border border-border/60 bg-background/60 p-4 space-y-3">
          <p className="text-xs font-semibold">Neues Konto erstellen</p>
          <div className="grid gap-3 sm:grid-cols-[1fr,auto]">
            <input
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
              placeholder="z.B. Krypto, Nebengewerbe, Partner..."
              className="h-9 w-full rounded-lg border border-input bg-background px-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"
            />
            <div className="flex items-center gap-1.5">
              {COLORS.map((c) => (
                <button
                  key={c}
                  onClick={() => setNewColor(c)}
                  className={cn(
                    "h-6 w-6 rounded-full border-2 transition-all",
                    newColor === c ? "border-foreground scale-110" : "border-transparent"
                  )}
                  style={{ backgroundColor: c }}
                />
              ))}
            </div>
          </div>

          {/* Category selection */}
          <div>
            <p className="text-xs text-muted-foreground mb-2">Kategorien zuordnen</p>
            <div className="flex flex-wrap gap-1.5">
              {allCategories.map((cat) => {
                const selected = newCategories.includes(cat);
                return (
                  <button
                    key={cat}
                    onClick={() =>
                      setNewCategories((prev) =>
                        selected ? prev.filter((c) => c !== cat) : [...prev, cat]
                      )
                    }
                    className={cn(
                      "rounded-lg px-2.5 py-1 text-xs font-medium border transition-all",
                      selected
                        ? "border-foreground/20 bg-foreground/5 text-foreground"
                        : "border-border/40 text-muted-foreground hover:text-foreground hover:border-border"
                    )}
                  >
                    {cat}
                  </button>
                );
              })}
            </div>
          </div>

          <div className="flex justify-end">
            <button
              onClick={addAccount}
              disabled={!newName.trim()}
              className="flex items-center gap-1.5 rounded-lg bg-foreground px-4 py-2 text-xs font-medium text-background transition-all hover:opacity-90 disabled:opacity-40"
            >
              <Plus className="h-3 w-3" />
              Konto erstellen
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
