import {
  Users,
  UserCheck,
  UserMinus,
  Clock,
  BarChart3,
  TrendingUp,
} from 'lucide-react';

import { createMemberManagementApi } from '@kit/member-management/api';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';

import { AccountNotFound } from '~/components/account-not-found';
import { CmsPageShell } from '~/components/cms-page-shell';
import { StatsCard } from '~/components/stats-card';
import { StatsBarChart, StatsPieChart } from '~/components/stats-charts';

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

export default async function MemberStatisticsPage({ 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 <AccountNotFound />;

  const api = createMemberManagementApi(client);
  const stats = await api.getMemberStatistics(acct.id);

  const statusChartData = [
    { name: 'Aktiv', value: stats.active ?? 0 },
    { name: 'Inaktiv', value: stats.inactive ?? 0 },
    { name: 'Ausstehend', value: stats.pending ?? 0 },
    { name: 'Ausgetreten', value: stats.resigned ?? 0 },
  ];

  return (
    <CmsPageShell account={account} title="Mitglieder-Statistiken">
      <div className="flex w-full flex-col gap-6">
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <StatsCard
            title="Gesamt"
            value={stats.total ?? 0}
            icon={<Users className="h-5 w-5" />}
          />
          <StatsCard
            title="Aktiv"
            value={stats.active ?? 0}
            icon={<UserCheck className="h-5 w-5" />}
          />
          <StatsCard
            title="Inaktiv"
            value={stats.inactive ?? 0}
            icon={<UserMinus className="h-5 w-5" />}
          />
          <StatsCard
            title="Ausstehend"
            value={stats.pending ?? 0}
            icon={<Clock className="h-5 w-5" />}
          />
        </div>

        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <BarChart3 className="h-5 w-5" />
                Mitglieder nach Status
              </CardTitle>
            </CardHeader>
            <CardContent>
              <StatsBarChart data={statusChartData} />
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <TrendingUp className="h-5 w-5" />
                Verteilung
              </CardTitle>
            </CardHeader>
            <CardContent>
              <StatsPieChart data={statusChartData} />
            </CardContent>
          </Card>
        </div>
      </div>
    </CmsPageShell>
  );
}
