import React, { useState } from "react";
import PageHeader from "../../components/common/PageHeader.jsx";
import DataTable from "../../components/common/DataTable.jsx";
import ErrorBanner from "../../components/common/ErrorBanner.jsx";
import { listTicketLogs } from "../../services/ticketsApi.js";

export default function AdminTicketLogsPage({ initialTicketId = "" }) {
  const [logs, setLogs] = useState([]);
  const [ticketId, setTicketId] = useState(initialTicketId ? String(initialTicketId) : "");
  const [error, setError] = useState("");

  const load = React.useCallback(async () => {
    try {
      setError("");
      const rows = await listTicketLogs(ticketId ? { ticket_id: ticketId } : {});
      setLogs(rows);
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    }
  }, [ticketId]);

  React.useEffect(() => {
    load();
  }, [load]);

  return (
    <div className="portal-page">
      <PageHeader title="Ticket Logs" subtitle="View audit trail for ticket updates and resolutions." />
      <ErrorBanner message={error} />
      <div className="ptw-panel">
        <div className="ptw-toolbar">
          <input
            className="swi-input"
            type="number"
            value={ticketId}
            onChange={(e) => setTicketId(e.target.value)}
            placeholder="Filter by ticket id"
          />
          <button type="button" className="swi-btn swi-btn--ghost" onClick={load}>Apply</button>
          <button type="button" className="swi-btn swi-btn--ghost" onClick={() => { setTicketId(""); }}>Clear</button>
        </div>
        <DataTable
          columns={[
            { key: "id", label: "Log ID" },
            { key: "ticket_id", label: "Ticket ID" },
            { key: "status_id", label: "Status" },
            { key: "ticket_type_id", label: "Type" },
            { key: "description", label: "Description" },
            { key: "created_at", label: "Created" },
            { key: "closed_at", label: "Closed" }
          ]}
          rows={logs}
          keyField="id"
        />
      </div>
    </div>
  );
}
