import React, { useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { ChevronDown, ChevronRight, Plus } from "lucide-react"
import { Stage, SubStage } from "@/api/rtk/pipelines-api"
import { useGetSubStagesByStageNameQuery } from "@/api/rtk/pipelines-api"
import { SubStageList } from "./sub-stage-list"

interface StageWithSubStagesProps {
  stage: Stage
  onSubStageUpdate: () => void
}

export function StageWithSubStages({ stage, onSubStageUpdate }: StageWithSubStagesProps) {
  const [isExpanded, setIsExpanded] = useState(false)
  
  const { data: subStages = [], isLoading: isLoadingSubStages, refetch: refetchSubStages } = 
    useGetSubStagesByStageNameQuery(stage.stageNameId || stage.id)

  const handleToggleExpand = () => {
    setIsExpanded(!isExpanded)
  }

  const handleSubStageUpdate = () => {
    refetchSubStages()
    onSubStageUpdate()
  }

  return (
    <Card className="mb-4">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Button
              variant="ghost"
              size="sm"
              onClick={handleToggleExpand}
              className="p-1 h-6 w-6"
            >
              {isExpanded ? (
                <ChevronDown className="h-4 w-4" />
              ) : (
                <ChevronRight className="h-4 w-4" />
              )}
            </Button>
            <div className="flex items-center gap-2">
              {stage.color && (
                <div
                  className="w-3 h-3 rounded-full border"
                  style={{ backgroundColor: stage.color }}
                />
              )}
              <CardTitle className="text-base">{stage.name}</CardTitle>
            </div>
            <div className="flex items-center gap-2">
              {stage.prob !== undefined && (
                <Badge variant="secondary">
                  {stage.prob}%
                </Badge>
              )}
              {subStages.length > 0 && (
                <Badge variant="outline">
                  {subStages.length} sub-stages
                </Badge>
              )}
            </div>
          </div>
        </div>
      </CardHeader>
      
      {isExpanded && (
        <CardContent className="pt-0">
          <SubStageList
            stageNameId={stage.stageNameId || stage.id}
            subStages={subStages}
            isLoading={isLoadingSubStages}
            onRefresh={handleSubStageUpdate}
          />
        </CardContent>
      )}
    </Card>
  )
}
