"use client"

import * as React from "react"
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { ArrowRightLeft, Loader2, Trash2, Users } from "lucide-react"
import { cn } from "@/lib/utils"
import { useGetPipelinesQuery } from "@/api/rtk/pipelines-api"
import { useAuthToken } from "@/hooks/use-auth-token"

export interface StageOption {
  id: string
  name: string
  color?: string
}

export interface TransferItem {
  id: string
  name: string
  currentStage?: string
  subtext?: string
}

interface Props {
  open: boolean
  onClose: () => void
  /** Extra stages to merge in (e.g. activeBoard.stages for deals). API stages take precedence. */
  extraStages?: StageOption[]
  selectedCount: number
  entityLabel?: string
  currentStageId?: string
  items?: TransferItem[]
  onRemoveItem?: (id: string) => void
  onTransfer: (stageId: string, stageName: string) => Promise<void>
}

const STAGE_COLORS: Record<string, string> = {
  prospecting: "#6C63FF",
  "proposal sent": "#F59E0B",
  qualified: "#8B83FF",
  negotiation: "#FF8C42",
  "closed lost": "#FF6B6B",
  "closed won": "#22C55E",
  customer: "#10B981",
  "new lead": "#6C63FF",
}

function colorFor(name: string, fallback?: string) {
  return STAGE_COLORS[name.toLowerCase()] ?? fallback ?? "#6C63FF"
}

