import { JSONUIRenderer } from '@/lib/json-ui'
import { UIComponent } from '@/lib/json-ui/schema'
import { toast } from 'sonner'
import { useKV } from '@github/spark/hooks'
import { useState } from 'react'

export function JSONDemoPage() {
  const [todos, setTodos] = useKV('json-demo-todos', [
    { id: 1, text: 'Design JSON schema', completed: true },
    { id: 2, text: 'Build atomic components', completed: false },
    { id: 3, text: 'Create custom hooks', completed: false },
  ])
  
  const [newTodo, setNewTodo] = useState('')

  const handleAction = (handler: any, event?: any) => {
    switch (handler.action) {
      case 'add-todo':
        if (newTodo.trim()) {
          setTodos((current: any) => [
            ...current,
            { id: Date.now(), text: newTodo, completed: false }
          ])
          setNewTodo('')
          toast.success('Todo added!')
        }
        break
      
      case 'toggle-todo':
        setTodos((current: any) =>
          current.map((todo: any) =>
            todo.id === handler.params?.id
              ? { ...todo, completed: !todo.completed }
              : todo
          )
        )
        break
      
      case 'delete-todo':
        setTodos((current: any) =>
          current.filter((todo: any) => todo.id !== handler.params?.id)
        )
        toast.success('Todo deleted')
        break
      
      case 'update-input':
        setNewTodo(event.target.value)
        break
    }
  }

  const pageSchema: UIComponent = {
    id: 'json-demo-page',
    type: 'div',
    className: 'h-full overflow-auto p-6',
    children: [
      {
        id: 'header',
        type: 'div',
        className: 'mb-6',
        children: [
          {
            id: 'title',
            type: 'h1',
            className: 'text-3xl font-bold mb-2',
            children: 'JSON-Driven UI Demo'
          },
          {
            id: 'description',
            type: 'p',
            className: 'text-muted-foreground',
            children: 'This entire page is built from a JSON schema - no JSX required!'
          }
        ]
      },
      {
        id: 'main-card',
        type: 'Card',
        className: 'max-w-2xl',
        children: [
          {
            id: 'card-header',
            type: 'CardHeader',
            children: [
              {
                id: 'card-title',
                type: 'CardTitle',
                children: 'Todo List'
              },
              {
                id: 'card-description',
                type: 'CardDescription',
                children: 'Manage your tasks with JSON-powered UI'
              }
            ]
          },
          {
            id: 'card-content',
            type: 'CardContent',
            className: 'space-y-4',
            children: [
              {
                id: 'input-group',
                type: 'div',
                className: 'flex gap-2',
                children: [
                  {
                    id: 'todo-input',
                    type: 'Input',
                    props: {
                      placeholder: 'Enter a new todo...',
                      value: newTodo
                    },
                    events: {
                      onChange: { action: 'update-input' }
                    }
                  },
                  {
                    id: 'add-button',
                    type: 'Button',
                    props: {
                      children: 'Add'
                    },
                    events: {
                      onClick: { action: 'add-todo' }
                    }
                  }
                ]
              },
              {
                id: 'todo-list',
                type: 'div',
                className: 'space-y-2',
                children: todos.map((todo: any) => ({
                  id: `todo-${todo.id}`,
                  type: 'div',
                  className: 'flex items-center gap-2 p-3 rounded-lg border bg-card',
                  children: [
                    {
                      id: `checkbox-${todo.id}`,
                      type: 'Checkbox',
                      props: {
                        checked: todo.completed
                      },
                      events: {
                        onCheckedChange: {
                          action: 'toggle-todo',
                          params: { id: todo.id }
                        }
                      }
                    },
                    {
                      id: `text-${todo.id}`,
                      type: 'span',
                      className: todo.completed
                        ? 'flex-1 line-through text-muted-foreground'
                        : 'flex-1',
                      children: todo.text
                    },
                    {
                      id: `delete-${todo.id}`,
                      type: 'Button',
                      props: {
                        variant: 'ghost',
                        size: 'sm',
                        children: '×'
                      },
                      events: {
                        onClick: {
                          action: 'delete-todo',
                          params: { id: todo.id }
                        }
                      }
                    }
                  ]
                }))
              }
            ]
          }
        ]
      }
    ]
  }

  return (
    <JSONUIRenderer
      component={pageSchema}
      dataMap={{ todos, newTodo }}
      onAction={handleAction}
    />
  )
}
