import { Button } from "@/components/ui/button";
import { createClient } from "@/lib/supabase/server";
import { ChevronLeftIcon } from "lucide-react";
import Link from "next/link";
import Polls from "./_components/polls";

interface PageProps {
  params: Promise<{ id: string; memberId: string }>;
}

export default async function Page(props: PageProps) {
  const { id, memberId } = await props.params;
  const supabase = await createClient();
  const { data: polls } = await supabase.from("polls").select().eq("id", id);
  const { data: members } = await supabase
    .from("poll_members")
    .select()
    .eq("poll_id", id)
    .eq("id", parseInt(memberId));
  const { data: choices } = await supabase
    .from("poll_choices")
    .select()
    .eq("poll_id", id);

  if (!polls || polls.length === 0) {
    return <div className="max-w-6xl mx-auto py-2 w-[95%]">Poll not found</div>;
  }

  if (!members || members.length === 0) {
    return (
      <div className="max-w-6xl mx-auto py-2 w-[95%]">Member not found</div>
    );
  }

  const [poll] = polls;
  const [member] = members;

  return (
    <main className="max-w-6xl mx-auto py-4 w-[95%] h-screen flex flex-col gap-4">
      <div className="flex justify-between items-center relative">
        <Button size="icon" variant="ghost" asChild>
          <Link href={`/polls/${id}`}>
            <ChevronLeftIcon />
          </Link>
        </Button>
        <h1 className="absolute left-1/2 transform -translate-x-1/2">
          {poll.name}
        </h1>
        <Button>{member.name}</Button>
      </div>

      <Polls
        choices={(choices || []).map((c) => ({
          id: c.id,
          name: c.name,
          picture: c.picture,
          distance: c.distance || undefined,
        }))}
      />
    </main>
  );
}
