'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 { ProjectLogoWithUrl } from '@/components/shared/project-logo-with-url'
import { AlertTriangle, FileText, Upload, Users } 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 SubmissionPanel({ roundId, programId }: { roundId: string; programId: string }) {
  const { data: roundStats, isLoading: statsLoading } = trpc.analytics.getRoundTypeStats.useQuery(
    { roundId },
    { refetchInterval: 30_000 },
  )

  const { data: recentFiles } = trpc.analytics.getRecentFiles.useQuery(
    { roundId, limit: 10 },
    { refetchInterval: 30_000 },
  )

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

  const stats = roundStats?.stats as {
    totalFiles: number
    teamsSubmitted: number
  } | undefined

  const files = recentFiles ?? []
  const projects = projectsData?.projects ?? []

  return (
    <div className="space-y-4">
      {/* Stats Cards */}
      {statsLoading ? (
        <div className="grid grid-cols-2 gap-3">
          <Skeleton className="h-20 rounded-lg" />
          <Skeleton className="h-20 rounded-lg" />
        </div>
      ) : stats ? (
        <div className="grid grid-cols-2 gap-3">
          <Card className="p-3 text-center">
            <div className="flex items-center justify-center gap-2">
              <Upload className="h-4 w-4 text-violet-500" />
              <p className="text-2xl font-semibold tabular-nums">{stats.totalFiles}</p>
            </div>
            <p className="text-xs text-muted-foreground mt-0.5">Files Uploaded</p>
          </Card>
          <Card className="p-3 text-center">
            <div className="flex items-center justify-center gap-2">
              <Users className="h-4 w-4 text-blue-500" />
              <p className="text-2xl font-semibold tabular-nums">{stats.teamsSubmitted}</p>
            </div>
            <p className="text-xs text-muted-foreground mt-0.5">Teams with Uploads</p>
          </Card>
        </div>
      ) : null}

      {/* Recent Document Uploads */}
      {files.length > 0 && (
        <AnimatedCard index={1}>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="flex items-center gap-2 text-sm">
                <FileText className="h-4 w-4 text-violet-500" />
                Recent Documents
              </CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <div className="divide-y">
                {files.map((f: any) => (
                  <Link
                    key={f.id}
                    href={`/observer/projects/${f.project?.id}` as Route}
                    className="flex items-center gap-3 px-4 py-2.5 hover:bg-muted/50 transition-colors"
                  >
                    {/* Project avatar */}
                    <ProjectLogoWithUrl
                      project={{ id: f.project?.id ?? '', title: f.project?.title ?? '', logoKey: f.project?.logoKey }}
                      size="sm"
                      fallback="initials"
                    />

                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-medium truncate">{f.fileName}</p>
                      <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
                        <span className="truncate">{f.project?.title ?? 'Unknown project'}</span>
                        {/* Page count */}
                        {f.pageCount != null && (
                          <>
                            <span>·</span>
                            <span className="shrink-0">{f.pageCount} pg{f.pageCount !== 1 ? 's' : ''}</span>
                          </>
                        )}
                        {/* Language badge */}
                        {f.detectedLang && f.detectedLang !== 'und' && (
                          <>
                            <span>·</span>
                            <span className={`shrink-0 font-mono uppercase ${f.detectedLang !== 'eng' ? 'text-amber-600 font-semibold' : ''}`}>
                              {f.detectedLang}
                            </span>
                            {f.detectedLang !== 'eng' && (
                              <AlertTriangle className="h-3 w-3 text-amber-500 shrink-0" />
                            )}
                          </>
                        )}
                      </div>
                    </div>
                    <span className="text-[11px] tabular-nums text-muted-foreground shrink-0">
                      {f.createdAt ? relativeTime(f.createdAt) : ''}
                    </span>
                  </Link>
                ))}
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>
      )}

      {/* Project Teams */}
      {projects.length > 0 && (
        <AnimatedCard index={2}>
          <Card>
            <CardHeader className="pb-2">
              <div className="flex items-center justify-between">
                <CardTitle className="flex items-center gap-2 text-sm">
                  <Users className="h-4 w-4 text-emerald-500" />
                  Projects
                </CardTitle>
                <Link
                  href={'/observer/projects' as Route}
                  className="text-xs text-primary hover:underline"
                >
                  See all
                </Link>
              </div>
            </CardHeader>
            <CardContent className="p-0">
              <div className="divide-y">
                {projects.map((p) => (
                  <Link
                    key={p.id}
                    href={`/observer/projects/${p.id}` as Route}
                    className="flex items-center gap-3 px-4 py-2.5 hover:bg-muted/50 transition-colors"
                  >
                    <ProjectLogoWithUrl
                      project={{ id: p.id, title: p.title, logoKey: (p as any).logoKey }}
                      size="sm"
                      fallback="initials"
                    />
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-medium truncate">{p.title}</p>
                      {p.country && (
                        <p className="text-xs text-muted-foreground">
                          <CountryDisplay country={p.country} />
                        </p>
                      )}
                    </div>
                  </Link>
                ))}
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>
      )}
    </div>
  )
}
