'use client'

import { useState } from 'react'
import Link from 'next/link'

export interface DisplayRow {
  key: string
  responseId: string
  submissionNum: number
  isFirstInGroup: boolean
  date: string
  code: string
  prompt: string
  rendered: string | null
  zone: string
  sector: string
}

export function ResponsesTable({
  rows,
  surveyId,
  page,
}: {
  rows: DisplayRow[]
  surveyId?: string
  page: number
}) {
  const [expanded, setExpanded] = useState<Set<number>>(new Set())

  function toggle(submissionNum: number) {
    setExpanded((prev) => {
      const next = new Set(prev)
      if (next.has(submissionNum)) next.delete(submissionNum)
      else next.add(submissionNum)
      return next
    })
  }

  function detailHref(responseId: string): string {
    const params = new URLSearchParams()
    if (surveyId) params.set('survey_id', surveyId)
    params.set('page', String(page))
    return `/admin/responses/${responseId}?${params.toString()}`
  }

  return (
    <table className="admin-table">
      <thead>
        <tr>
          <th>#</th>
          <th>Fecha</th>
          <th>Código</th>
          <th>Pregunta</th>
          <th>Valor</th>
          <th className="admin-col-optional">Departamento</th>
          <th className="admin-col-optional">Sector</th>
          <th>Ver</th>
        </tr>
      </thead>
      <tbody>
        {rows
          .filter((row) => row.isFirstInGroup || expanded.has(row.submissionNum))
          .map((row) => {
            const groupClass =
              row.submissionNum % 2 === 0 ? 'admin-group-even' : 'admin-group-odd'
            const isExpanded = expanded.has(row.submissionNum)
            const trClass = row.isFirstInGroup
              ? `${groupClass} admin-group-start admin-row-toggle`
              : groupClass

            return (
              <tr
                key={row.key}
                className={trClass}
                // Conveniencia para mouse — sin semántica ARIA en la fila (evita
                // anidar un control interactivo real, el Link "Ver", dentro de un
                // elemento expuesto como role="button" a lectores de pantalla).
                // El toggle accesible por teclado vive en el <button> de abajo.
                onClick={row.isFirstInGroup ? () => toggle(row.submissionNum) : undefined}
              >
                <td>
                  {row.isFirstInGroup ? (
                    <button
                      type="button"
                      className="admin-row-toggle-btn"
                      onClick={(e) => {
                        e.stopPropagation()
                        toggle(row.submissionNum)
                      }}
                      aria-expanded={isExpanded}
                      aria-label={isExpanded ? 'Colapsar respuesta' : 'Expandir respuesta'}
                    >
                      <span className="admin-toggle-icon" aria-hidden="true">
                        {isExpanded ? '▼' : '▶'}
                      </span>
                      {row.submissionNum}
                    </button>
                  ) : (
                    row.submissionNum
                  )}
                </td>
                <td>{row.date}</td>
                <td>{row.code}</td>
                <td className="admin-prompt">{row.prompt}</td>
                <td>
                  {row.rendered === null ? (
                    <span className="admin-nodata">sin dato</span>
                  ) : (
                    row.rendered
                  )}
                </td>
                <td className="admin-col-optional">{row.zone}</td>
                <td className="admin-col-optional">{row.sector}</td>
                <td onClick={(e) => e.stopPropagation()}>
                  {row.isFirstInGroup && (
                    <Link href={detailHref(row.responseId)} className="admin-action-link">
                      Ver
                    </Link>
                  )}
                </td>
              </tr>
            )
          })}
      </tbody>
    </table>
  )
}
