'use client'

import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  Plus,
  MoreHorizontal,
  Eye,
  Edit,
  Layers,
  GitBranch,
  Calendar,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { format } from 'date-fns'
import { useEdition } from '@/contexts/edition-context'

const statusColors: Record<string, string> = {
  DRAFT: 'bg-gray-100 text-gray-700',
  ACTIVE: 'bg-emerald-100 text-emerald-700',
  ARCHIVED: 'bg-muted text-muted-foreground',
  CLOSED: 'bg-blue-100 text-blue-700',
}

export default function PipelineListPage() {
  const { currentEdition } = useEdition()
  const programId = currentEdition?.id

  const { data: pipelines, isLoading } = trpc.pipeline.list.useQuery(
    { programId: programId! },
    { enabled: !!programId }
  )

  if (!programId) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-bold">Pipelines</h1>
            <p className="text-sm text-muted-foreground">
              Select an edition to view pipelines
            </p>
          </div>
        </div>
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <Calendar className="h-12 w-12 text-muted-foreground/50" />
            <p className="mt-2 font-medium">No Edition Selected</p>
            <p className="text-sm text-muted-foreground">
              Select an edition from the sidebar to view its pipelines
            </p>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold">Pipelines</h1>
          <p className="text-sm text-muted-foreground">
            Manage evaluation pipelines for {currentEdition?.name}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Link href={`/admin/rounds/new-pipeline?programId=${programId}` as Route}>
            <Button size="sm">
              <Plus className="h-4 w-4 mr-1" />
              Create Pipeline
            </Button>
          </Link>
        </div>
      </div>

      {/* Loading */}
      {isLoading && (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {[1, 2, 3].map((i) => (
            <Card key={i}>
              <CardHeader>
                <Skeleton className="h-5 w-32" />
                <Skeleton className="h-4 w-20 mt-1" />
              </CardHeader>
              <CardContent>
                <Skeleton className="h-4 w-full" />
                <Skeleton className="h-4 w-3/4 mt-2" />
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Empty State */}
      {!isLoading && (!pipelines || pipelines.length === 0) && (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <GitBranch className="h-12 w-12 text-muted-foreground/50" />
            <p className="mt-2 font-medium">No Pipelines Yet</p>
            <p className="text-sm text-muted-foreground mb-4">
              Create your first pipeline to start managing project evaluation
            </p>
            <Link href={`/admin/rounds/new-pipeline?programId=${programId}` as Route}>
              <Button size="sm">
                <Plus className="h-4 w-4 mr-1" />
                Create Pipeline
              </Button>
            </Link>
          </CardContent>
        </Card>
      )}

      {/* Pipeline Cards */}
      {pipelines && pipelines.length > 0 && (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {pipelines.map((pipeline) => (
            <Link
              key={pipeline.id}
              href={`/admin/rounds/pipeline/${pipeline.id}` as Route}
              className="block"
            >
              <Card className="group hover:shadow-md transition-shadow cursor-pointer">
                <CardHeader className="pb-3">
                  <div className="flex items-start justify-between">
                    <div className="min-w-0 flex-1">
                      <CardTitle className="text-base truncate">
                        {pipeline.name}
                      </CardTitle>
                      <CardDescription className="font-mono text-xs">
                        {pipeline.slug}
                      </CardDescription>
                    </div>
                    <div className="flex items-center gap-2">
                      <Badge
                        variant="secondary"
                        className={cn(
                          'text-[10px] shrink-0',
                          statusColors[pipeline.status] ?? ''
                        )}
                      >
                        {pipeline.status}
                      </Badge>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity"
                            onClick={(e) => e.preventDefault()}
                          >
                            <MoreHorizontal className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem asChild>
                            <Link href={`/admin/rounds/pipeline/${pipeline.id}` as Route}>
                              <Eye className="h-4 w-4 mr-2" />
                              View
                            </Link>
                          </DropdownMenuItem>
                          <DropdownMenuItem asChild>
                            <Link href={`/admin/rounds/pipeline/${pipeline.id}/edit` as Route}>
                              <Edit className="h-4 w-4 mr-2" />
                              Edit
                            </Link>
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="flex items-center gap-4 text-sm text-muted-foreground">
                    <div className="flex items-center gap-1">
                      <Layers className="h-3.5 w-3.5" />
                      <span>{pipeline._count.tracks} tracks</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <GitBranch className="h-3.5 w-3.5" />
                      <span>{pipeline._count.routingRules} rules</span>
                    </div>
                  </div>
                  <p className="text-xs text-muted-foreground mt-2">
                    Created {format(new Date(pipeline.createdAt), 'MMM d, yyyy')}
                  </p>
                </CardContent>
              </Card>
            </Link>
          ))}
        </div>
      )}
    </div>
  )
}
