import React from "react";
import { useNavigate } from "react-router-dom";
import type { TicketListItem } from "../../types/ticket";

interface TicketTableProps {
  tickets: TicketListItem[];
  sortCol: keyof TicketListItem;
  sortDir: "asc" | "desc";
  onSort: (col: keyof TicketListItem) => void;
}

const columns: { key: keyof TicketListItem; label: string }[] = [
  { key: "ticket_id", label: "Ticket ID" },
  { key: "priority", label: "Priority" },
  { key: "title", label: "Title" },
  { key: "category", label: "Category" },
  { key: "type", label: "Type" },
  { key: "status", label: "Status" },
  { key: "created_at", label: "Created" },
  { key: "updated_at", label: "Updated" },
];

const TicketTable: React.FC<TicketTableProps> = ({
  tickets,
  sortCol,
  sortDir,
  onSort,
}) => {
  const navigate = useNavigate();

  return (
    <table>
      <thead>
        <tr>
          {columns.map((col) => (
            <th
              key={col.key}
              onClick={() => onSort(col.key)}
              className={sortCol === col.key ? `sort-${sortDir}` : ""}
            >
              {col.label}
            </th>
          ))}
        </tr>
      </thead>

      <tbody>
        {tickets.length === 0 && (
          <tr>
            <td colSpan={8}>No tickets found</td>
          </tr>
        )}

        {tickets.map((t) => (
          <tr key={t.ticket_id} className={`priority-${t.priority}`}>
            <td>
              <a
                className="ticket-link"
                onClick={() => navigate(`/ticket/${t.ticket_id}`)}
              >
                {t.ticket_id}
              </a>
            </td>
            <td>{t.priority}</td>
            <td>{t.title}</td>
            <td>{t.category}</td>
            <td>{t.type}</td>
            <td>
              <span className={`status-${t.status.replace(" ", "-")}`}>
                {t.status}
              </span>
            </td>
            <td>{new Date(t.created_at).toLocaleString()}</td>
            <td>{new Date(t.updated_at).toLocaleString()}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default TicketTable;
