import { useQuery } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import { api } from '../lib/api-client';
import { AppShell, PageBody, PageHeader } from '../layout/AppShell';
import { Card, CardContent, CardHeader, CardTitle, Badge, Skeleton } from '../components/ui/primitives';
import { ArrowRight, Rss, Package, ListChecks, Shield } from 'lucide-react';

interface MeResponse {
  user: { email: string; role: string };
  jobs: { pending: number; running: number; completed: number; failed: number; cancelled: number; total: number };
  recentActivity: { created_at: string; action: string; entity_type: string }[];
  serverTime: string;
}

interface DashboardStats {
  feeds: { enabled: number; total: number; errored: number };
  products: { total: number; sneakers: number };
  today: { clicks: number; conversions: number; revenue: number };
}

export function DashboardPage() {
  const me = useQuery({ queryKey: ['me'], queryFn: () => api.get<MeResponse>('/me') });
  const stats = useQuery({ queryKey: ['dashboard-stats'], queryFn: () => api.get<DashboardStats>('/dashboard/stats') });

  return (
    <AppShell>
      <PageHeader title="Dashboard" description="Overzicht van je SneakerPicks-status" />
      <PageBody>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          <StatCard
            title="Feeds"
            value={stats.data ? `${stats.data.feeds.enabled}/${stats.data.feeds.total}` : '…'}
            hint={stats.data ? `${stats.data.feeds.errored} met fouten` : undefined}
            icon={<Rss className="h-4 w-4 text-[#00FF6A]" />}
            to="/cms/feeds"
          />
          <StatCard
            title="Producten"
            value={stats.data ? fmt(stats.data.products.total) : '…'}
            hint={stats.data ? `${fmt(stats.data.products.sneakers)} sneakers` : undefined}
            icon={<Package className="h-4 w-4 text-[#00FF6A]" />}
            to="/cms/products"
          />
          <StatCard
            title="Jobs"
            value={me.data ? `${me.data.jobs.running + me.data.jobs.pending}` : '…'}
            hint={me.data ? `${me.data.jobs.failed} mislukt` : undefined}
            icon={<ListChecks className="h-4 w-4 text-[#00FF6A]" />}
            to="/cms/jobs"
          />
          <StatCard
            title="Omzet (30d)"
            value={stats.data ? `€${fmt(Math.round(stats.data.today.revenue))}` : '…'}
            hint={stats.data ? `${fmt(stats.data.today.clicks)} kliks` : undefined}
            icon={<Shield className="h-4 w-4 text-[#00FF6A]" />}
            to="/cms/jobs"
          />
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
          <Card>
            <CardHeader>
              <CardTitle>Recente activiteit</CardTitle>
            </CardHeader>
            <CardContent>
              {me.isLoading ? (
                <div className="space-y-2">
                  <Skeleton className="h-8 w-full" />
                  <Skeleton className="h-8 w-full" />
                  <Skeleton className="h-8 w-full" />
                </div>
              ) : me.data?.recentActivity.length ? (
                <ul className="divide-y divide-[#222]">
                  {me.data.recentActivity.map((row, i) => (
                    <li key={i} className="flex items-center justify-between py-2 text-xs">
                      <span className="text-[#F5F5F5]">
                        <Badge variant="muted" className="mr-2">{row.action}</Badge>
                        {row.entity_type}
                      </span>
                      <span className="text-[#666]">{relTime(row.created_at)}</span>
                    </li>
                  ))}
                </ul>
              ) : (
                <p className="text-xs text-[#666]">Geen recente acties.</p>
              )}
              <Link to="/cms/audit" className="mt-3 inline-flex items-center gap-1 text-xs text-[#00FF6A] hover:underline">
                Audit log bekijken <ArrowRight className="h-3 w-3" />
              </Link>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Welkom</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-sm text-[#F5F5F5]">Hallo {me.data?.user.email ?? 'admin'},</p>
              <p className="text-xs text-[#999] mt-2 leading-relaxed">
                Dit is je nieuwe CMS. Gebruik <kbd className="bg-[#0A0A0A] border border-[#333] rounded px-1.5 py-0.5 text-[10px]">Ctrl+K</kbd> om snel te navigeren of acties uit te voeren.
              </p>
              <div className="mt-4 flex flex-wrap gap-2">
                <Link to="/cms/feeds" className="text-xs text-[#00FF6A] hover:underline">Beheer feeds →</Link>
                <Link to="/cms/products" className="text-xs text-[#00FF6A] hover:underline">Producten →</Link>
                <Link to="/cms/homepage" className="text-xs text-[#00FF6A] hover:underline">Homepage →</Link>
              </div>
            </CardContent>
          </Card>
        </div>
      </PageBody>
    </AppShell>
  );
}

function StatCard({
  title,
  value,
  hint,
  icon,
  to,
}: {
  title: string;
  value: string;
  hint?: string;
  icon: React.ReactNode;
  to: string;
}) {
  return (
    <Link to={to} className="block">
      <Card className="hover:border-[#444] transition-colors">
        <CardContent>
          <div className="flex items-start justify-between mb-2">
            <span className="text-xs text-[#999]">{title}</span>
            {icon}
          </div>
          <div className="text-2xl font-semibold text-[#F5F5F5]">{value}</div>
          {hint && <div className="text-[10px] text-[#666] mt-1">{hint}</div>}
        </CardContent>
      </Card>
    </Link>
  );
}

function fmt(n: number) {
  return new Intl.NumberFormat('nl-NL').format(n);
}

function relTime(iso: string) {
  const d = new Date(iso);
  const diff = Date.now() - d.getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'zojuist';
  if (mins < 60) return `${mins}m geleden`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}u geleden`;
  const days = Math.floor(hrs / 24);
  return `${days}d geleden`;
}
