import { useMemo } from 'react'
import { useKrateStore } from '../state/krateStore'
import { useCanvasStore } from '../state/canvasStore'
import { NAMESPACE_COLORS } from '../data/mockResources'

interface WindowInfo {
  type: string
  title: string
}

interface CreateKrateOptions {
  title: string
  type: string
  namespace?: string
  color?: string
  windows?: WindowInfo[]
}

export const useCreateKrate = () => {
  const addKrate = useKrateStore((state) => state.addKrate)
  const setCam = useCanvasStore((state) => state.setCam)
  const setZoom = useCanvasStore((state) => state.setZoom)

  const COLLISION_TOLERANCE = 20

  const findNonOverlappingPosition = (width: number, height: number, Krates: Map<string, any>): { x: number; y: number } => {

    const getAABB = (krate: any) => ({
      x1: krate.x - COLLISION_TOLERANCE,
      y1: krate.y - COLLISION_TOLERANCE,
      x2: krate.x + krate.width + COLLISION_TOLERANCE,
      y2: krate.y + krate.height + COLLISION_TOLERANCE,
    })

    const rectsOverlap = (r1: any, r2: any) => {
      return r1.x1 < r2.x2 && r1.x2 > r2.x1 && r1.y1 < r2.y2 && r1.y2 > r2.y1
    }

    const checkOverlap = (x: number, y: number, Krates: Map<string, any>): boolean => {
      const newRect = {
        x1: x - COLLISION_TOLERANCE,
        y1: y - COLLISION_TOLERANCE,
        x2: x + width + COLLISION_TOLERANCE,
        y2: y + height + COLLISION_TOLERANCE,
      }

      for (const krate of Krates.values()) {
        const existingRect = getAABB(krate)
        if (rectsOverlap(newRect, existingRect)) {
          return true
        }
      }
      return false
    }

    let x = 100
    let y = 100
    let attempts = 0
    const maxAttempts = 100

    while (attempts < maxAttempts) {
      if (!checkOverlap(x, y, Krates)) {
        return { x, y }
      }

      x += width / 2
      if (x > 8000) {
        x = 100
        y += height / 2
      }
      attempts++
    }

    return { x, y }
  }

  const createKrate = (options: CreateKrateOptions) => {
    const { title, type, namespace, color, windows } = options

    const Krates = useKrateStore.getState().krates
    const { x, y } = findNonOverlappingPosition(800, 600, Krates)

    const krateColor = color || (namespace ? NAMESPACE_COLORS[namespace] || '#6fb1ff' : '#6fb1ff')

    const defaultWindows: Map<string, any> = new Map()

    if (windows && windows.length > 0) {
      windows.forEach((win, index) => {
        defaultWindows.set(`${title}-${index}`, {
          id: `${title}-${index}`,
          type: win.type,
          title: win.title,
          x: index * 412,
          y: 0,
          width: 380,
          height: 360,
          color: krateColor,
        })
      })
    } else {
      const windowTypes = type === 'namespace' ? ['collection'] : ['logs', 'describe']

      windowTypes.forEach((winType, index) => {
        defaultWindows.set(`${title}-${winType}`, {
          id: `${title}-${winType}`,
          type: winType,
          title: winType === 'logs' ? 'Logs' : 'Describe',
          x: index * 412,
          y: 0,
          width: 380,
          height: 360,
          color: krateColor,
        })
      })
    }

    const newKrate = {
      id: `krate-${Date.now()}`,
      type,
      title,
      x,
      y,
      width: 800,
      height: 600,
      color: krateColor,
      minimized: false,
      windowLayout: {
        cols: 2,
        rows: 2,
        cells: new Map(),
      },
      windows: defaultWindows,
    }

    addKrate(newKrate)

    setCam(x + 400, y + 300)
    setZoom(0.92)
  }

  return useMemo(
    () => ({
      createKrate,
    }),
    []
  )
}
