import { useMemo } from "react";
import { Link, useParams } from "react-router-dom";

import {
  Card,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { useGroups } from "@/context/GroupsContext";
import { useCompartmentsByGroup } from "@/hooks/useCompartmentsByGroup";

export function GroupPage() {
  const { groupId: groupIdParam } = useParams();
  const { groups } = useGroups();

  const groupId = useMemo(() => {
    if (!groupIdParam) return "";
    return decodeURIComponent(groupIdParam);
  }, [groupIdParam]);

  const groupTitle = useMemo(() => {
    if (!groupId) return "Group";
    const match = groups.find((g) => g.groupId === groupId);
    return match?.displayName ?? groupId;
  }, [groupId, groups]);

  const { compartments, status, error } = useCompartmentsByGroup(groupId);

  return (
    <div className="mx-auto max-w-md px-4 pt-6">
      <h1 className="text-2xl font-semibold tracking-tight">{groupTitle}</h1>
      <p className="mt-2 text-sm text-muted-foreground">Compartments</p>

      {status === "loading" ? (
        <p className="mt-4 text-sm text-muted-foreground">Loading compartments…</p>
      ) : null}

      {status === "error" ? (
        <p className="mt-4 text-sm text-destructive">{error}</p>
      ) : null}

      <div className="mt-6 grid grid-cols-2 gap-3">
        {compartments.map((c) => (
          <Link
            key={c.id}
            to={`/groups/${encodeURIComponent(groupId)}/compartments/${encodeURIComponent(c.id)}`}
            className="min-w-0"
          >
            <Card className="h-full transition-colors hover:bg-muted/40">
              <CardHeader className="p-0">
                <CardTitle className="line-clamp-2">{c.displayName}</CardTitle>
                <CardDescription className="truncate">{c.id}</CardDescription>
              </CardHeader>
            </Card>
          </Link>
        ))}
      </div>

      {status !== "loading" && groupId && compartments.length === 0 ? (
        <p className="mt-4 text-sm text-muted-foreground">No compartments found.</p>
      ) : null}
    </div>
  );
}
