/*
 * UIWS 이식 공통 컴포넌트 키트 — 색상 하드코딩 금지(테마 토큰 var(--uiws-*)만 사용).
 * 다크/라이트 양 모드에서 대비/가독성 정상. 기존 PMS 컴포넌트와 충돌 회피 위해 components/uiws/ 네임스페이스.
 */
import { type ReactNode, type CSSProperties } from 'react'

const card: CSSProperties = {
  background: 'var(--uiws-surface)',
  border: '1px solid var(--uiws-border)',
  borderRadius: 12,
  boxShadow: 'var(--uiws-shadow)',
}

export function PageHeader({ title, subtitle, actions }: { title: string; subtitle?: string; actions?: ReactNode }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 20 }}>
      <div>
        <h1 style={{ fontSize: 22, fontWeight: 700, color: 'var(--uiws-text)' }}>{title}</h1>
        {subtitle && <div style={{ fontSize: 13, color: 'var(--uiws-text-muted)', marginTop: 4 }}>{subtitle}</div>}
      </div>
      <div style={{ display: 'flex', gap: 8 }}>{actions}</div>
    </div>
  )
}

export function Panel({ children, style }: { children: ReactNode; style?: CSSProperties }) {
  return <div style={{ ...card, padding: 18, ...style }}>{children}</div>
}

export function Button({
  children, onClick, variant = 'primary', type = 'button', disabled,
}: {
  children: ReactNode; onClick?: () => void; variant?: 'primary' | 'ghost' | 'danger'
  type?: 'button' | 'submit'; disabled?: boolean
}) {
  const styles: Record<string, CSSProperties> = {
    primary: { background: 'var(--uiws-primary)', color: 'var(--uiws-primary-contrast)', border: 'none' },
    ghost: { background: 'transparent', color: 'var(--uiws-text-muted)', border: '1px solid var(--uiws-border)' },
    danger: { background: 'var(--uiws-danger)', color: '#fff', border: 'none' },
  }
  return (
    <button type={type} onClick={onClick} disabled={disabled}
      style={{ padding: '9px 16px', borderRadius: 8, fontSize: 13, fontWeight: 600,
        cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.5 : 1, ...styles[variant] }}>
      {children}
    </button>
  )
}

export function Input({
  value, onChange, placeholder, type = 'text', style,
}: {
  value: string; onChange: (v: string) => void; placeholder?: string; type?: string; style?: CSSProperties
}) {
  return (
    <input type={type} value={value} placeholder={placeholder} onChange={e => onChange(e.target.value)}
      style={{ padding: '9px 12px', borderRadius: 8, fontSize: 13,
        background: 'var(--uiws-input-bg)', border: '1px solid var(--uiws-border)', color: 'var(--uiws-text)', ...style }} />
  )
}

export function FormField({ label, children }: { label: string; children: ReactNode }) {
  return (
    <label style={{ display: 'block', marginBottom: 12 }}>
      <div style={{ fontSize: 12, color: 'var(--uiws-text-muted)', marginBottom: 6 }}>{label}</div>
      {children}
    </label>
  )
}

export function SearchBar({ children }: { children: ReactNode }) {
  return (
    <Panel style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap', marginBottom: 16 }}>
      {children}
    </Panel>
  )
}

export interface Column<T> {
  key: string
  header: string
  render?: (row: T) => ReactNode
  width?: number | string
  align?: 'left' | 'center' | 'right'
}

export function DataGrid<T extends Record<string, unknown>>({
  columns, rows, rowKey, onRowClick, empty = '데이터가 없습니다.',
}: {
  columns: Column<T>[]; rows: T[]; rowKey: (row: T) => string | number
  onRowClick?: (row: T) => void; empty?: string
}) {
  return (
    <div style={{ ...card, overflow: 'hidden' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, color: 'var(--uiws-text)' }}>
        <thead>
          <tr style={{ background: 'var(--uiws-surface-2)' }}>
            {columns.map(c => (
              <th key={c.key} style={{ textAlign: c.align ?? 'left', padding: '11px 14px',
                color: 'var(--uiws-text-muted)', fontWeight: 600, fontSize: 12,
                borderBottom: '1px solid var(--uiws-border)', width: c.width }}>{c.header}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.length === 0 ? (
            <tr><td colSpan={columns.length} style={{ padding: 28, textAlign: 'center', color: 'var(--uiws-text-faint)' }}>{empty}</td></tr>
          ) : rows.map(row => (
            <tr key={rowKey(row)} onClick={() => onRowClick?.(row)}
              style={{ cursor: onRowClick ? 'pointer' : 'default', borderBottom: '1px solid var(--uiws-border)' }}
              onMouseEnter={e => (e.currentTarget.style.background = 'var(--uiws-row-hover)')}
              onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}>
              {columns.map(c => (
                <td key={c.key} style={{ padding: '11px 14px', textAlign: c.align ?? 'left' }}>
                  {c.render ? c.render(row) : String(row[c.key] ?? '')}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

export function Pagination({ page, totalPages, onChange }: { page: number; totalPages: number; onChange: (p: number) => void }) {
  if (totalPages <= 1) return null
  return (
    <div style={{ display: 'flex', gap: 6, justifyContent: 'center', marginTop: 16 }}>
      <Button variant="ghost" disabled={page <= 0} onClick={() => onChange(page - 1)}>이전</Button>
      <span style={{ alignSelf: 'center', fontSize: 13, color: 'var(--uiws-text-muted)' }}>
        {page + 1} / {totalPages}
      </span>
      <Button variant="ghost" disabled={page >= totalPages - 1} onClick={() => onChange(page + 1)}>다음</Button>
    </div>
  )
}

export function YnBadge({ yn, yes = '읽음', no = '안읽음' }: { yn: string; yes?: string; no?: string }) {
  const on = yn === 'Y'
  return (
    <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 9px', borderRadius: 999,
      color: on ? 'var(--uiws-success)' : 'var(--uiws-text-muted)',
      background: on ? 'rgba(46,204,113,0.12)' : 'var(--uiws-surface-2)',
      border: '1px solid var(--uiws-border)' }}>
      {on ? yes : no}
    </span>
  )
}

export function Modal({ title, onClose, children, footer }: { title: string; onClose: () => void; children: ReactNode; footer?: ReactNode }) {
  return (
    <div onClick={onClose}
      style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'flex',
        justifyContent: 'center', alignItems: 'center', zIndex: 1000 }}>
      <div onClick={e => e.stopPropagation()}
        style={{ ...card, width: 'min(560px, 92vw)', maxHeight: '88vh', overflow: 'auto', padding: 22 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <h2 style={{ fontSize: 17, fontWeight: 700, color: 'var(--uiws-text)' }}>{title}</h2>
          <button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--uiws-text-muted)', fontSize: 20, cursor: 'pointer' }}>×</button>
        </div>
        <div>{children}</div>
        {footer && <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 18 }}>{footer}</div>}
      </div>
    </div>
  )
}

export function Spinner({ label = '불러오는 중...' }: { label?: string }) {
  return <div style={{ padding: 28, textAlign: 'center', color: 'var(--uiws-text-faint)', fontSize: 13 }}>{label}</div>
}
