import { useNavigate } from "react-router-dom";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { useAppStore } from "@/stores/app-store";
import { flattenStreams } from "@/lib/stream-utils";
import { formatDistanceToNow } from "@/lib/time-utils";
import { ParticlePreview } from "./particle-preview";

function getInitials(email: string): string {
  const prefix = email.split("@")[0] ?? "";
  return prefix.slice(0, 2).toUpperCase();
}

export function StreamList() {
  const networks = useAppStore((s) => s.networks);
  const selectedNetworkId = useAppStore((s) => s.selectedNetworkId);
  const navigate = useNavigate();

  const streams = flattenStreams(networks, selectedNetworkId);

  if (streams.length === 0) {
    return (
      <div className="flex flex-1 items-center justify-center">
        <p className="text-muted-foreground text-sm">No streams yet</p>
      </div>
    );
  }

  return (
    <div className="grid grid-cols-2 gap-3 p-4">
      {streams.map((stream) => {
        const lastParticle =
          stream.particles.length > 0
            ? stream.particles[stream.particles.length - 1]
            : null;

        const timeSource = lastParticle?.created_at ?? stream.updated_at;
        const senderEmail = lastParticle?.created_by_email;
        const senderPrefix = senderEmail?.split("@")[0];

        return (
          <Card
            key={stream.id}
            size="sm"
            className="hover:bg-accent/50 cursor-pointer overflow-hidden transition-colors pt-0!"
            onClick={() => navigate(`/streams/${stream.id}`)}
          >
            {/* Preview hero area */}
            <div className="relative aspect-[4/3] overflow-hidden">
              {lastParticle ? (
                <ParticlePreview particle={lastParticle} />
              ) : (
                <div className="flex h-full w-full items-center justify-center">
                  <p className="text-muted-foreground text-xs italic">
                    No messages yet
                  </p>
                </div>
              )}

              {/* Unseen badge overlay */}
              {stream.unseen_count > 0 && (
                <Badge
                  variant="default"
                  className="absolute top-1.5 right-1.5 text-[10px]"
                >
                  {stream.unseen_count}
                </Badge>
              )}
            </div>

            {/* Footer: avatar + stream info */}
            <div className="flex items-center gap-2 px-3 py-2">
              {senderEmail ? (
                <Avatar size="sm">
                  <AvatarFallback className="text-[10px]">
                    {getInitials(senderEmail)}
                  </AvatarFallback>
                </Avatar>
              ) : (
                <div className="size-6 shrink-0" />
              )}

              <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-medium">{stream.name}</p>
                <p className="text-muted-foreground truncate text-[11px]">
                  {senderPrefix && <span>{senderPrefix}</span>}
                  {senderPrefix && timeSource && <span> &middot; </span>}
                  {timeSource && <span>{formatDistanceToNow(timeSource)}</span>}
                </p>
              </div>
            </div>
          </Card>
        );
      })}
    </div>
  );
}
