import { useState, type ReactNode } from 'react'
import { createPortal } from 'react-dom'
import styles from './DetailPanel.module.css'

interface Tab {
  label: string
  value: string
  content: ReactNode
}

interface DetailPanelProps {
  open: boolean
  onClose: () => void
  title: string
  tabs?: Tab[]
  children?: ReactNode
  actions?: ReactNode
  className?: string
}

export function DetailPanel({ open, onClose, title, tabs, children, actions, className }: DetailPanelProps) {
  const [activeTab, setActiveTab] = useState(tabs?.[0]?.value ?? '')

  const activeContent = tabs?.find((t) => t.value === activeTab)?.content

  const content = (
    <>
      {open && <div className={styles.backdrop} onClick={onClose} aria-hidden="true" />}
      <aside
        className={`${styles.panel} ${open ? styles.open : ''} ${className ?? ''}`}
        aria-hidden={!open}
      >
        <div className={styles.header}>
          <span className={styles.title}>{title}</span>
          <button
            className={styles.closeBtn}
            onClick={onClose}
            aria-label="Close panel"
            type="button"
          >
            &times;
          </button>
        </div>

        {tabs && tabs.length > 0 && (
          <div className={styles.tabs}>
            {tabs.map((tab) => (
              <button
                key={tab.value}
                className={`${styles.tab} ${tab.value === activeTab ? styles.activeTab : ''}`}
                onClick={() => setActiveTab(tab.value)}
                type="button"
              >
                {tab.label}
              </button>
            ))}
          </div>
        )}

        <div className={styles.body}>
          {children ?? activeContent}
        </div>

        {actions && (
          <div className={styles.actions}>
            {actions}
          </div>
        )}
      </aside>
    </>
  )

  // Portal to AppShell level if target exists, otherwise render in place
  const portalTarget = document.getElementById('cameleer-detail-panel-root')
  return portalTarget ? createPortal(content, portalTarget) : content
}
