import type { ReactNode, ComponentProps } from 'react'
import { Panel, NodeResizer, type NodeProps, type PanelPosition } from '@xyflow/react'
import { BaseNode } from './base-node'
import { cn } from '@/lib/utils'

export type GroupNodeLabelProps = ComponentProps<'div'>

export function GroupNodeLabel({ children, className, ...props }: GroupNodeLabelProps) {
  return (
    <div className="h-full w-full" {...props}>
      <div className={cn('bg-card text-muted-foreground w-fit p-2 text-[10px] font-semibold uppercase tracking-wider', className)}>
        {children}
      </div>
    </div>
  )
}

export interface GroupNodeData {
  label?: string
  groupType?: string
  [key: string]: unknown
}

export type GroupNodeProps = Partial<NodeProps> & {
  label?: ReactNode
  position?: PanelPosition
}

function getLabelClassName(position?: PanelPosition): string {
  switch (position) {
    case 'top-left': return 'rounded-br-sm'
    case 'top-center': return 'rounded-b-sm'
    case 'top-right': return 'rounded-bl-sm'
    case 'bottom-left': return 'rounded-tr-sm'
    case 'bottom-right': return 'rounded-tl-sm'
    case 'bottom-center': return 'rounded-t-sm'
    default: return 'rounded-br-sm'
  }
}

export function GroupNode({ data, selected }: NodeProps) {
  const nodeData = data as unknown as GroupNodeData
  const label = nodeData.label || 'Group'

  return (
    <>
      <NodeResizer
        isVisible={selected}
        minWidth={150}
        minHeight={100}
        lineStyle={{ borderColor: 'var(--color-accent)', borderWidth: 1 }}
        handleStyle={{ width: 8, height: 8, borderColor: 'var(--color-accent)', background: 'var(--color-card)' }}
      />
      <BaseNode
        className={cn(
          'h-full w-full min-h-[100px] min-w-[150px] overflow-hidden rounded-lg bg-elevated/30 border-default/50',
          selected && 'border-accent',
        )}
      >
        <Panel className="m-0 p-0" position="top-left">
          <GroupNodeLabel className={getLabelClassName('top-left')}>
            {label}
          </GroupNodeLabel>
        </Panel>
      </BaseNode>
    </>
  )
}
