import React, { useEffect, 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 { createTicket, deleteTicket, listTicketLogs, listTickets, updateTicket } from "../../services/ticketsApi.js";

export default function AdminTicketsLogsPage() {
  const [tickets, setTickets] = useState([]);
  const [logs, setLogs] = useState([]);
  const [selected, setSelected] = useState(null);
  const [error, setError] = useState("");

  async function load() {
    try {
      const [t, l] = await Promise.all([listTickets(), listTicketLogs()]);
      setTickets(t);
      setLogs(l);
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    }
  }
  useEffect(() => { load(); }, []);

  return (
    <div className="portal-page">
      <PageHeader title="Tickets & Logs" subtitle="Raise, update, close, delete tickets and inspect ticket logs." />
      <ErrorBanner message={error} />
      <div className="ptw-split">
        <div className="ptw-panel">
          <h3 className="ptw-panel__title">Tickets</h3>
          <div className="ptw-row-actions">
            <button type="button" className="swi-btn" onClick={async () => { await createTicket({ description: "New PTW ticket", status_id: 1, ticket_type_id: 1, user_id: 1 }); await load(); }}>Raise Ticket</button>
            <button type="button" className="swi-btn swi-btn--ghost" onClick={load}>Refresh</button>
          </div>
          <DataTable columns={[{ key: "id", label: "ID" }, { key: "description", label: "Description" }, { key: "status_id", label: "Status" }, { key: "created_at", label: "Created" }]} rows={tickets} keyField="id" onRowClick={setSelected} />
        </div>
        <div className="ptw-panel">
          <h3 className="ptw-panel__title">Selected Ticket Actions</h3>
          {selected ? (
            <>
              <p><strong>#{selected.id}</strong> {selected.description}</p>
              <div className="ptw-row-actions">
                <button type="button" className="swi-btn" onClick={async () => { await updateTicket(selected.id, { description: `${selected.description} (updated)` }); await load(); }}>Update</button>
                <button type="button" className="swi-btn" onClick={async () => { await updateTicket(selected.id, { status_id: 2, closed_at: new Date().toISOString().slice(0, 19).replace("T", " ") }); await load(); }}>Close</button>
                <button type="button" className="swi-btn swi-btn--danger" onClick={async () => { await deleteTicket(selected.id); setSelected(null); await load(); }}>Delete</button>
              </div>
            </>
          ) : <p className="ptw-muted">Select a ticket.</p>}
        </div>
      </div>
      <div className="ptw-panel">
        <h3 className="ptw-panel__title">View Ticket Logs</h3>
        <DataTable columns={[{ key: "id", label: "Log ID" }, { key: "ticket_id", label: "Ticket ID" }, { key: "status_id", label: "Status" }, { key: "created_at", label: "Created" }, { key: "closed_at", label: "Closed" }]} rows={logs} keyField="id" />
      </div>
    </div>
  );
}
