import { useNavigate } from "react-router-dom";
import { Users } from "lucide-react";
import { Small } from "@/components/ui/typography";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { useNetworks } from "@/hooks/use-networks";
import { Progress } from "@/components/ui/progress";
import type { Network } from "@/api/types";

function NetworkRow({
  network,
  onClick,
}: {
  network: Network;
  onClick: () => void;
}) {
  const initials = network.name.slice(0, 2).toUpperCase();
  const memberCount = network.humans.length;

  return (
    <button
      type="button"
      onClick={onClick}
      className="flex w-full items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-accent"
    >
      <Avatar>
        <AvatarFallback className="bg-primary/10 text-primary font-medium">
          {initials}
        </AvatarFallback>
      </Avatar>
      <div className="min-w-0 flex-1">
        <p className="truncate text-sm font-medium">{network.name}</p>
        <div className="text-muted-foreground flex items-center gap-1">
          <Users className="size-3" />
          <Small className="text-muted-foreground">
            {memberCount} {memberCount === 1 ? "member" : "members"}
          </Small>
        </div>
      </div>
    </button>
  );
}

export default function NetworkSelector() {
  const navigate = useNavigate();

  const { data, isPending, error } = useNetworks();

  if (isPending) {
    return <Progress />;
  }

  if (error) {
    return (
      <div className="flex h-full items-center justify-center">
        <p className="text-destructive text-sm">Failed to load networks</p>
        <p>{error.message}</p>
      </div>
    );
  }

  if (data?.length === 0) {
    return (
      <div className="mx-auto flex h-full max-w-sm flex-col items-center justify-center gap-4 px-4 text-center">
        <p className="text-muted-foreground">
          You don't have access to any networks yet. Please email us to get
          started.
        </p>
        <a href="mailto:team@flowylabs.ai" className="text-primary underline">
          team@flowylabs.ai
        </a>
      </div>
    );
  }

  return (
    <ScrollArea className="h-full">
      <div className="py-1">
        {data?.map((network, index) => (
          <div key={network.id}>
            <NetworkRow
              network={network}
              onClick={() => navigate(`/${network.id}`)}
            />
            {index < data.length - 1 && <Separator className="mx-4" />}
          </div>
        ))}
      </div>
    </ScrollArea>
  );
}
