'use client'

import { useMemo } from 'react'
import * as Tabs from '@radix-ui/react-tabs'
import { Blocks, Settings2, FileText, Search, Palette } from 'lucide-react'
import type { BuilderNode, PageNode } from '@actuate-media/cms-core'
import { BlockEditor } from './BlockEditor.js'
import { NodeSettings } from './NodeSettings.js'
import { PageSettingsEditor } from './PageSettings.js'
import { BuilderSEOPanel } from './SEOPanel.js'
import { DesignScorePanel } from './DesignScore.js'
import type { PageSettings } from '../../hooks/useBuilderState.js'

export interface ContextPanelProps {
  activeTab: 'block' | 'node' | 'page' | 'seo' | 'design'
  onTabChange: (tab: 'block' | 'node' | 'page' | 'seo' | 'design') => void
  selectedNode: BuilderNode | null
  tree: PageNode
  pageSettings: PageSettings
  onUpdateSettings: (id: string, settings: Record<string, unknown>) => void
  onUpdateBlock: (id: string, data: Record<string, unknown>) => void
  onRemoveNode: (id: string) => void
  onDuplicateNode: (id: string) => void
  onMoveNodeUp: (id: string) => void
  onMoveNodeDown: (id: string) => void
  onPageSettingsChange: (settings: Partial<PageSettings>) => void
  onAddRow: (sectionId: string) => void
  config: any
}

type TabDef = {
  value: 'block' | 'node' | 'page' | 'seo' | 'design'
  label: string
  icon: typeof Blocks
}

const TABS: TabDef[] = [
  { value: 'block', label: 'Block', icon: Blocks },
  { value: 'node', label: 'Node', icon: Settings2 },
  { value: 'page', label: 'Page', icon: FileText },
  { value: 'seo', label: 'SEO', icon: Search },
  { value: 'design', label: 'Design', icon: Palette },
]

export function ContextPanel({
  activeTab,
  onTabChange,
  selectedNode,
  tree,
  pageSettings,
  onUpdateSettings,
  onUpdateBlock,
  onRemoveNode,
  onDuplicateNode,
  onMoveNodeUp,
  onMoveNodeDown,
  onPageSettingsChange,
  onAddRow,
  config,
}: ContextPanelProps) {
  const availableTabs = useMemo(() => {
    if (!selectedNode) return TABS.filter((t) => t.value !== 'block' && t.value !== 'node')
    if (selectedNode.type === 'block') return TABS.filter((t) => t.value !== 'node')
    return TABS.filter((t) => t.value !== 'block')
  }, [selectedNode])

  const effectiveTab = useMemo(() => {
    if (availableTabs.some((t) => t.value === activeTab)) return activeTab
    if (selectedNode?.type === 'block') return 'block'
    if (selectedNode) return 'node'
    return 'page'
  }, [activeTab, availableTabs, selectedNode])

  return (
    <div className="bg-card h-full w-full overflow-y-auto">
      <Tabs.Root
        value={effectiveTab}
        onValueChange={(value) => onTabChange(value as ContextPanelProps['activeTab'])}
      >
        <Tabs.List className="border-border bg-muted/30 flex border-b">
          {availableTabs.map((tab) => {
            const Icon = tab.icon
            return (
              <Tabs.Trigger
                key={tab.value}
                value={tab.value}
                className="text-muted-foreground hover:text-foreground data-[state=active]:text-foreground data-[state=active]:border-primary data-[state=active]:bg-background flex flex-1 items-center justify-center gap-1.5 px-2 py-2.5 text-xs font-medium transition-colors data-[state=active]:border-b-2"
              >
                <Icon size={14} />
                <span>{tab.label}</span>
              </Tabs.Trigger>
            )
          })}
        </Tabs.List>

        <Tabs.Content value="block">
          {selectedNode?.type === 'block' && (
            <BlockEditor
              node={selectedNode}
              onUpdateBlock={onUpdateBlock}
              onUpdateSettings={onUpdateSettings}
              onRemoveNode={onRemoveNode}
              onDuplicateNode={onDuplicateNode}
              config={config}
            />
          )}
        </Tabs.Content>

        <Tabs.Content value="node">
          {selectedNode &&
            selectedNode.type !== 'block' &&
            selectedNode.type !== 'page' &&
            selectedNode.type !== 'savedSectionRef' && (
              <NodeSettings
                node={selectedNode}
                onUpdateSettings={onUpdateSettings}
                onRemoveNode={onRemoveNode}
                onDuplicateNode={onDuplicateNode}
                onMoveNodeUp={onMoveNodeUp}
                onMoveNodeDown={onMoveNodeDown}
                onAddRow={selectedNode.type === 'section' ? onAddRow : undefined}
              />
            )}
        </Tabs.Content>

        <Tabs.Content value="page">
          <PageSettingsEditor settings={pageSettings} onChange={onPageSettingsChange} />
        </Tabs.Content>

        <Tabs.Content value="seo">
          <BuilderSEOPanel
            tree={tree}
            pageSettings={pageSettings}
            onPageSettingsChange={onPageSettingsChange}
            selectedNodeId={selectedNode?.id ?? null}
          />
        </Tabs.Content>

        <Tabs.Content value="design">
          <DesignScorePanel tree={tree} />
        </Tabs.Content>
      </Tabs.Root>
    </div>
  )
}