export function BulkStageTransferModal({
  open,
  onClose,
  extraStages = [],
  selectedCount,
  entityLabel = "item",
  currentStageId,
  items = [],
  onRemoveItem,
  onTransfer,
}: Props) {
  const { token } = useAuthToken()
  const [targetStageId, setTargetStageId] = React.useState("")
  const [isTransferring, setIsTransferring] = React.useState(false)

  const { data: pipelines, isLoading: pipelinesLoading } = useGetPipelinesQuery(undefined, {
    skip: !open || !token,
  })

  const apiStages = React.useMemo<StageOption[]>(() => {
    if (!pipelines?.length) return []
    const seen = new Set<string>()
    const result: StageOption[] = []
    for (const pipeline of pipelines) {
      const raw = (pipeline.stages ?? []) as Array<{ id?: string; name?: string; color?: string }>
      for (const s of raw) {
        const name = s.name ?? s.id ?? ""
        const id = s.id ?? name
        if (!name || seen.has(name.toLowerCase())) continue
        seen.add(name.toLowerCase())
        result.push({ id, name, color: s.color ?? colorFor(name) })
      }
    }
    return result
  }, [pipelines])

  const stages = React.useMemo<StageOption[]>(() => {
    if (apiStages.length === 0) {
      const seen = new Set<string>()
      return extraStages.filter(s => {
        const key = s.name.toLowerCase()
        if (seen.has(key)) return false
        seen.add(key)
        return true
      })
    }
    const seen = new Set(apiStages.map(s => s.name.toLowerCase()))
    return [...apiStages, ...extraStages.filter(s => !seen.has(s.name.toLowerCase()))]
  }, [apiStages, extraStages])

  React.useEffect(() => { if (open) setTargetStageId("") }, [open])

  const selectedStage = stages.find(s => s.id === targetStageId)

  const handleTransfer = async () => {
    if (!selectedStage) return
    setIsTransferring(true)
    try {
      await onTransfer(selectedStage.id, selectedStage.name)
      onClose()
    } finally {
      setIsTransferring(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="sm:max-w-xl md:max-w-2xl lg:max-w-3xl p-0 overflow-hidden max-h-[90vh] flex flex-col" aria-describedby={undefined}>
        {/* Header */}
        <div className="flex items-center gap-3 px-6 pt-6 pb-4 border-b border-border/40 bg-accent/5 shrink-0">
          <div className="size-9 rounded-xl bg-accent flex items-center justify-center shrink-0">
            <ArrowRightLeft size={16} className="text-white" />
          </div>
          <div>
            <DialogTitle className="text-[16px] font-extrabold font-['Lexend'] text-text leading-tight">
              Bulk Stage Transfer
            </DialogTitle>
            <p className="text-[12px] text-gray-500 font-['Lexend_Deca'] mt-0.5">
              Move {selectedCount} {entityLabel}{selectedCount > 1 ? "s" : ""} to a new stage
            </p>
          </div>
        </div>

        <div className="flex flex-col md:flex-row flex-1 overflow-hidden min-h-[300px]">
          {/* Selected Items List */}
          {items.length > 0 && (
            <div className="flex-1 border-r border-border/40 bg-gray-50/30 overflow-y-auto scrollbar-themed p-4">
              <p className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] mb-3">
                Selected {entityLabel}s ({items.length})
              </p>
              <div className="space-y-2">
                {items.map((item) => (
                  <div 
                    key={item.id} 
                    className="flex items-center justify-between gap-3 p-2.5 rounded-xl bg-white border border-border/60 group hover:border-accent/40 hover:shadow-sm transition-all"
                  >
                    <div className="flex items-center gap-2.5 overflow-hidden">
                      <div className="size-8 rounded-lg bg-accent/5 flex items-center justify-center shrink-0 border border-accent/10">
                        <Users size={14} className="text-accent" />
                      </div>
                      <div className="min-w-0">
                        <p className="text-[12px] font-bold font-['Lexend'] text-text truncate">
                          {item.name}
                        </p>
                        <div className="flex items-center gap-2 mt-0.5">
                          {item.currentStage && (
                            <span className="text-[10px] font-medium text-gray-400 bg-gray-100 px-1.5 py-0.5 rounded uppercase tracking-tight">
                              {item.currentStage}
                            </span>
                          )}
                          {item.subtext && <span className="text-[10px] text-gray-400 truncate">{item.subtext}</span>}
                        </div>
                      </div>
                    </div>
                    {onRemoveItem && (
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => onRemoveItem(item.id)}
                        className="size-7 opacity-100 hover:bg-destructive/10 hover:text-destructive transition-all"
                      >
                        <Trash2 size={13} />
                      </Button>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Stage selection */}
          <div className={cn("flex-1 px-6 py-5 overflow-y-auto scrollbar-themed", !items.length && "md:w-full")}>
            <p className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] mb-3">
              Select target stage
            </p>

            {pipelinesLoading ? (
              <div className="grid grid-cols-1 gap-2">
                {Array.from({ length: 6 }).map((_, i) => (
                  <div key={i} className="h-10 rounded-xl bg-border/30 animate-pulse" />
                ))}
              </div>
            ) : stages.length === 0 ? (
              <p className="text-[13px] text-gray-400 text-center py-6">No stages found</p>
            ) : (
              <div className="grid grid-cols-1 gap-2">
                {stages.map(stage => {
                  const isSelected = targetStageId === stage.id
                  const isCurrent = stage.id === currentStageId
                  return (
                    <button
                      key={stage.id}
                      disabled={isCurrent}
                      onClick={() => setTargetStageId(stage.id)}
                      className={cn(
                        "flex items-center gap-2.5 px-3 py-2.5 rounded-xl border text-left transition-all duration-150",
                        isSelected
                          ? "border-accent bg-accent/10 shadow-sm"
                          : "border-border/60 bg-white hover:border-accent/40 hover:bg-accent/5",
                        isCurrent && "opacity-60 cursor-not-allowed bg-gray-50/50 grayscale-[0.2]"
                      )}
                    >
                      <span
                        className="size-2.5 rounded-full shrink-0"
                        style={{ backgroundColor: stage.color || "#6C63FF" }}
                      />
                      <span className={cn(
                        "text-[12px] font-bold font-['Lexend'] truncate",
                        isSelected ? "text-accent" : "text-text",
                        isCurrent && "text-gray-400"
                      )}>
                        {stage.name}
                      </span>
                      {isCurrent && (
                        <span className="ml-auto text-[9px] font-bold bg-gray-100 text-gray-400 px-1.5 py-0.5 rounded-md uppercase tracking-wider font-['Lexend_Deca']">
                          Current
                        </span>
                      )}
                      {isSelected && (
                        <span className="ml-auto size-4 rounded-full bg-accent flex items-center justify-center shrink-0">
                          <svg width="8" height="8" viewBox="0 0 8 8" fill="none">
                            <path d="M1.5 4L3.5 6L6.5 2" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                          </svg>
                        </span>
                      )}
                    </button>
                  )
                })}
              </div>
            )}
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-2 px-6 py-4 border-t border-border/40 shrink-0">
          <Button variant="ghost" size="sm" onClick={onClose} disabled={isTransferring}>
            Cancel
          </Button>
          <Button
            size="sm"
            onClick={handleTransfer}
            disabled={!targetStageId || isTransferring || (items.length === 0 && selectedCount > 0)}
            className="gap-1.5 min-w-28"
          >
            {isTransferring
              ? <><Loader2 size={13} className="animate-spin" /> Transferring…</>
              : <><ArrowRightLeft size={13} /> Transfer {selectedCount}</>
            }
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  )
}

