import { useState } from "react";
import { useQuery } from "convex/react";
import { api } from "../../convex/_generated/api";
import type { Doc } from "../../convex/_generated/dataModel";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { CategoryFormDialog } from "@/components/categories/CategoryFormDialog";

function CategorySection({
  title,
  categories,
  onEdit,
}: {
  title: string;
  categories: Doc<"categories">[];
  onEdit: (c: Doc<"categories">) => void;
}) {
  return (
    <Card>
      <CardHeader>
        <CardTitle>{title}</CardTitle>
      </CardHeader>
      <CardContent className="space-y-2">
        {categories.length === 0 && (
          <p className="text-sm text-muted-foreground">Keine Kategorien</p>
        )}
        {categories.map((cat) => (
          <div key={cat._id} className="flex items-center justify-between rounded-lg border p-3">
            <Badge style={{ backgroundColor: cat.color, color: "#fff", border: "none" }}>
              {cat.name}
            </Badge>
            <Button size="sm" variant="outline" onClick={() => onEdit(cat)}>
              Bearbeiten
            </Button>
          </div>
        ))}
      </CardContent>
    </Card>
  );
}

export function CategoriesPage() {
  const categories = useQuery(api.categories.list);
  const [edit, setEdit] = useState<Doc<"categories"> | null>(null);
  const [createOpen, setCreateOpen] = useState(false);

  const income = categories?.filter((c) => c.kind === "einnahme") ?? [];
  const fixed = categories?.filter((c) => c.kind === "ausgabe" && c.block === "wiederkehrend") ?? [];
  const variable = categories?.filter((c) => c.kind === "ausgabe" && c.block === "variabel") ?? [];

  return (
    <div className="space-y-4">
      <Button onClick={() => setCreateOpen(true)}>Neue Kategorie</Button>
      <div className="grid gap-4 lg:grid-cols-3">
        <CategorySection title="Einnahmen" categories={income} onEdit={setEdit} />
        <CategorySection title="Ausgaben – wiederkehrend" categories={fixed} onEdit={setEdit} />
        <CategorySection title="Ausgaben – variabel" categories={variable} onEdit={setEdit} />
      </div>
      <CategoryFormDialog open={createOpen} onOpenChange={setCreateOpen} />
      <CategoryFormDialog
        open={!!edit}
        onOpenChange={(o) => !o && setEdit(null)}
        category={edit ?? undefined}
      />
    </div>
  );
}
