import React from 'react'
import { Button } from './Button'

// ─── Pagination ───────────────────────────────────────────────────────────────

export interface PaginationProps {
  currentPage: number
  totalPages: number
  totalCount?: number
  pageSize?: number
  onPageChange: (page: number) => void
  className?: string
}

function buildPages(current: number, total: number): (number | '...')[] {
  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1)
  const pages: (number | '...')[] = [1]
  if (current > 3) pages.push('...')
  for (let i = Math.max(2, current - 1); i <= Math.min(total - 1, current + 1); i++) {
    pages.push(i)
  }
  if (current < total - 2) pages.push('...')
  pages.push(total)
  return pages
}

export const Pagination: React.FC<PaginationProps> = ({
  currentPage,
  totalPages,
  totalCount,
  pageSize = 10,
  onPageChange,
  className = '',
}) => {
  const start = (currentPage - 1) * pageSize + 1
  const end = Math.min(currentPage * pageSize, totalCount ?? currentPage * pageSize)
  const pages = buildPages(currentPage, totalPages)

  return (
    <div className={`flex justify-between items-center ${className}`}>
      {totalCount != null && (
        <span className="text-caption text-slate-400 font-semibold">
          {start}-{end} / {totalCount}건
        </span>
      )}
      <div className="flex gap-1 ml-auto">
        <button
          onClick={() => onPageChange(currentPage - 1)}
          disabled={currentPage <= 1}
          className="w-8 h-8 rounded-lg border border-slate-200 flex items-center justify-center text-xs text-slate-400 cursor-pointer hover:bg-slate-100 disabled:opacity-40 disabled:cursor-not-allowed"
        >
          <span className="material-symbols-outlined text-body-lg">chevron_left</span>
        </button>

        {pages.map((p, i) =>
          p === '...' ? (
            <span key={`ellipsis-${i}`} className="w-8 h-8 flex items-center justify-center text-xs text-slate-400">
              ...
            </span>
          ) : (
            <button
              key={p}
              onClick={() => onPageChange(p as number)}
              className={`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold transition-colors cursor-pointer ${
                p === currentPage
                  ? 'bg-teal-500 text-white'
                  : 'border border-slate-200 text-slate-500 font-semibold hover:bg-slate-100'
              }`}
            >
              {p}
            </button>
          )
        )}

        <button
          onClick={() => onPageChange(currentPage + 1)}
          disabled={currentPage >= totalPages}
          className="w-8 h-8 rounded-lg border border-slate-200 flex items-center justify-center text-xs text-slate-400 cursor-pointer hover:bg-slate-100 disabled:opacity-40 disabled:cursor-not-allowed"
        >
          <span className="material-symbols-outlined text-body-lg">chevron_right</span>
        </button>
      </div>
    </div>
  )
}

// ─── Table ────────────────────────────────────────────────────────────────────

export interface TableColumn<T = Record<string, unknown>> {
  key: string
  label: string
  width?: string
  render?: (value: unknown, row: T, index: number) => React.ReactNode
}

export interface TableProps<T = Record<string, unknown>> {
  columns: TableColumn<T>[]
  data: T[]
  title?: string
  totalCount?: number
  onSearch?: (query: string) => void
  onFilter?: () => void
  searchPlaceholder?: string
  currentPage?: number
  totalPages?: number
  pageSize?: number
  onPageChange?: (page: number) => void
  className?: string
  emptyMessage?: string
}

export function Table<T = Record<string, unknown>>({
  columns,
  data,
  title,
  totalCount,
  onSearch,
  onFilter,
  searchPlaceholder = '검색...',
  currentPage,
  totalPages,
  pageSize,
  onPageChange,
  className = '',
  emptyMessage = '데이터가 없습니다.',
}: TableProps<T>) {
  const gridCols = columns.map((c) => c.width ?? '1fr').join(' ')

  return (
    <div className={`bg-white rounded-[14px] shadow-soft-md border border-slate-100 overflow-hidden ${className}`}>
      {/* Toolbar */}
      {(title || onSearch || onFilter) && (
        <div className="flex justify-between items-center px-5 py-4 border-b border-slate-100">
          <div className="flex items-center gap-2">
            {title && <h3 className="text-sm font-bold text-slate-900">{title}</h3>}
            {totalCount != null && (
              <span className="min-w-[20px] h-5 px-1.5 bg-teal-50 text-teal-600 rounded-md text-caption font-bold flex items-center justify-center">
                {totalCount}
              </span>
            )}
          </div>
          <div className="flex gap-2">
            {onSearch && (
              <div className="relative">
                <span className="material-symbols-outlined absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400 text-body-md">
                  search
                </span>
                <input
                  className="bg-slate-50 border border-slate-200 rounded-lg pl-8 pr-3 py-1.5 text-caption w-48 focus:ring-1 focus:ring-teal-500 outline-none"
                  placeholder={searchPlaceholder}
                  onChange={(e) => onSearch(e.target.value)}
                />
              </div>
            )}
            {onFilter && (
              <Button variant="outline" size="sm" onClick={onFilter} leftIcon="filter_list">
                필터
              </Button>
            )}
          </div>
        </div>
      )}

      {/* Header */}
      <div
        className="grid px-5 py-2.5 bg-slate-50 border-b border-slate-100"
        style={{ gridTemplateColumns: gridCols }}
      >
        {columns.map((col) => (
          <span key={col.key} className="text-caption font-semibold uppercase tracking-wider text-slate-400">
            {col.label}
          </span>
        ))}
      </div>

      {/* Rows */}
      <div className="divide-y divide-slate-50">
        {data.length === 0 ? (
          <div className="px-5 py-10 text-center text-body-sm text-slate-400">{emptyMessage}</div>
        ) : (
          data.map((row, rowIndex) => (
            <div
              key={rowIndex}
              className="grid px-5 py-3 items-center hover:bg-slate-50/50 transition-colors"
              style={{ gridTemplateColumns: gridCols }}
            >
              {columns.map((col) => (
                <div key={col.key}>
                  {col.render
                    ? col.render((row as Record<string, unknown>)[col.key], row, rowIndex)
                    : String((row as Record<string, unknown>)[col.key] ?? '')}
                </div>
              ))}
            </div>
          ))
        )}
      </div>

      {/* Pagination */}
      {currentPage != null && totalPages != null && onPageChange && (
        <div className="px-5 py-3 bg-slate-50 border-t border-slate-100">
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            totalCount={totalCount}
            pageSize={pageSize}
            onPageChange={onPageChange}
          />
        </div>
      )}
    </div>
  )
}
