'use client'

import { useState } from 'react'
import type { ComponentRenderProps } from '@json-render/react'
import { useActions } from '@json-render/react'

type Column = {
  key: string; label: string; sortable?: boolean; align?: string
  format?: string; width?: string
}

const avatarColors = ['#4f46e5', '#7c3aed', '#059669', '#d97706', '#dc2626', '#0891b2']

function getInitials(name: string) {
  return name.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase()
}

function formatCell(value: unknown, format?: string): React.ReactNode {
  if (value === null || value === undefined) return <span className="text-gray-400">—</span>

  switch (format) {
    case 'email':
      return <a href={`mailto:${value}`} className="text-indigo-600 hover:underline">{String(value)}</a>
    case 'phone':
      return <span className="text-gray-600">{String(value)}</span>
    case 'date':
      return <span className="text-gray-500 text-sm">{String(value)}</span>
    case 'currency':
      return <span className="font-mono font-medium">{String(value)}</span>
    case 'tags': {
      const tags = Array.isArray(value) ? value : [value]
      return (
        <div className="flex flex-wrap gap-1 max-w-[200px]">
          {tags.slice(0, 3).map((t, i) => (
            <span key={i} className="px-2 py-0.5 bg-indigo-50 text-indigo-600 rounded-full text-xs font-medium">
              {String(t)}
            </span>
          ))}
          {tags.length > 3 && (
            <span className="px-2 py-0.5 bg-gray-100 text-gray-500 rounded-full text-xs font-medium">
              +{tags.length - 3}
            </span>
          )}
        </div>
      )
    }
    case 'avatar': {
      const name = String(value)
      const color = avatarColors[name.charCodeAt(0) % avatarColors.length]
      return (
        <div className="flex items-center gap-3">
          <div
            className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-semibold shrink-0"
            style={{ background: color }}
          >
            {getInitials(name)}
          </div>
          <span className="font-medium text-gray-900">{name}</span>
        </div>
      )
    }
    case 'status': {
      const s = String(value).toLowerCase()
      const cls = s.includes('active') ? 'bg-green-100 text-green-700'
        : s.includes('new') ? 'bg-blue-100 text-blue-700'
        : s.includes('lost') ? 'bg-red-100 text-red-700'
        : 'bg-gray-100 text-gray-600'
      return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${cls}`}>{String(value)}</span>
    }
    default:
      return <span>{String(value)}</span>
  }
}

export function DataTable({ element }: ComponentRenderProps) {
  const { columns, rows, selectable, rowAction, emptyMessage, pageSize = 10 } = element.props as {
    columns: Column[]; rows: Array<Record<string, unknown>>; selectable?: boolean
    rowAction?: string; emptyMessage?: string; pageSize?: number
  }
  const [selected, setSelected] = useState<Set<number>>(new Set())
  const [sortKey, setSortKey] = useState<string | null>(null)
  const [sortAsc, setSortAsc] = useState(true)
  const [page, setPage] = useState(0)
  const { execute } = useActions()

  const sortedRows = [...rows].sort((a, b) => {
    if (!sortKey) return 0
    const av = String(a[sortKey] ?? ''), bv = String(b[sortKey] ?? '')
    return sortAsc ? av.localeCompare(bv) : bv.localeCompare(av)
  })

  const totalPages = Math.ceil(sortedRows.length / pageSize)
  const pageRows = sortedRows.slice(page * pageSize, (page + 1) * pageSize)

  const toggleSort = (key: string) => {
    if (sortKey === key) setSortAsc(!sortAsc)
    else { setSortKey(key); setSortAsc(true) }
  }

  const toggleAll = () => {
    if (selected.size === pageRows.length) setSelected(new Set())
    else setSelected(new Set(pageRows.map((_, i) => page * pageSize + i)))
  }

  if (rows.length === 0) {
    return (
      <div className="py-16 text-center">
        <p className="text-4xl mb-3">📋</p>
        <p className="text-gray-500">{emptyMessage || 'No data available'}</p>
      </div>
    )
  }

  return (
    <div className="bg-white rounded-xl shadow-sm overflow-hidden">
      {selected.size > 0 && (
        <div className="px-5 py-2 bg-indigo-50 text-indigo-600 text-sm font-medium">
          {selected.size} selected
        </div>
      )}
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr>
              {selectable && (
                <th className="w-10 px-4 py-3 bg-gray-50 border-b border-gray-200">
                  <input type="checkbox" className="accent-indigo-600 w-4 h-4" checked={selected.size === pageRows.length && pageRows.length > 0} onChange={toggleAll} />
                </th>
              )}
              {columns.map(col => (
                <th
                  key={col.key}
                  className={`px-4 py-3 bg-gray-50 border-b border-gray-200 text-left text-xs font-medium text-gray-500 uppercase tracking-wider ${col.sortable ? 'cursor-pointer hover:bg-gray-100 select-none' : ''}`}
                  style={col.width ? { width: col.width } : undefined}
                  onClick={() => col.sortable && toggleSort(col.key)}
                >
                  {col.label}
                  {col.sortable && sortKey === col.key && (
                    <span className="ml-1 text-indigo-600">{sortAsc ? '↑' : '↓'}</span>
                  )}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {pageRows.map((row, ri) => {
              const globalIdx = page * pageSize + ri
              const isSelected = selected.has(globalIdx)
              return (
                <tr
                  key={ri}
                  className={`border-b border-gray-100 hover:bg-gray-50 transition-colors ${isSelected ? 'bg-indigo-50' : ''} ${rowAction ? 'cursor-pointer' : ''}`}
                  onClick={() => rowAction && execute({ name: rowAction, params: { contactId: String(row.id || ri) } })}
                >
                  {selectable && (
                    <td className="px-4 py-3" onClick={e => e.stopPropagation()}>
                      <input
                        type="checkbox" className="accent-indigo-600 w-4 h-4"
                        checked={isSelected}
                        onChange={() => {
                          const next = new Set(selected)
                          next.has(globalIdx) ? next.delete(globalIdx) : next.add(globalIdx)
                          setSelected(next)
                        }}
                      />
                    </td>
                  )}
                  {columns.map(col => (
                    <td key={col.key} className="px-4 py-3 border-b border-gray-50">
                      {formatCell(row[col.key], col.format)}
                    </td>
                  ))}
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>
      {totalPages > 1 && (
        <div className="flex items-center justify-between px-5 py-3 border-t border-gray-200">
          <span className="text-sm text-gray-500">
            {page * pageSize + 1}–{Math.min((page + 1) * pageSize, rows.length)} of {rows.length}
          </span>
          <div className="flex gap-2">
            <button
              className="px-3 py-1.5 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
              disabled={page === 0} onClick={() => setPage(p => p - 1)}
            >
              Previous
            </button>
            <button
              className="px-3 py-1.5 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
              disabled={page >= totalPages - 1} onClick={() => setPage(p => p + 1)}
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
