'use client'

import { useState, useTransition } from 'react'
import { Trash2, MoreHorizontal } from 'lucide-react'
import { useDroppable, useDraggable } from '@dnd-kit/core'
import { SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { toast } from 'sonner'
import { Badge } from '@/components/ui/badge'
import { CodeBadge } from '@/components/shared/code-badge'
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem,
  DropdownMenuTrigger, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent,
} from '@/components/ui/dropdown-menu'
import { PanelNavBar } from '@/components/shared/panel-nav-bar'
import { UserAvatar } from '@/components/shared/user-avatar'
import { DemoTooltip } from '@/components/shared/demo-tooltip'
import { useSprintStore } from '@/stores/sprint-store'
import { claimStoryAction, unclaimStoryAction, reassignStoryAction, claimAllUnassignedInActiveSprintAction } from '@/actions/stories'
import { cn } from '@/lib/utils'

const STATUS_COLORS: Record<string, string> = {
  OPEN: 'bg-status-todo/15 text-status-todo border-status-todo/30',
  IN_SPRINT: 'bg-status-in-progress/15 text-status-in-progress border-status-in-progress/30',
  DONE: 'bg-status-done/15 text-status-done border-status-done/30',
}
const STATUS_LABELS: Record<string, string> = { OPEN: 'Open', IN_SPRINT: 'In Sprint', DONE: 'Klaar' }

const PRIORITY_COLORS: Record<number, string> = {
  1: 'bg-priority-critical/15 text-priority-critical border-priority-critical/30',
  2: 'bg-priority-high/15 text-priority-high border-priority-high/30',
  3: 'bg-priority-medium/15 text-priority-medium border-priority-medium/30',
  4: 'bg-priority-low/15 text-priority-low border-priority-low/30',
}
const PRIORITY_LABELS: Record<number, string> = { 1: 'Kritiek', 2: 'Hoog', 3: 'Gemiddeld', 4: 'Laag' }

export interface SprintStory {
  id: string
  code: string | null
  title: string
  priority: number
  status: string
  taskCount: number
  doneCount: number
  assignee_id: string | null
  assignee_username: string | null
}

export interface ProductMember {
  userId: string
  username: string
}

export interface PbiWithStories {
  id: string
  code: string | null
  title: string
  stories: SprintStory[]
}

// --- Left panel: Sprint Backlog ---

