'use client'

import { useState, useEffect } 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,
  CardDescription,
  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 { toast } from 'sonner'
import { cn } from '@/lib/utils'
import {
  ArrowLeft,
  Edit,
  MoreHorizontal,
  Rocket,
  Archive,
  Settings2,
  Layers,
  GitBranch,
  Loader2,
} from 'lucide-react'

import { IntakePanel } from '@/components/admin/pipeline/stage-panels/intake-panel'
import { FilterPanel } from '@/components/admin/pipeline/stage-panels/filter-panel'
import { EvaluationPanel } from '@/components/admin/pipeline/stage-panels/evaluation-panel'
import { SelectionPanel } from '@/components/admin/pipeline/stage-panels/selection-panel'
import { LiveFinalPanel } from '@/components/admin/pipeline/stage-panels/live-final-panel'
import { ResultsPanel } from '@/components/admin/pipeline/stage-panels/results-panel'

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',
}

const stageTypeColors: Record<string, string> = {
  INTAKE: 'bg-blue-100 text-blue-700',
  FILTER: 'bg-amber-100 text-amber-700',
  EVALUATION: 'bg-purple-100 text-purple-700',
  SELECTION: 'bg-rose-100 text-rose-700',
  LIVE_FINAL: 'bg-emerald-100 text-emerald-700',
  RESULTS: 'bg-cyan-100 text-cyan-700',
}

function StagePanel({
  stageId,
  stageType,
  configJson,
}: {
  stageId: string
  stageType: string
  configJson: Record<string, unknown> | null
}) {
  switch (stageType) {
    case 'INTAKE':
      return <IntakePanel stageId={stageId} configJson={configJson} />
    case 'FILTER':
      return <FilterPanel stageId={stageId} configJson={configJson} />
    case 'EVALUATION':
      return <EvaluationPanel stageId={stageId} configJson={configJson} />
    case 'SELECTION':
      return <SelectionPanel stageId={stageId} configJson={configJson} />
    case 'LIVE_FINAL':
      return <LiveFinalPanel stageId={stageId} configJson={configJson} />
    case 'RESULTS':
      return <ResultsPanel stageId={stageId} configJson={configJson} />
    default:
      return (
        <Card>
          <CardContent className="py-8 text-center text-sm text-muted-foreground">
            Unknown stage type: {stageType}
          </CardContent>
        </Card>
      )
  }
}

