import { GraduationCap, Users, Calendar, TrendingUp, BarChart3 } from 'lucide-react';

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

import { createCourseManagementApi } from '@kit/course-management/api';

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 CourseStatisticsPage({ 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 = createCourseManagementApi(client);
  const stats = await api.getStatistics(acct.id);

  const statusChartData = [
    { name: 'Aktiv', value: stats.openCourses },
    { name: 'Abgeschlossen', value: stats.completedCourses },
    { name: 'Gesamt', value: stats.totalCourses },
  ];

  return (
    <CmsPageShell account={account} title="Kurs-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="Kurse gesamt" value={stats.totalCourses} icon={<GraduationCap className="h-5 w-5" />} />
          <StatsCard title="Aktive Kurse" value={stats.openCourses} icon={<Calendar className="h-5 w-5" />} />
          <StatsCard title="Teilnehmer" value={stats.totalParticipants} icon={<Users className="h-5 w-5" />} />
          <StatsCard title="Abgeschlossen" value={stats.completedCourses} icon={<TrendingUp 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" />
                Kursauslastung
              </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>
  );
}
