import { getSupabaseServerClient } from '@kit/supabase/server-client';

import { createMemberManagementApi } from '@kit/member-management/api';

interface MembersPageProps {
  params: Promise<{ account: string }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}

export default async function MembersPage({ params, searchParams }: MembersPageProps) {
  const { account } = await params;
  const search = await searchParams;
  const client = getSupabaseServerClient();
  const api = createMemberManagementApi(client);

  const { data: accountData } = await client
    .from('accounts')
    .select('id')
    .eq('slug', account)
    .single();

  if (!accountData) return <div>Konto nicht gefunden</div>;

  const page = Number(search.page) || 1;
  const result = await api.listMembers(accountData.id, {
    search: search.q as string,
    status: search.status as string,
    page,
  });

  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Mitglieder</h1>
          <p className="text-muted-foreground">{result.total} Mitglieder</p>
        </div>
      </div>

      <div className="rounded-md border">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b bg-muted/50">
              <th className="p-3 text-left">Nr.</th>
              <th className="p-3 text-left">Name</th>
              <th className="p-3 text-left">E-Mail</th>
              <th className="p-3 text-left">Ort</th>
              <th className="p-3 text-left">Status</th>
            </tr>
          </thead>
          <tbody>
            {result.data.map((member: Record<string, unknown>) => (
              <tr key={String(member.id)} className="border-b hover:bg-muted/30">
                <td className="p-3">{String(member.member_number ?? '—')}</td>
                <td className="p-3 font-medium">{String(member.last_name)}, {String(member.first_name)}</td>
                <td className="p-3">{String(member.email ?? '—')}</td>
                <td className="p-3">{String(member.postal_code ?? '')} {String(member.city ?? '')}</td>
                <td className="p-3">{String(member.status)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
