import type { LucideIcon } from 'lucide-react';
import {
  Activity,
  Building2,
  FileText,
  GraduationCap,
  LayoutGrid,
  ListChecks,
  School,
  Users,
} from 'lucide-react';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ModuleHeader } from '@/components/ui/module-header';
import { PageSkeleton } from '@/components/ui/page-skeleton';
import { usePlatformStats } from '@/business/platform/hooks';
import { getAuthRoleLabel } from '@/business/auth/selectors';
import { isUserRole } from '@/shared/constants/roles';

interface StatCardProps {
  readonly label: string;
  readonly value: number;
  readonly icon: LucideIcon;
  readonly tone: string;
}

function StatCard({ label, value, icon: Icon, tone }: StatCardProps) {
  return (
    <Card>
      <CardContent className="flex items-center gap-3 p-4">
        <span className={`flex h-10 w-10 items-center justify-center rounded-xl text-white ${tone}`}>
          <Icon size={18} />
        </span>
        <div>
          <p className="text-2xl font-bold text-white leading-none">{value.toLocaleString()}</p>
          <p className="text-xs text-slate-400 mt-1">{label}</p>
        </div>
      </CardContent>
    </Card>
  );
}

function roleLabelFor(roleName: string): string {
  return isUserRole(roleName) ? getAuthRoleLabel(roleName) : roleName;
}

export default function PlatformDashboardPage() {
  const { data, isLoading, error } = usePlatformStats();

  if (isLoading) {
    return <PageSkeleton />;
  }

  if (error || !data) {
    return (
      <div className="p-4 md:p-6">
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-200">
          Could not load platform statistics.
        </div>
      </div>
    );
  }

  const roleEntries = Object.entries(data.users.byRole).sort((a, b) => b[1] - a[1]);

  return (
    <div className="space-y-6 p-4 md:p-6">
      <ModuleHeader
        title="Platform Dashboard"
        description="Platform-wide overview across all organizations."
        icon={LayoutGrid}
        iconClassName="bg-gradient-to-br from-violet-500 to-violet-700"
      />

      <section className="space-y-3">
        <h3 className="text-sm font-semibold text-slate-300">Organizations & Locations</h3>
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <StatCard label="Organizations" value={data.tenants.organizations} icon={Building2} tone="bg-violet-500" />
          <StatCard label="Schools" value={data.tenants.schools} icon={School} tone="bg-blue-500" />
          <StatCard label="Campuses" value={data.tenants.campuses} icon={GraduationCap} tone="bg-emerald-500" />
          <StatCard label="Classes" value={data.tenants.classes} icon={LayoutGrid} tone="bg-amber-500" />
        </div>
      </section>

      <section className="space-y-3">
        <h3 className="text-sm font-semibold text-slate-300">Content & activity</h3>
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <StatCard label="FRAME entries" value={data.content.frameEntries} icon={ListChecks} tone="bg-orange-500" />
          <StatCard label="Quizzes" value={data.content.quizzes} icon={ListChecks} tone="bg-teal-500" />
          <StatCard label="Documents" value={data.content.documents} icon={FileText} tone="bg-slate-600" />
          <StatCard label="Active sessions" value={data.activeSessions} icon={Activity} tone="bg-rose-500" />
        </div>
      </section>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <Users size={16} />
            Users by role
            <span className="ml-auto text-sm font-normal text-slate-400">
              {data.users.total.toLocaleString()} total
            </span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          {roleEntries.length === 0 ? (
            <p className="text-sm text-slate-400">No users yet.</p>
          ) : (
            <ul className="divide-y divide-slate-700/50">
              {roleEntries.map(([roleName, count]) => (
                <li key={roleName} className="flex items-center justify-between py-2">
                  <span className="text-sm text-slate-200">{roleLabelFor(roleName)}</span>
                  <span className="text-sm font-semibold text-white">{count.toLocaleString()}</span>
                </li>
              ))}
            </ul>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
