'use client'

import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Badge } from '@/components/ui/badge'
import { AnimatedCard } from '@/components/shared/animated-container'
import { CountryDisplay } from '@/components/shared/country-display'
import { Inbox, Globe, FolderOpen } from 'lucide-react'

function relativeTime(date: Date | string): string {
  const now = Date.now()
  const then = new Date(date).getTime()
  const diff = Math.floor((now - then) / 1000)
  if (diff < 60) return `${diff}s ago`
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`
  return `${Math.floor(diff / 86400)}d ago`
}

export function IntakePanel({ roundId, programId }: { roundId: string; programId: string }) {
  const { data: roundStats, isLoading: statsLoading } = trpc.analytics.getRoundTypeStats.useQuery(
    { roundId },
    { refetchInterval: 30_000 },
  )

  const { data: projectsData } = trpc.analytics.getAllProjects.useQuery(
    { roundId, perPage: 8 },
    { refetchInterval: 30_000 },
  )

  const { data: geoData } = trpc.analytics.getGeographicDistribution.useQuery(
    { programId, roundId },
    { enabled: !!programId, refetchInterval: 30_000 },
  )

  const stats = roundStats?.stats as {
    totalProjects: number
    byCategory: { category: string; count: number }[]
    byState: { state: string; count: number }[]
  } | undefined

  const projects = projectsData?.projects ?? []
  const topCountries = (geoData ?? []).slice(0, 10)

  return (
    <div className="space-y-4">
      {/* Stats Cards */}
      {statsLoading ? (
        <div className="grid grid-cols-3 gap-3">
          {[...Array(3)].map((_, i) => <Skeleton key={i} className="h-20 rounded-lg" />)}
        </div>
      ) : stats ? (
        <div className="grid grid-cols-3 gap-3">
          <Card className="p-3 text-center">
            <p className="text-2xl font-semibold tabular-nums">{stats.totalProjects}</p>
            <p className="text-xs text-muted-foreground mt-0.5">Total Projects</p>
          </Card>
          {stats.byCategory.map((c) => (
            <Card key={c.category} className="p-3 text-center">
              <p className="text-2xl font-semibold tabular-nums">{c.count}</p>
              <p className="text-xs text-muted-foreground mt-0.5 truncate">{c.category}</p>
            </Card>
          ))}
        </div>
      ) : null}

      {/* Recent Submissions */}
      <AnimatedCard index={1}>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="flex items-center gap-2 text-sm">
              <Inbox className="h-4 w-4 text-brand-teal" />
              Recent Submissions
            </CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            {projects.length > 0 ? (
              <div className="divide-y">
                {projects.map((p) => (
                  <Link
                    key={p.id}
                    href={`/observer/projects/${p.id}` as Route}
                    className="flex items-center justify-between gap-2 px-4 py-2.5 hover:bg-muted/50 transition-colors"
                  >
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-medium truncate">{p.title}</p>
                      <p className="text-xs text-muted-foreground truncate">
                        {p.teamName ?? 'No team'} · {p.country ? <CountryDisplay country={p.country} /> : ''}
                      </p>
                    </div>
                    <span className="text-[11px] tabular-nums text-muted-foreground shrink-0">
                      {p.country ? <CountryDisplay country={p.country} /> : ''}
                    </span>
                  </Link>
                ))}
              </div>
            ) : (
              <div className="p-4 text-sm text-muted-foreground">No submissions yet.</div>
            )}
          </CardContent>
        </Card>
      </AnimatedCard>

      {/* Country Ranking */}
      {topCountries.length > 0 && (
        <AnimatedCard index={2}>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="flex items-center gap-2 text-sm">
                <Globe className="h-4 w-4 text-blue-500" />
                Top Countries
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-1.5">
                {topCountries.map((c, i) => (
                  <div key={c.countryCode} className="flex items-center justify-between text-sm">
                    <span className="truncate">
                      <span className="text-muted-foreground tabular-nums mr-2">{i + 1}.</span>
                      {c.countryCode}
                    </span>
                    <Badge variant="secondary" className="tabular-nums text-xs">
                      {c.count}
                    </Badge>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>
      )}

      {/* Category Breakdown */}
      {stats && stats.byCategory.length > 0 && (
        <AnimatedCard index={3}>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="flex items-center gap-2 text-sm">
                <FolderOpen className="h-4 w-4 text-emerald-500" />
                Category Breakdown
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex gap-2">
                {stats.byCategory.map((c) => {
                  const pct = stats.totalProjects > 0 ? Math.round((c.count / stats.totalProjects) * 100) : 0
                  return (
                    <div key={c.category} className="flex-1 rounded-lg bg-muted p-3 text-center">
                      <p className="text-lg font-semibold tabular-nums">{pct}%</p>
                      <p className="text-xs text-muted-foreground truncate">{c.category}</p>
                    </div>
                  )
                })}
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>
      )}
    </div>
  )
}
