import { Check, RefreshCw, SkipForward, ChevronRight, ChevronLeft, Zap, Square } from 'lucide-react'
import { useAIFlowBuilderStore } from '@/store/aiFlowBuilderStore'
import { GeneratingAnimation } from './GeneratingAnimation'
import { cn } from '@/lib/utils'

export function BranchDetailView() {
  const {
    selectedBranches,
    currentBranchIndex,
    generateBranchDetail,
    assemble,
    isLoading,
    error,
    phase,
    setError,
    isGeneratingAll,
    generateAllBranchDetails,
    cancelGenerateAll,
  } = useAIFlowBuilderStore()

  const viewingIndex = currentBranchIndex
  const setViewingIndex = (i: number) => useAIFlowBuilderStore.setState({ currentBranchIndex: i })
  const currentBranch = selectedBranches[viewingIndex]

  const allBranchesHaveDetail = selectedBranches.every((b) => b.steps)
  const branchesWithDetail = selectedBranches.filter((b) => b.steps).length

  const handleGenerate = async (branchName: string) => {
    setError(null)
    await generateBranchDetail(branchName)
  }

  const handleAssemble = async () => {
    await assemble()
  }

  if (phase === 'generating' && isLoading) {
    return (
      <GeneratingAnimation
        branchContext={
          isGeneratingAll
            ? {
                current: selectedBranches.filter((b) => b.steps).length + 1,
                total: selectedBranches.length,
              }
            : undefined
        }
      />
    )
  }

  return (
    <div className="flex flex-col gap-4">

      {/* Content area */}
      <div className="space-y-4">
        {/* Branch tabs */}
        <div className="flex items-center gap-2 overflow-x-auto pb-1">
          {selectedBranches.map((branch, i) => (
            <button
              key={branch.name}
              type="button"
              onClick={() => setViewingIndex(i)}
              className={cn(
                'flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors',
                viewingIndex === i
                  ? 'border-primary/30 bg-primary/10 text-foreground'
                  : 'border-border text-muted-foreground hover:bg-accent',
                branch.steps && 'pr-2'
              )}
            >
              {branch.name}
              {branch.steps && (
                <Check className="h-3 w-3 text-green-400" />
              )}
            </button>
          ))}
        </div>

        {/* Current branch detail */}
        {currentBranch && (
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-sm font-medium text-foreground">{currentBranch.name}</h3>
                <p className="text-xs text-muted-foreground">{currentBranch.description}</p>
              </div>
            </div>

            {currentBranch.steps ? (
              <div className="space-y-3">
                {/* Mini tree preview */}
                <div className="max-h-48 overflow-y-auto rounded-lg border border-border bg-accent/30 p-3">
                  <NodePreview node={currentBranch.steps} depth={0} />
                </div>

                <div className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={() => handleGenerate(currentBranch.name)}
                    disabled={isLoading || isGeneratingAll}
                    className="flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50"
                  >
                    <RefreshCw className="h-3 w-3" />
                    Regenerate
                  </button>
                </div>
              </div>
            ) : (
              <div className="flex flex-col items-center gap-4 rounded-lg border border-dashed border-border bg-accent/20 py-8">
                <p className="text-sm text-muted-foreground">
                  Generate AI detail for this branch
                </p>

                {/* Generate All — primary action, shown when multiple branches remain */}
                {selectedBranches.filter((b) => !b.steps).length > 1 && (
                  isGeneratingAll ? (
                    <button
                      type="button"
                      onClick={cancelGenerateAll}
                      className="flex items-center gap-2 rounded-lg border border-red-400/30 bg-red-400/10 px-5 py-2.5 text-sm font-medium text-red-400 hover:bg-red-400/20"
                    >
                      <Square className="h-4 w-4" />
                      Stop Generating
                    </button>
                  ) : (
                    <button
                      type="button"
                      onClick={generateAllBranchDetails}
                      disabled={isLoading}
                      className="flex items-center gap-2 rounded-lg bg-gradient-brand px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-primary/20 hover:opacity-90 disabled:opacity-50"
                    >
                      <Zap className="h-4 w-4" />
                      Generate All {selectedBranches.filter((b) => !b.steps).length} Branches
                    </button>
                  )
                )}

                {/* Divider + secondary actions */}
                {selectedBranches.filter((b) => !b.steps).length > 1 && (
                  <div className="flex items-center gap-3 text-xs text-muted-foreground">
                    <div className="h-px w-8 bg-border" />
                    or
                    <div className="h-px w-8 bg-border" />
                  </div>
                )}

                <div className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={() => handleGenerate(currentBranch.name)}
                    disabled={isLoading || isGeneratingAll}
                    className="flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50"
                  >
                    Generate this branch
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      if (viewingIndex < selectedBranches.length - 1) {
                        setViewingIndex(viewingIndex + 1)
                      }
                    }}
                    disabled={isGeneratingAll}
                    className="flex items-center gap-1 rounded-lg border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent disabled:opacity-50"
                  >
                    <SkipForward className="h-3 w-3" />
                    Skip
                  </button>
                </div>
              </div>
            )}
          </div>
        )}

        {/* Error */}
        {error && (
          <div className="rounded-lg border border-red-400/20 bg-red-400/5 px-3 py-2 text-sm text-red-400">
            {error}
          </div>
        )}
      </div>

      {/* Navigation — sticky so it's always visible */}
      <div className="sticky bottom-0 flex items-center justify-between border-t border-border bg-card pt-3 pb-1">
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => setViewingIndex(Math.max(0, viewingIndex - 1))}
            disabled={viewingIndex === 0}
            className="flex items-center gap-1 rounded-lg border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent disabled:opacity-30"
          >
            <ChevronLeft className="h-3.5 w-3.5" />
            Previous
          </button>
          <button
            type="button"
            onClick={() =>
              setViewingIndex(Math.min(selectedBranches.length - 1, viewingIndex + 1))
            }
            disabled={viewingIndex === selectedBranches.length - 1}
            className="flex items-center gap-1 rounded-lg border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent disabled:opacity-30"
          >
            Next
            <ChevronRight className="h-3.5 w-3.5" />
          </button>
        </div>

        <div className="flex items-center gap-3">
          <span className="text-xs text-muted-foreground">
            {branchesWithDetail}/{selectedBranches.length} detailed
          </span>
          <button
            type="button"
            onClick={handleAssemble}
            disabled={!allBranchesHaveDetail || isLoading}
            className={cn(
              'rounded-lg bg-gradient-brand px-4 py-2 text-sm font-medium text-white shadow-lg shadow-primary/20',
              allBranchesHaveDetail && !isLoading
                ? 'hover:opacity-90'
                : 'cursor-not-allowed opacity-50'
            )}
          >
            Assemble Tree
          </button>
        </div>
      </div>
    </div>
  )
}

/** Recursive mini-preview of a node tree */
function NodePreview({ node, depth }: { node: Record<string, unknown>; depth: number }) {
  const type = node.type as string
  const label =
    type === 'decision'
      ? (node.question as string)
      : (node.title as string) || 'Untitled'
  const children = (node.children as Record<string, unknown>[]) || []

  const typeColors: Record<string, string> = {
    decision: 'bg-blue-400',
    action: 'bg-amber-400',
    solution: 'bg-green-400',
  }

  return (
    <div style={{ marginLeft: depth * 16 }}>
      <div className="flex items-center gap-2 py-0.5">
        <div className={cn('h-2 w-2 rounded-full', typeColors[type] || 'bg-muted-foreground')} />
        <span className="text-xs text-foreground truncate">{label}</span>
        <span className="text-[10px] font-label text-muted-foreground">{type}</span>
      </div>
      {children.map((child) => (
        <NodePreview key={child.id as string ?? crypto.randomUUID()} node={child} depth={depth + 1} />
      ))}
    </div>
  )
}
