import { UserCheck, UserX, FileText } from 'lucide-react';

import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { Badge } from '@kit/ui/badge';
import { Button } from '@kit/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';

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

import { CmsPageShell } from '~/components/cms-page-shell';
import { EmptyState } from '~/components/empty-state';

interface PageProps {
  params: Promise<{ account: string }>;
}

const STATUS_VARIANT: Record<string, 'secondary' | 'default' | 'info' | 'destructive'> = {
  pending: 'secondary',
  approved: 'default',
  rejected: 'destructive',
};

const STATUS_LABEL: Record<string, string> = {
  pending: 'Ausstehend',
  approved: 'Genehmigt',
  rejected: 'Abgelehnt',
};

export default async function ApplicationsPage({ params }: PageProps) {
  const { account } = await params;
  const client = getSupabaseServerClient();

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

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

  const api = createMemberManagementApi(client);
  const applications = await api.listApplications(acct.id);

  return (
    <CmsPageShell account={account} title="Anträge">
      <div className="flex w-full flex-col gap-6">
        <div>
          <h1 className="text-2xl font-bold">Mitgliedsanträge</h1>
          <p className="text-muted-foreground">Eingehende Anträge prüfen und bearbeiten</p>
        </div>

        {applications.length === 0 ? (
          <EmptyState
            icon={<FileText className="h-8 w-8" />}
            title="Keine Anträge"
            description="Es liegen derzeit keine Mitgliedsanträge vor."
          />
        ) : (
          <Card>
            <CardHeader>
              <CardTitle>Alle Anträge ({applications.length})</CardTitle>
            </CardHeader>
            <CardContent>
              <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 font-medium">Name</th>
                      <th className="p-3 text-left font-medium">E-Mail</th>
                      <th className="p-3 text-left font-medium">Datum</th>
                      <th className="p-3 text-left font-medium">Status</th>
                      <th className="p-3 text-right font-medium">Aktionen</th>
                    </tr>
                  </thead>
                  <tbody>
                    {applications.map((app: Record<string, unknown>) => (
                      <tr key={String(app.id)} className="border-b hover:bg-muted/30">
                        <td className="p-3 font-medium">
                          {String(app.last_name ?? '')}, {String(app.first_name ?? '')}
                        </td>
                        <td className="p-3">{String(app.email ?? '—')}</td>
                        <td className="p-3">
                          {app.created_at
                            ? new Date(String(app.created_at)).toLocaleDateString('de-DE')
                            : '—'}
                        </td>
                        <td className="p-3">
                          <Badge variant={STATUS_VARIANT[String(app.status)] ?? 'secondary'}>
                            {STATUS_LABEL[String(app.status)] ?? String(app.status)}
                          </Badge>
                        </td>
                        <td className="p-3 text-right">
                          {String(app.status) === 'pending' && (
                            <div className="flex justify-end gap-2">
                              <Button size="sm" variant="default">
                                <UserCheck className="mr-1 h-3 w-3" />
                                Genehmigen
                              </Button>
                              <Button size="sm" variant="destructive">
                                <UserX className="mr-1 h-3 w-3" />
                                Ablehnen
                              </Button>
                            </div>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </CmsPageShell>
  );
}
