'use client'

import { useState } from 'react'
import { Button } from '../components/ui/Button.js'

interface NavNode {
  id: string
  label: string
  url: string
  children: NavNode[]
}

export interface NavBuilderFieldProps {
  label: string
  value?: NavNode[]
  onChange: (value: NavNode[]) => void
  helpText?: string
}

export function NavBuilderField({ label, value = [], onChange, helpText }: NavBuilderFieldProps) {
  function addItem() {
    onChange([...value, { id: crypto.randomUUID(), label: 'New Item', url: '/', children: [] }])
  }

  function removeItem(id: string) {
    onChange(value.filter((n) => n.id !== id))
  }

  function renderNode(node: NavNode, depth: number) {
    return (
      <div
        key={node.id}
        className="rounded-md border border-[var(--border)] bg-[var(--card)] p-3"
        style={{ marginLeft: depth * 24 }}
      >
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2 text-sm">
            <svg
              className="h-4 w-4 text-[var(--muted-foreground)]"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path strokeLinecap="round" strokeLinejoin="round" d="M4 6h16M4 12h16M4 18h16" />
            </svg>
            <span className="font-medium">{node.label}</span>
            <span className="text-xs text-[var(--muted-foreground)]">{node.url}</span>
          </div>
          <button
            type="button"
            onClick={() => removeItem(node.id)}
            className="text-xs text-[var(--muted-foreground)] hover:text-[var(--destructive)]"
          >
            Remove
          </button>
        </div>
        {node.children.length > 0 && (
          <div className="mt-2 space-y-2">
            {node.children.map((child) => renderNode(child, depth + 1))}
          </div>
        )}
      </div>
    )
  }

  return (
    <div>
      <label className="mb-2 block text-sm font-medium">{label}</label>
      <div className="space-y-2">{value.map((node) => renderNode(node, 0))}</div>
      <Button variant="secondary" size="sm" onClick={addItem} className="mt-2">
        Add Nav Item
      </Button>
      {helpText && <p className="mt-1 text-xs text-[var(--muted-foreground)]">{helpText}</p>}
    </div>
  )
}
