import { DASHBOARD_MODULES } from '@nexumi/shared';
import { Activity, MessageSquare, Mic, Users } from 'lucide-react';
import Link from 'next/link';
import { getActivitySummary } from '@/lib/activity';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { listRecentDashboardAudit } from '@/lib/audit';
import { getLocale, t } from '@/lib/i18n';
import { getModuleStatuses } from '@/lib/modules';

interface OverviewPageProps {
  params: Promise<{ guildId: string }>;
}

function formatDate(iso: string, locale: string): string {
  return new Date(iso).toLocaleString(locale === 'de' ? 'de-DE' : 'en-US', {
    dateStyle: 'medium',
    timeStyle: 'short'
  });
}

function moduleHref(moduleId: string): string {
  return DASHBOARD_MODULES.find((module) => module.id === moduleId)?.href ?? moduleId;
}

export default async function GuildOverviewPage({ params }: OverviewPageProps) {
  const { guildId } = await params;
  const locale = await getLocale();
  const [modules, auditEntries, activitySummary] = await Promise.all([
    getModuleStatuses(guildId),
    listRecentDashboardAudit(guildId, 10),
    getActivitySummary(guildId)
  ]);

  const enabledCount = modules.filter((module) => module.enabled).length;
  const numberLocale = locale === 'de' ? 'de-DE' : 'en-US';

  return (
    <div className="space-y-10">
      <div className="space-y-2">
        <h1 className="text-3xl font-semibold tracking-tight">{t(locale, 'dashboard.overview.title')}</h1>
        <p className="max-w-2xl text-sm text-muted-foreground">
          {t(locale, 'dashboard.overview.activityHint')}
        </p>
      </div>

      <section className="space-y-4">
        <div className="flex items-center gap-2">
          <Activity className="size-4 text-primary" />
          <h2 className="text-lg font-medium">{t(locale, 'dashboard.overview.activityTitle')}</h2>
        </div>
        <div className="grid gap-4 sm:grid-cols-3">
          <Card className="border-border/80 bg-card/80">
            <CardContent className="flex items-start gap-3 p-5">
              <div className="rounded-md bg-primary/10 p-2 text-primary">
                <MessageSquare className="size-4" />
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
                  {t(locale, 'dashboard.overview.activityMessages')}
                </p>
                <p className="mt-1 text-2xl font-semibold tabular-nums">
                  {activitySummary.messageCount.toLocaleString(numberLocale)}
                </p>
              </div>
            </CardContent>
          </Card>
          <Card className="border-border/80 bg-card/80">
            <CardContent className="flex items-start gap-3 p-5">
              <div className="rounded-md bg-primary/10 p-2 text-primary">
                <Mic className="size-4" />
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
                  {t(locale, 'dashboard.overview.activityVoiceMinutes')}
                </p>
                <p className="mt-1 text-2xl font-semibold tabular-nums">
                  {activitySummary.voiceMinutes.toLocaleString(numberLocale)}
                </p>
              </div>
            </CardContent>
          </Card>
          <Card className="border-border/80 bg-card/80">
            <CardContent className="flex items-start gap-3 p-5">
              <div className="rounded-md bg-primary/10 p-2 text-primary">
                <Users className="size-4" />
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
                  {t(locale, 'dashboard.overview.activityActiveUsers')}
                </p>
                <p className="mt-1 text-2xl font-semibold tabular-nums">
                  {activitySummary.activeUserCount.toLocaleString(numberLocale)}
                </p>
              </div>
            </CardContent>
          </Card>
        </div>
      </section>

      <section className="space-y-4">
        <div className="flex items-center justify-between gap-4">
          <div>
            <h2 className="text-lg font-medium">{t(locale, 'dashboard.overview.moduleStatusTitle')}</h2>
            {modules.length > 0 ? (
              <p className="text-sm text-muted-foreground">
                {enabledCount}/{modules.length} {t(locale, 'common.enabled').toLowerCase()}
              </p>
            ) : null}
          </div>
          <Link
            href={`/dashboard/${guildId}/modules`}
            className="text-sm font-medium text-primary hover:underline"
          >
            {t(locale, 'dashboard.overview.viewAllModules')}
          </Link>
        </div>
        {modules.length === 0 ? (
          <Card className="border-dashed">
            <CardContent className="p-8 text-center text-sm text-muted-foreground">
              {t(locale, 'dashboard.overview.moduleStatusEmpty')}
            </CardContent>
          </Card>
        ) : (
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {modules.map((module) => (
              <Link key={module.id} href={`/dashboard/${guildId}/${moduleHref(module.id)}`}>
                <Card className="h-full border-border/80 transition-colors hover:border-primary/40 hover:bg-accent/30">
                  <CardContent className="flex items-center justify-between gap-3 p-4">
                    <span className="font-medium">{t(locale, `modules.${module.id}.label`)}</span>
                    <Badge variant={module.enabled ? 'success' : 'secondary'}>
                      {t(locale, module.enabled ? 'common.enabled' : 'common.disabled')}
                    </Badge>
                  </CardContent>
                </Card>
              </Link>
            ))}
          </div>
        )}
      </section>

      <section className="space-y-4">
        <h2 className="text-lg font-medium">{t(locale, 'dashboard.overview.recentAuditTitle')}</h2>
        <Card className="border-border/80">
          <CardHeader className="pb-2">
            <CardTitle className="text-base">{t(locale, 'dashboard.overview.recentAuditTitle')}</CardTitle>
            <CardDescription>{t(locale, 'dashboard.overview.auditPath')}</CardDescription>
          </CardHeader>
          <CardContent>
            {auditEntries.length === 0 ? (
              <p className="py-6 text-center text-sm text-muted-foreground">
                {t(locale, 'dashboard.overview.auditEmpty')}
              </p>
            ) : (
              <ul className="divide-y divide-border">
                {auditEntries.map((entry) => (
                  <li key={entry.id} className="flex items-center justify-between gap-4 py-3 text-sm">
                    <div className="min-w-0">
                      <p className="truncate font-medium">{entry.action}</p>
                      {entry.path ? <p className="truncate text-xs text-muted-foreground">{entry.path}</p> : null}
                    </div>
                    <span className="whitespace-nowrap text-xs text-muted-foreground">
                      {formatDate(entry.createdAt, locale)}
                    </span>
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>
      </section>
    </div>
  );
}