function SortableSprintRow({
  story, isDemo, onRemove, onSelect, isSelected,
  currentUserId, productId, members, onAssigneeChange,
}: {
  story: SprintStory
  isDemo: boolean
  onRemove: () => void
  onSelect: () => void
  isSelected: boolean
  currentUserId: string
  productId: string
  members: ProductMember[]
  onAssigneeChange: (storyId: string, id: string | null, username: string | null) => void
}) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: story.id })
  const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.4 : 1 }
  const [, startTransition] = useTransition()

  function handleClaim(e: React.MouseEvent) {
    e.stopPropagation()
    const me = members.find(m => m.userId === currentUserId)
    onAssigneeChange(story.id, currentUserId, me?.username ?? null)
    startTransition(async () => {
      const result = await claimStoryAction(story.id, productId)
      if (!result.success) {
        onAssigneeChange(story.id, story.assignee_id, story.assignee_username)
        toast.error(result.error ?? 'Claimen mislukt')
      } else {
        toast.success('Story geclaimd')
      }
    })
  }

  function handleUnclaim(e: React.MouseEvent) {
    e.stopPropagation()
    onAssigneeChange(story.id, null, null)
    startTransition(async () => {
      const result = await unclaimStoryAction(story.id, productId)
      if (!result.success) {
        onAssigneeChange(story.id, story.assignee_id, story.assignee_username)
        toast.error(result.error ?? 'Teruggeven mislukt')
      }
    })
  }

  function handleReassign(e: React.MouseEvent, targetUserId: string, targetUsername: string) {
    e.stopPropagation()
    onAssigneeChange(story.id, targetUserId, targetUsername)
    startTransition(async () => {
      const result = await reassignStoryAction(story.id, productId, targetUserId)
      if (!result.success) {
        onAssigneeChange(story.id, story.assignee_id, story.assignee_username)
        toast.error(result.error ?? 'Toewijzen mislukt')
      } else {
        toast.success(`Toegewezen aan ${targetUsername}`)
      }
    })
  }

  return (
    <div
      ref={setNodeRef}
      style={style}
      onClick={onSelect}
      className={cn(
        'group flex items-start gap-3 px-4 py-2.5 border-b border-border cursor-pointer transition-colors',
        isSelected
          ? 'bg-primary-container text-primary-container-foreground'
          : 'hover:bg-surface-container'
      )}
    >
      {!isDemo && (
        <span
          {...attributes}
          {...listeners}
          aria-label="Versleep om te sorteren of naar Product Backlog"
          className="text-muted-foreground cursor-grab active:cursor-grabbing shrink-0 select-none text-sm mt-0.5"
          onClick={e => e.stopPropagation()}
        >
          ⠿
        </span>
      )}
      <div className="flex-1 min-w-0">
        <div className="flex items-start justify-between gap-2">
          <p className="text-sm truncate flex-1">{story.title}</p>
          {story.code && <CodeBadge code={story.code} className="shrink-0 mt-0.5" />}
        </div>
        <div className="flex items-center gap-1.5 mt-0.5">
          <Badge className={cn('text-[10px] px-1.5 py-0 border', PRIORITY_COLORS[story.priority])}>
            {PRIORITY_LABELS[story.priority]}
          </Badge>
          <span className="text-xs text-muted-foreground">{story.doneCount}/{story.taskCount} klaar</span>
        </div>
        <div className="flex items-center gap-1.5 mt-1">
          {story.assignee_id ? (
            <>
              <UserAvatar userId={story.assignee_id} username={story.assignee_username ?? '?'} size="xs" />
              <span className="text-xs text-muted-foreground truncate">{story.assignee_username}</span>
            </>
          ) : (
            <span className="text-xs text-muted-foreground italic">Niet geclaimd</span>
          )}
        </div>
      </div>
      <div className="flex items-center gap-1 shrink-0 mt-0.5" onClick={e => e.stopPropagation()}>
        <DemoTooltip show={isDemo}>
          <DropdownMenu>
            <DropdownMenuTrigger
              disabled={isDemo}
              className="opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-foreground p-0.5 rounded bg-transparent border-0 cursor-pointer"
              aria-label="Story opties"
            >
              <MoreHorizontal size={14} />
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" onClick={e => e.stopPropagation()}>
              {story.assignee_id !== currentUserId && (
                <DropdownMenuItem onClick={handleClaim}>Pak op</DropdownMenuItem>
              )}
              {story.assignee_id && (
                <DropdownMenuItem onClick={handleUnclaim}>Geef terug aan team</DropdownMenuItem>
              )}
              <DropdownMenuSub>
                <DropdownMenuSubTrigger>Wijs toe aan</DropdownMenuSubTrigger>
                <DropdownMenuSubContent>
                  {members.map(m => (
                    <DropdownMenuItem key={m.userId} onClick={e => handleReassign(e, m.userId, m.username)}>
                      <UserAvatar userId={m.userId} username={m.username} size="xs" />
                      <span>{m.username}</span>
                    </DropdownMenuItem>
                  ))}
                </DropdownMenuSubContent>
              </DropdownMenuSub>
            </DropdownMenuContent>
          </DropdownMenu>
        </DemoTooltip>
        {!isDemo && (
          <button
            onClick={e => { e.stopPropagation(); onRemove() }}
            className="opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-error"
            aria-label="Verwijder uit sprint"
          >
            <Trash2 size={14} />
          </button>
        )}
      </div>
    </div>
  )
}

