import React from "react"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Badge } from "@/components/ui/badge"
import { Stage } from "@/api/rtk/pipelines-api"
import { StageWithSubStages } from "@/components/pipelines/stage-with-sub-stages"
import { useGetPipelinesQuery } from "@/api/rtk/pipelines-api"

interface StagesWithSubStagesViewerDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  pipeline: any
  stages: { id: string; name: string }[]
}

export function StagesWithSubStagesViewerDialog({
  open,
  onOpenChange,
  pipeline,
  stages,
}: StagesWithSubStagesViewerDialogProps) {
  const { data: pipelines = [] } = useGetPipelinesQuery()
  
  // Find the full pipeline data with stage details
  const fullPipeline = pipelines.find(p => p.id === pipeline.id)
  
  const handleSubStageUpdate = () => {
    // Force refresh of pipeline data
    // This will trigger a refetch of the pipeline data
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[80vh]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <span>{pipeline.name}</span>
            <Badge variant="outline" className="text-xs">
              {stages.length} stages
            </Badge>
          </DialogTitle>
        </DialogHeader>
        
        <ScrollArea className="h-[60vh] pr-4">
          <div className="space-y-4">
            {stages.map((stage: any) => {
              // Find the full stage data from the pipeline
              const fullStage = fullPipeline?.stages?.find((s: any) => s.id === stage.id)
              
              return (
                <StageWithSubStages
                  key={stage.id}
                  stage={{
                    id: stage.id,
                    name: stage.name,
                    color: (fullStage as any)?.color,
                    prob: (fullStage as any)?.prob,
                    stageNameId: (fullStage as any)?.stageNameId,
                    subStages: (fullStage as any)?.subStages || []
                  }}
                  onSubStageUpdate={handleSubStageUpdate}
                />
              )
            })}
            
            {stages.length === 0 && (
              <div className="text-center py-8">
                <p className="text-muted-foreground">No stages found in this pipeline</p>
              </div>
            )}
          </div>
        </ScrollArea>
      </DialogContent>
    </Dialog>
  )
}
