'use client'

import Link from 'next/link'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeadCell,
  TableRow,
} from 'flowbite-react'
import { FiArrowUp, FiChevronDown, FiChevronUp, FiEye } from 'react-icons/fi'

import tableTheme from '@/lib/themes/table'
import { formatDuration } from '@/lib/utils/date'
import { formatRoleLabel } from '@/lib/utils/user-performance'
import { PerformanceSortKey, SortDirection, UserPerformanceRow } from '../types'

interface UserPerformanceTableProps {
  rows: UserPerformanceRow[]
  isLoading: boolean
  sort: PerformanceSortKey
  direction: SortDirection
  onSort: (key: PerformanceSortKey) => void
}

function SortableHeader({
  label,
  column,
  sort,
  direction,
  onSort,
  className = '',
}: {
  label: string
  column: PerformanceSortKey
  sort: PerformanceSortKey
  direction: SortDirection
  onSort: (key: PerformanceSortKey) => void
  className?: string
}) {
  const isActive = sort === column

  return (
    <TableHeadCell className={`text-nowrap p-4 ${className}`}>
      <button
        type="button"
        className={`flex items-center gap-1 text-sm font-medium hover:text-primary ${
          isActive ? 'text-primary' : ''
        } ${className.includes('right') ? 'ml-auto' : ''}`}
        onClick={() => onSort(column)}
      >
        {label}
        {isActive ? (
          direction === 'asc' ? (
            <FiChevronUp className="h-4 w-4" />
          ) : (
            <FiChevronDown className="h-4 w-4" />
          )
        ) : (
          <FiArrowUp className="h-4 w-4 opacity-30" />
        )}
      </button>
    </TableHeadCell>
  )
}

export default function UserPerformanceTable({
  rows,
  isLoading,
  sort,
  direction,
  onSort,
}: UserPerformanceTableProps) {
  return (
    <div className="min-h-48 overflow-x-auto rounded-lg border border-slate-200">
      <Table theme={tableTheme.table} hoverable>
        <TableHead>
          <TableRow>
            <SortableHeader
              label="User"
              column="name"
              sort={sort}
              direction={direction}
              onSort={onSort}
            />
            <SortableHeader
              label="Avg Follow-Up Points"
              column="avg_points"
              sort={sort}
              direction={direction}
              onSort={onSort}
              className="text-right"
            />
            <SortableHeader
              label="Avg Follow-Up Response Time"
              column="avg_response_seconds"
              sort={sort}
              direction={direction}
              onSort={onSort}
              className="text-right"
            />
            <SortableHeader
              label="Follow-Ups Confirmed"
              column="follow_ups_confirmed"
              sort={sort}
              direction={direction}
              onSort={onSort}
              className="text-right"
            />
            <SortableHeader
              label="Pending Follow-Ups"
              column="ready_for_follow_ups"
              sort={sort}
              direction={direction}
              onSort={onSort}
              className="text-right"
            />
            <SortableHeader
              label="Confirmed Orders"
              column="confirmed_orders"
              sort={sort}
              direction={direction}
              onSort={onSort}
              className="text-right"
            />
            <SortableHeader
              label="Unconfirmed Orders"
              column="unconfirmed_orders"
              sort={sort}
              direction={direction}
              onSort={onSort}
              className="text-right"
            />
            <TableHeadCell className="p-4 text-center">Action</TableHeadCell>
          </TableRow>
        </TableHead>

        <TableBody className="divide-y divide-gray-200">
          {isLoading ? (
            Array.from({ length: 5 }).map((_, index) => (
              <TableRow key={`skeleton-${index}`} className="bg-white">
                {Array.from({ length: 8 }).map((__, cellIndex) => (
                  <TableCell key={`skeleton-cell-${cellIndex}`} className="p-4">
                    <div className="h-4 w-24 animate-pulse rounded bg-slate-200" />
                  </TableCell>
                ))}
              </TableRow>
            ))
          ) : rows.length === 0 ? (
            <TableRow className="bg-white">
              <TableCell colSpan={8} className="p-8 text-center text-slate-400">
                No users match the selected filters.
              </TableCell>
            </TableRow>
          ) : (
            rows.map((row) => (
              <TableRow key={row.id} className="bg-white">
                <TableCell className="p-4 text-nowrap">
                  <div className="font-semibold text-slate-900">{row.name}</div>
                  <div className="text-sm text-slate-500">
                    {formatRoleLabel(row.role)}
                  </div>
                </TableCell>
                <TableCell className="p-4 text-right font-medium tabular-nums">
                  {row.avg_points != null ? row.avg_points.toFixed(1) : '-'}
                </TableCell>
                <TableCell className="p-4 text-right font-mono text-sm tabular-nums">
                  {formatDuration(row.avg_response_seconds)}
                </TableCell>
                <TableCell className="p-4 text-right tabular-nums">
                  {row.follow_ups_confirmed}
                </TableCell>
                <TableCell className="p-4 text-right tabular-nums">
                  {row.ready_for_follow_ups}
                </TableCell>
                <TableCell className="p-4 text-right tabular-nums">
                  {row.confirmed_orders}
                </TableCell>
                <TableCell className="p-4 text-right tabular-nums">
                  {row.unconfirmed_orders}
                </TableCell>
                <TableCell className="p-4 text-center">
                  <Link
                    href={`/user-performance/detail/${row.id}`}
                    className="inline-flex items-center gap-1 rounded-md p-2 text-primary hover:bg-slate-100"
                    aria-label={`View performance of ${row.name}`}
                    title="View User Performance"
                  >
                    <FiEye className="h-4 w-4" />
                  </Link>
                </TableCell>
              </TableRow>
            ))
          )}
        </TableBody>
      </Table>
    </div>
  )
}
