'use client'

import { useState } from 'react'
import { useParams } from 'next/navigation'
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,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { toast } from 'sonner'
import { cn } from '@/lib/utils'
import {
  ArrowLeft,
  ChevronDown,
  Layers,
  Users,
  FileBox,
  ClipboardList,
  Settings,
  MoreHorizontal,
  Archive,
  Loader2,
  Plus,
} from 'lucide-react'
import { CompetitionTimeline } from '@/components/admin/competition/competition-timeline'

const ROUND_TYPES = [
  { value: 'INTAKE', label: 'Intake' },
  { value: 'FILTERING', label: 'Filtering' },
  { value: 'EVALUATION', label: 'Evaluation' },
  { value: 'SUBMISSION', label: 'Submission' },
  { value: 'MENTORING', label: 'Mentoring' },
  { value: 'LIVE_FINAL', label: 'Live Final' },
  { value: 'DELIBERATION', label: 'Deliberation' },
] as const

const statusConfig = {
  DRAFT: {
    label: 'Draft',
    bgClass: 'bg-gray-100 text-gray-700',
    dotClass: 'bg-gray-500',
  },
  ACTIVE: {
    label: 'Active',
    bgClass: 'bg-emerald-100 text-emerald-700',
    dotClass: 'bg-emerald-500',
  },
  CLOSED: {
    label: 'Closed',
    bgClass: 'bg-blue-100 text-blue-700',
    dotClass: 'bg-blue-500',
  },
  ARCHIVED: {
    label: 'Archived',
    bgClass: 'bg-muted text-muted-foreground',
    dotClass: 'bg-muted-foreground',
  },
} as const

const roundTypeColors: Record<string, string> = {
  INTAKE: 'bg-gray-100 text-gray-700',
  FILTERING: 'bg-amber-100 text-amber-700',
  EVALUATION: 'bg-blue-100 text-blue-700',
  SUBMISSION: 'bg-purple-100 text-purple-700',
  MENTORING: 'bg-teal-100 text-teal-700',
  LIVE_FINAL: 'bg-red-100 text-red-700',
  DELIBERATION: 'bg-indigo-100 text-indigo-700',
}