interface SprintBacklogLeftProps {
  sprintId: string
  stories: SprintStory[]
  isDemo: boolean
  onRemove: (storyId: string) => void
  onSelect: (storyId: string) => void
  selectedStoryId: string | null
  currentUserId: string
  productId: string
  members: ProductMember[]
  onAssigneeChange: (storyId: string, id: string | null, username: string | null) => void
}

export function SprintBacklogLeft({
  sprintId, stories, isDemo, onRemove, onSelect, selectedStoryId,
  currentUserId, productId, members, onAssigneeChange,
}: SprintBacklogLeftProps) {
  const { sprintStoryOrder } = useSprintStore()
  const { setNodeRef, isOver } = useDroppable({ id: 'sprint-zone' })
  const [isPending, startTransition] = useTransition()

  const unassignedCount = stories.filter(s => s.assignee_id === null).length
  const currentUserUsername = members.find(m => m.userId === currentUserId)?.username ?? null

  function handleClaimAll() {
    const unassigned = stories.filter(s => s.assignee_id === null)
    unassigned.forEach(s => onAssigneeChange(s.id, currentUserId, currentUserUsername))
    startTransition(async () => {
      const result = await claimAllUnassignedInActiveSprintAction(productId)
      if (!result.success) {
        unassigned.forEach(s => onAssigneeChange(s.id, null, null))
        toast.error(result.error ?? 'Claimen mislukt')
      } else {
        toast.success(`${result.count} ${result.count === 1 ? 'story' : 'stories'} geclaimd`)
      }
    })
  }

  const storyMap = Object.fromEntries(stories.map(s => [s.id, s]))
  const order = sprintStoryOrder[sprintId] ?? stories.map(s => s.id)
  const orderedStories = order.map(id => storyMap[id]).filter(Boolean)

  return (
    <div className="flex flex-col h-full">
      <PanelNavBar
        title="Sprint Backlog"
        actions={
          <DemoTooltip show={isDemo}>
            <button
              onClick={handleClaimAll}
              disabled={isDemo || unassignedCount === 0 || isPending}
              className="text-xs text-primary hover:text-primary/80 disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap"
            >
              {isPending ? 'Claimen…' : `Claim ongeclaimd (${unassignedCount})`}
            </button>
          </DemoTooltip>
        }
      />
      <div
        ref={setNodeRef}
        className={cn(
          'flex-1 overflow-y-auto transition-colors',
          isOver && 'bg-primary/5 ring-2 ring-inset ring-primary/20 rounded'
        )}
      >
        {orderedStories.length === 0 ? (
          <p className={cn(
            'text-sm text-muted-foreground text-center mt-8 px-4',
            isOver && 'text-primary'
          )}>
            {isOver ? 'Loslaten om toe te voegen aan Sprint' : 'Geen stories in de Sprint. Sleep stories vanuit het linkerpaneel.'}
          </p>
        ) : (
          <SortableContext items={orderedStories.map(s => s.id)} strategy={verticalListSortingStrategy}>
            {orderedStories.map(story => (
              <SortableSprintRow
                key={story.id}
                story={story}
                isDemo={isDemo}
                onRemove={() => onRemove(story.id)}
                onSelect={() => onSelect(story.id)}
                isSelected={selectedStoryId === story.id}
                currentUserId={currentUserId}
                productId={productId}
                members={members}
                onAssigneeChange={onAssigneeChange}
              />
            ))}
          </SortableContext>
        )}
      </div>
    </div>
  )
}

// --- Right panel: Product Backlog grouped by PBI ---