export default function PipelineDetailPage() {
  const params = useParams()
  const pipelineId = params.id as string

  const [selectedTrackId, setSelectedTrackId] = useState<string | null>(null)
  const [selectedStageId, setSelectedStageId] = useState<string | null>(null)

  const { data: pipeline, isLoading } = trpc.pipeline.getDraft.useQuery({
    id: pipelineId,
  })

  // Auto-select first track and stage
  useEffect(() => {
    if (pipeline && pipeline.tracks.length > 0 && !selectedTrackId) {
      const firstTrack = pipeline.tracks[0]
      setSelectedTrackId(firstTrack.id)
      if (firstTrack.stages.length > 0) {
        setSelectedStageId(firstTrack.stages[0].id)
      }
    }
  }, [pipeline, selectedTrackId])

  const publishMutation = trpc.pipeline.publish.useMutation({
    onSuccess: () => toast.success('Pipeline published'),
    onError: (err) => toast.error(err.message),
  })

  const updateMutation = trpc.pipeline.update.useMutation({
    onSuccess: () => toast.success('Pipeline updated'),
    onError: (err) => toast.error(err.message),
  })

  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 (!pipeline) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-3">
          <Link href="/admin/rounds/pipelines">
            <Button variant="ghost" size="icon">
              <ArrowLeft className="h-4 w-4" />
            </Button>
          </Link>
          <div>
            <h1 className="text-xl font-bold">Pipeline Not Found</h1>
            <p className="text-sm text-muted-foreground">
              The requested pipeline does not exist
            </p>
          </div>
        </div>
      </div>
    )
  }

  const selectedTrack = pipeline.tracks.find((t) => t.id === selectedTrackId)
  const selectedStage = selectedTrack?.stages.find(
    (s) => s.id === selectedStageId
  )

  const handleTrackChange = (trackId: string) => {
    setSelectedTrackId(trackId)
    const track = pipeline.tracks.find((t) => t.id === trackId)
    if (track && track.stages.length > 0) {
      setSelectedStageId(track.stages[0].id)
    } else {
      setSelectedStageId(null)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Link href="/admin/rounds/pipelines">
            <Button variant="ghost" size="icon">
              <ArrowLeft className="h-4 w-4" />
            </Button>
          </Link>
          <div>
            <div className="flex items-center gap-2">
              <h1 className="text-xl font-bold">{pipeline.name}</h1>
              <Badge
                variant="secondary"
                className={cn(
                  'text-[10px]',
                  statusColors[pipeline.status] ?? ''
                )}
              >
                {pipeline.status}
              </Badge>
            </div>
            <p className="text-sm text-muted-foreground font-mono">
              {pipeline.slug}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <Link href={`/admin/rounds/pipeline/${pipelineId}/edit` as Route}>
            <Button variant="outline" size="sm">
              <Edit className="h-4 w-4 mr-1" />
              Edit
            </Button>
          </Link>
          <Link href={`/admin/rounds/pipeline/${pipelineId}/advanced` as Route}>
            <Button variant="outline" size="sm">
              <Settings2 className="h-4 w-4 mr-1" />
              Advanced
            </Button>
          </Link>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="icon" className="h-8 w-8">
                <MoreHorizontal className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              {pipeline.status === 'DRAFT' && (
                <DropdownMenuItem
                  disabled={publishMutation.isPending}
                  onClick={() =>
                    publishMutation.mutate({ id: pipelineId })
                  }
                >
                  {publishMutation.isPending ? (
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  ) : (
                    <Rocket className="h-4 w-4 mr-2" />
                  )}
                  Publish
                </DropdownMenuItem>
              )}
              {pipeline.status === 'ACTIVE' && (
                <DropdownMenuItem
                  disabled={updateMutation.isPending}
                  onClick={() =>
                    updateMutation.mutate({
                      id: pipelineId,
                      status: 'CLOSED',
                    })
                  }
                >
                  Close Pipeline
                </DropdownMenuItem>
              )}
              <DropdownMenuSeparator />
              <DropdownMenuItem
                disabled={updateMutation.isPending}
                onClick={() =>
                  updateMutation.mutate({
                    id: pipelineId,
                    status: 'ARCHIVED',
                  })
                }
              >
                <Archive className="h-4 w-4 mr-2" />
                Archive
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Pipeline Summary */}
      <div className="grid gap-4 sm:grid-cols-3">
        <Card>
          <CardContent className="pt-4">
            <div className="flex items-center gap-2">
              <Layers className="h-4 w-4 text-blue-500" />
              <span className="text-sm font-medium">Tracks</span>
            </div>
            <p className="text-2xl font-bold mt-1">{pipeline.tracks.length}</p>
            <p className="text-xs text-muted-foreground">
              {pipeline.tracks.filter((t) => t.kind === 'MAIN').length} main,{' '}
              {pipeline.tracks.filter((t) => t.kind === 'AWARD').length} award
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-4">
            <div className="flex items-center gap-2">
              <GitBranch className="h-4 w-4 text-purple-500" />
              <span className="text-sm font-medium">Stages</span>
            </div>
            <p className="text-2xl font-bold mt-1">
              {pipeline.tracks.reduce((sum, t) => sum + t.stages.length, 0)}
            </p>
            <p className="text-xs text-muted-foreground">across all tracks</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-4">
            <div className="flex items-center gap-2">
              <GitBranch className="h-4 w-4 text-emerald-500" />
              <span className="text-sm font-medium">Transitions</span>
            </div>
            <p className="text-2xl font-bold mt-1">
              {pipeline.tracks.reduce(
                (sum, t) =>
                  sum +
                  t.stages.reduce(
                    (s, stage) => s + stage.transitionsFrom.length,
                    0
                  ),
                0
              )}
            </p>
            <p className="text-xs text-muted-foreground">stage connections</p>
          </CardContent>
        </Card>
      </div>

      {/* Track Tabs */}
      {pipeline.tracks.length > 0 && (
        <Tabs
          value={selectedTrackId ?? undefined}
          onValueChange={handleTrackChange}
        >
          <TabsList className="w-full justify-start overflow-x-auto">
            {pipeline.tracks
              .sort((a, b) => a.sortOrder - b.sortOrder)
              .map((track) => (
                <TabsTrigger
                  key={track.id}
                  value={track.id}
                  className="flex items-center gap-1.5"
                >
                  <span>{track.name}</span>
                  <Badge
                    variant="outline"
                    className="text-[9px] h-4 px-1"
                  >
                    {track.kind}
                  </Badge>
                </TabsTrigger>
              ))}
          </TabsList>

          {pipeline.tracks.map((track) => (
            <TabsContent key={track.id} value={track.id} className="mt-4">
              {/* Track Info */}
              <Card className="mb-4">
                <CardHeader className="pb-2">
                  <div className="flex items-center justify-between">
                    <div>
                      <CardTitle className="text-sm">{track.name}</CardTitle>
                      <CardDescription className="font-mono text-xs">
                        {track.slug}
                      </CardDescription>
                    </div>
                    <div className="flex items-center gap-2">
                      {track.routingMode && (
                        <Badge variant="outline" className="text-[10px]">
                          {track.routingMode}
                        </Badge>
                      )}
                      {track.decisionMode && (
                        <Badge variant="outline" className="text-[10px]">
                          {track.decisionMode}
                        </Badge>
                      )}
                    </div>
                  </div>
                </CardHeader>
              </Card>

              {/* Stage Tabs within Track */}
              {track.stages.length > 0 ? (
                <Tabs
                  value={
                    selectedTrackId === track.id
                      ? selectedStageId ?? undefined
                      : undefined
                  }
                  onValueChange={setSelectedStageId}
                >
                  <TabsList className="w-full justify-start overflow-x-auto">
                    {track.stages
                      .sort((a, b) => a.sortOrder - b.sortOrder)
                      .map((stage) => (
                        <TabsTrigger
                          key={stage.id}
                          value={stage.id}
                          className="flex items-center gap-1.5"
                        >
                          <span>{stage.name}</span>
                          <Badge
                            variant="secondary"
                            className={cn(
                              'text-[9px] h-4 px-1',
                              stageTypeColors[stage.stageType] ?? ''
                            )}
                          >
                            {stage.stageType.replace('_', ' ')}
                          </Badge>
                        </TabsTrigger>
                      ))}
                  </TabsList>

                  {track.stages.map((stage) => (
                    <TabsContent
                      key={stage.id}
                      value={stage.id}
                      className="mt-4"
                    >
                      <StagePanel
                        stageId={stage.id}
                        stageType={stage.stageType}
                        configJson={
                          stage.configJson as Record<string, unknown> | null
                        }
                      />
                    </TabsContent>
                  ))}
                </Tabs>
              ) : (
                <Card>
                  <CardContent className="py-8 text-center text-sm text-muted-foreground">
                    No stages configured for this track
                  </CardContent>
                </Card>
              )}
            </TabsContent>
          ))}
        </Tabs>
      )}
    </div>
  )
}