export default function CompetitionDetailPage() {
  const params = useParams()
  const competitionId = params.id as string
  const utils = trpc.useUtils()
  const [addRoundOpen, setAddRoundOpen] = useState(false)
  const [roundForm, setRoundForm] = useState({
    name: '',
    roundType: '' as string,
  })

  const { data: competition, isLoading } = trpc.competition.getById.useQuery({
    id: competitionId,
  })

  const updateMutation = trpc.competition.update.useMutation({
    onSuccess: () => {
      utils.competition.getById.invalidate({ id: competitionId })
      toast.success('Competition updated')
    },
    onError: (err) => toast.error(err.message),
  })

  const createRoundMutation = trpc.round.create.useMutation({
    onSuccess: () => {
      utils.competition.getById.invalidate({ id: competitionId })
      toast.success('Round created')
      setAddRoundOpen(false)
      setRoundForm({ name: '', roundType: '' })
    },
    onError: (err) => toast.error(err.message),
  })

  const handleStatusChange = (newStatus: 'DRAFT' | 'ACTIVE' | 'CLOSED' | 'ARCHIVED') => {
    updateMutation.mutate({ id: competitionId, status: newStatus })
  }

  const handleCreateRound = () => {
    if (!roundForm.name.trim() || !roundForm.roundType) {
      toast.error('Name and type are required')
      return
    }
    const slug = roundForm.name
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-|-$/g, '')
    const nextOrder = competition?.rounds.length ?? 0
    createRoundMutation.mutate({
      competitionId,
      name: roundForm.name.trim(),
      slug,
      roundType: roundForm.roundType as any,
      sortOrder: nextOrder,
    })
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-3">
          <Skeleton className="h-8 w-8" />
          <div>
            <Skeleton className="h-6 w-48" />
            <Skeleton className="h-4 w-32 mt-1" />
          </div>
        </div>
        <Skeleton className="h-10 w-full" />
        <Skeleton className="h-64 w-full" />
      </div>
    )
  }

  if (!competition) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-3">
          <Link href={"/admin/competitions" as Route}>
            <Button variant="ghost" size="icon" className="h-8 w-8" aria-label="Back to competitions list">
              <ArrowLeft className="h-4 w-4" />
            </Button>
          </Link>
          <div>
            <h1 className="text-xl font-bold">Competition Not Found</h1>
            <p className="text-sm text-muted-foreground">
              The requested competition does not exist
            </p>
          </div>
        </div>
      </div>
    )
  }

  const status = competition.status as keyof typeof statusConfig
  const config = statusConfig[status] || statusConfig.DRAFT

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div className="flex items-start gap-3 min-w-0">
          <Link href={"/admin/competitions" as Route} className="mt-1 shrink-0">
            <Button variant="ghost" size="icon" className="h-8 w-8" aria-label="Back to competitions list">
              <ArrowLeft className="h-4 w-4" />
            </Button>
          </Link>
          <div className="min-w-0">
            <div className="flex flex-wrap items-center gap-2">
              <h1 className="text-xl font-bold truncate">{competition.name}</h1>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <button
                    className={cn(
                      'inline-flex items-center gap-1 text-[10px] px-2 py-1 rounded-full transition-colors shrink-0',
                      config.bgClass,
                      'hover:opacity-80'
                    )}
                  >
                    {config.label}
                    <ChevronDown className="h-3 w-3" />
                  </button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="start">
                  {(['DRAFT', 'ACTIVE', 'CLOSED'] as const).map((s) => (
                    <DropdownMenuItem
                      key={s}
                      onClick={() => handleStatusChange(s)}
                      disabled={competition.status === s || updateMutation.isPending}
                    >
                      {s.charAt(0) + s.slice(1).toLowerCase()}
                    </DropdownMenuItem>
                  ))}
                  <DropdownMenuSeparator />
                  <DropdownMenuItem
                    onClick={() => handleStatusChange('ARCHIVED')}
                    disabled={competition.status === 'ARCHIVED' || updateMutation.isPending}
                  >
                    <Archive className="h-4 w-4 mr-2" />
                    Archive
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
            <p className="text-sm text-muted-foreground font-mono">{competition.slug}</p>
          </div>
        </div>

        <div className="flex items-center gap-2 shrink-0">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="icon" className="h-8 w-8" aria-label="More actions">
                <MoreHorizontal className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem asChild>
                <Link href={`/admin/competitions/${competitionId}/assignments` as Route}>
                  <ClipboardList className="h-4 w-4 mr-2" />
                  Assignments
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem asChild>
                <Link href={`/admin/competitions/${competitionId}/deliberation` as Route}>
                  <Users className="h-4 w-4 mr-2" />
                  Deliberation
                </Link>
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem
                onClick={() => handleStatusChange('ARCHIVED')}
                disabled={updateMutation.isPending}
              >
                {updateMutation.isPending ? (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                ) : (
                  <Archive className="h-4 w-4 mr-2" />
                )}
                Archive
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid gap-3 grid-cols-2 sm:grid-cols-4">
        <Card>
          <CardContent className="pt-4 pb-3">
            <div className="flex items-center gap-2">
              <Layers className="h-4 w-4 text-blue-500" />
              <span className="text-sm font-medium">Rounds</span>
            </div>
            <p className="text-2xl font-bold mt-1">{competition.rounds.length}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-4 pb-3">
            <div className="flex items-center gap-2">
              <Users className="h-4 w-4 text-purple-500" />
              <span className="text-sm font-medium">Juries</span>
            </div>
            <p className="text-2xl font-bold mt-1">{competition.juryGroups.length}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-4 pb-3">
            <div className="flex items-center gap-2">
              <FileBox className="h-4 w-4 text-emerald-500" />
              <span className="text-sm font-medium">Windows</span>
            </div>
            <p className="text-2xl font-bold mt-1">{competition.submissionWindows.length}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-4 pb-3">
            <div className="flex items-center gap-2">
              <Settings className="h-4 w-4 text-amber-500" />
              <span className="text-sm font-medium">Category</span>
            </div>
            <p className="text-lg font-bold mt-1 truncate">{competition.categoryMode}</p>
          </CardContent>
        </Card>
      </div>

      {/* Tabs */}
      <Tabs defaultValue="overview" className="space-y-4">
        <TabsList className="w-full sm:w-auto overflow-x-auto">
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="rounds">Rounds</TabsTrigger>
          <TabsTrigger value="juries">Juries</TabsTrigger>
          <TabsTrigger value="settings">Settings</TabsTrigger>
        </TabsList>

        {/* Overview Tab */}
        <TabsContent value="overview" className="space-y-6">
          <CompetitionTimeline
            competitionId={competitionId}
            rounds={competition.rounds}
          />
        </TabsContent>

        {/* Rounds Tab */}
        <TabsContent value="rounds" className="space-y-4">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <h2 className="text-lg font-semibold">Rounds ({competition.rounds.length})</h2>
            <Button size="sm" variant="outline" className="w-full sm:w-auto" onClick={() => setAddRoundOpen(true)}>
              <Plus className="h-4 w-4 mr-1" />
              Add Round
            </Button>
          </div>

          {competition.rounds.length === 0 ? (
            <Card className="border-dashed">
              <CardContent className="py-8 text-center text-sm text-muted-foreground">
                No rounds configured. Add rounds to define the competition flow.
              </CardContent>
            </Card>
          ) : (
            <div className="space-y-2">
              {competition.rounds.map((round, index) => (
                <Link
                  key={round.id}
                  href={`/admin/competitions/${competitionId}/rounds/${round.id}` as Route}
                >
                  <Card className="hover:shadow-sm transition-shadow cursor-pointer">
                    <CardContent className="flex items-center gap-3 py-3">
                      <div className="flex h-8 w-8 items-center justify-center rounded-full bg-muted text-sm font-bold shrink-0">
                        {index + 1}
                      </div>
                      <div className="min-w-0 flex-1">
                        <p className="text-sm font-medium truncate">{round.name}</p>
                        <p className="text-xs text-muted-foreground font-mono">{round.slug}</p>
                      </div>
                      <Badge
                        variant="secondary"
                        className={cn(
                          'text-[10px] shrink-0',
                          roundTypeColors[round.roundType] ?? 'bg-gray-100 text-gray-700'
                        )}
                      >
                        {round.roundType.replace('_', ' ')}
                      </Badge>
                      <Badge
                        variant="outline"
                        className="text-[10px] shrink-0 hidden sm:inline-flex"
                      >
                        {round.status.replace('ROUND_', '')}
                      </Badge>
                    </CardContent>
                  </Card>
                </Link>
              ))}
            </div>
          )}
        </TabsContent>

        {/* Juries Tab */}
        <TabsContent value="juries" className="space-y-4">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <h2 className="text-lg font-semibold">Jury Groups ({competition.juryGroups.length})</h2>
            <Link href={`/admin/competitions/${competitionId}/juries` as Route}>
              <Button size="sm" variant="outline" className="w-full sm:w-auto">
                <Users className="h-4 w-4 mr-1" />
                Manage Juries
              </Button>
            </Link>
          </div>

          {competition.juryGroups.length === 0 ? (
            <Card className="border-dashed">
              <CardContent className="py-8 text-center text-sm text-muted-foreground">
                No jury groups configured. Create jury groups to assign evaluators.
              </CardContent>
            </Card>
          ) : (
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {competition.juryGroups.map((group) => (
                <Link
                  key={group.id}
                  href={`/admin/competitions/${competitionId}/juries/${group.id}` as Route}
                >
                  <Card className="hover:shadow-sm transition-shadow cursor-pointer h-full">
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm">{group.name}</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center gap-3 text-xs text-muted-foreground">
                        <span>{group._count.members} members</span>
                        <Badge variant="outline" className="text-[10px]">
                          Cap: {group.defaultCapMode}
                        </Badge>
                      </div>
                    </CardContent>
                  </Card>
                </Link>
              ))}
            </div>
          )}
        </TabsContent>

        {/* Settings Tab */}
        <TabsContent value="settings" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Competition Settings</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 sm:grid-cols-2">
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Category Mode</label>
                  <p className="text-sm mt-1">{competition.categoryMode}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Startup Finalists</label>
                  <p className="text-sm mt-1">{competition.startupFinalistCount}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Concept Finalists</label>
                  <p className="text-sm mt-1">{competition.conceptFinalistCount}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Notifications</label>
                  <div className="flex flex-wrap gap-2 mt-1">
                    {competition.notifyOnRoundAdvance && (
                      <Badge variant="secondary" className="text-[10px]">Round Advance</Badge>
                    )}
                    {competition.notifyOnDeadlineApproach && (
                      <Badge variant="secondary" className="text-[10px]">Deadline Approach</Badge>
                    )}
                  </div>
                </div>
              </div>
              {competition.deadlineReminderDays && (
                <div>
                  <label className="text-sm font-medium text-muted-foreground">
                    Reminder Days
                  </label>
                  <p className="text-sm mt-1">
                    {(competition.deadlineReminderDays as number[]).join(', ')} days before deadline
                  </p>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Add Round Dialog */}
      <Dialog open={addRoundOpen} onOpenChange={setAddRoundOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Add Round</DialogTitle>
            <DialogDescription>
              Add a new round to this competition. It will be appended to the current round sequence.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="round-name">Name *</Label>
              <Input
                id="round-name"
                placeholder="e.g. Initial Screening"
                value={roundForm.name}
                onChange={(e) => setRoundForm({ ...roundForm, name: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="round-type">Round Type *</Label>
              <Select
                value={roundForm.roundType}
                onValueChange={(value) => setRoundForm({ ...roundForm, roundType: value })}
              >
                <SelectTrigger id="round-type">
                  <SelectValue placeholder="Select type" />
                </SelectTrigger>
                <SelectContent>
                  {ROUND_TYPES.map((rt) => (
                    <SelectItem key={rt.value} value={rt.value}>
                      {rt.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setAddRoundOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleCreateRound} disabled={createRoundMutation.isPending}>
              {createRoundMutation.isPending ? 'Creating...' : 'Create Round'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