function DraggablePbiStoryRow({
  story,
  isDemo,
  onAdd,
}: {
  story: SprintStory
  isDemo: boolean
  onAdd: () => void
}) {
  const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id: `pb:${story.id}` })
  const style = transform
    ? { transform: `translate3d(${transform.x}px, ${transform.y}px, 0)`, zIndex: 50, position: 'relative' as const }
    : undefined

  return (
    <div
      ref={setNodeRef}
      style={style}
      onClick={!isDemo ? onAdd : undefined}
      className={cn(
        'flex items-center gap-3 px-6 py-2 border-b border-border/50 transition-colors',
        !isDemo && 'cursor-pointer hover:bg-primary/5',
        isDemo && 'opacity-60',
        isDragging && 'opacity-40'
      )}
    >
      {!isDemo && (
        <span
          {...attributes}
          {...listeners}
          aria-label="Sleep naar Sprint Backlog"
          className="text-muted-foreground cursor-grab active:cursor-grabbing shrink-0 select-none text-sm"
          onClick={e => e.stopPropagation()}
        >
          ⠿
        </span>
      )}
      <div className="flex-1 min-w-0">
        <div className="flex items-start justify-between gap-2">
          <p className="text-sm truncate flex-1">{story.title}</p>
          {story.code && <CodeBadge code={story.code} className="shrink-0 mt-0.5" />}
        </div>
        <Badge className={cn('text-[10px] px-1.5 py-0 border mt-0.5', STATUS_COLORS[story.status])}>
          {STATUS_LABELS[story.status]}
        </Badge>
      </div>
      {!isDemo && (
        <span className="text-xs text-muted-foreground shrink-0">+ toevoegen</span>
      )}
    </div>
  )
}

interface SprintBacklogRightProps {
  pbisWithStories: PbiWithStories[]
  sprintStoryIds: Set<string>
  isDemo: boolean
  onAdd: (storyId: string) => void
}

export function SprintBacklogRight({ pbisWithStories, sprintStoryIds, isDemo, onAdd }: SprintBacklogRightProps) {
  const [collapsed, setCollapsed] = useState<Set<string>>(new Set())
  const { setNodeRef, isOver } = useDroppable({ id: 'backlog-zone' })

  function toggle(pbiId: string) {
    setCollapsed(prev => {
      const next = new Set(prev)
      if (next.has(pbiId)) { next.delete(pbiId) } else { next.add(pbiId) }
      return next
    })
  }

  return (
    <div className="flex flex-col h-full">
      <PanelNavBar title="Product Backlog" />
      <div
        ref={setNodeRef}
        className={cn(
          'flex-1 overflow-y-auto py-2 transition-colors',
          isOver && 'bg-error/5 ring-2 ring-inset ring-error/20 rounded'
        )}
      >
        {pbisWithStories.map(pbi => (
          <div key={pbi.id}>
            <button
              onClick={() => toggle(pbi.id)}
              className="w-full flex items-center gap-2 px-4 py-1.5 hover:bg-surface-container transition-colors text-left"
            >
              <span className="text-xs">{collapsed.has(pbi.id) ? '▶' : '▼'}</span>
              <span className="text-sm font-medium truncate flex-1">{pbi.title}</span>
              {pbi.code && <CodeBadge code={pbi.code} />}
              <span className="text-xs text-muted-foreground">{pbi.stories.length}</span>
            </button>

            {!collapsed.has(pbi.id) && pbi.stories.map(story => {
              const inSprint = sprintStoryIds.has(story.id)
              if (inSprint) {
                return (
                  <div
                    key={story.id}
                    className="flex items-center gap-3 px-6 py-2 border-b border-border/50 opacity-40"
                  >
                    <div className="w-[14px] shrink-0" />
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between gap-2">
                        <p className="text-sm truncate flex-1">{story.title}</p>
                        {story.code && <CodeBadge code={story.code} className="shrink-0 mt-0.5" />}
                      </div>
                      <Badge className={cn('text-[10px] px-1.5 py-0 border mt-0.5', STATUS_COLORS[story.status])}>
                        {STATUS_LABELS[story.status]}
                      </Badge>
                    </div>
                    <span className="text-xs text-muted-foreground shrink-0">In Sprint</span>
                  </div>
                )
              }
              return <DraggablePbiStoryRow key={story.id} story={story} isDemo={isDemo} onAdd={() => onAdd(story.id)} />
            })}
          </div>
        ))}
      </div>
    </div>
  )
}
