import React, { useCallback, useEffect, useMemo, useState } from "react";
import AdminPageHeader from "../../components/admin/AdminPageHeader.jsx";
import TicketDetailModal from "../../components/admin/tickets/TicketDetailModal.jsx";
import {
  TICKET_STATUS,
  ticketStatusBadgeClass,
} from "../../constants/ticketStatus.js";
import { fetchTicketLogs } from "../../services/ticketsApi.js";
import { getApiErrorMessage } from "../../utils/apiError.js";

const STATUS_ALL = "all";

function formatDateTime(value) {
  if (!value) return "—";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return "—";
  return d.toLocaleString(undefined, {
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function ticketSummary(log) {
  const desc = (log.ticket_description || "").trim();
  if (!desc) return null;
  const line = desc.split(/\r?\n/)[0];
  return line.length > 72 ? `${line.slice(0, 72)}…` : line;
}

export default function AdminTicketLogsPage({ onNavigate }) {
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [query, setQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState(STATUS_ALL);
  const [ticketFilter, setTicketFilter] = useState("");
  const [detailId, setDetailId] = useState(null);

  const load = useCallback(async () => {
    setError("");
    const rows = await fetchTicketLogs({
      limit: 300,
      ticketId: ticketFilter.trim() || undefined,
      statusId: statusFilter === STATUS_ALL ? undefined : statusFilter,
    });
    setLogs(Array.isArray(rows) ? rows : []);
  }, [statusFilter, ticketFilter]);

  useEffect(() => {
    setLoading(true);
    load()
      .catch((e) =>
        setError(getApiErrorMessage(e, "Could not load ticket logs."))
      )
      .finally(() => setLoading(false));
  }, [load]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return logs;
    return logs.filter((log) => {
      const summary = (ticketSummary(log) || "").toLowerCase();
      const user = (log.user_name || "").toLowerCase();
      const desc = (log.description || "").toLowerCase();
      const status = (log.status_type || "").toLowerCase();
      const type = (log.ticket_type_name || "").toLowerCase();
      return (
        summary.includes(q) ||
        user.includes(q) ||
        desc.includes(q) ||
        status.includes(q) ||
        type.includes(q) ||
        String(log.ticket_id).includes(q) ||
        String(log.id).includes(q)
      );
    });
  }, [logs, query]);

  const statusCounts = useMemo(() => {
    const counts = {
      open: 0,
      inProgress: 0,
      resolved: 0,
    };
    for (const log of logs) {
      const id = Number(log.status_id);
      if (id === TICKET_STATUS.OPEN) counts.open += 1;
      else if (id === TICKET_STATUS.IN_PROGRESS) counts.inProgress += 1;
      else if (id === TICKET_STATUS.RESOLVED) counts.resolved += 1;
    }
    return counts;
  }, [logs]);

  const uniqueTickets = useMemo(() => {
    return new Set(logs.map((log) => log.ticket_id)).size;
  }, [logs]);

  return (
    <div className="swi-admin-ticket-logs">
      <AdminPageHeader
        title="Ticket logs"
        subtitle="History from the tickets_logs table — every create, status change, and update."
        actions={
          <>
            {onNavigate ? (
              <button
                type="button"
                className="swi-btn swi-btn--ghost"
                onClick={() => onNavigate("tickets")}
              >
                Back to tickets
              </button>
            ) : null}
            <button
              type="button"
              className="swi-btn swi-btn--ghost"
              disabled={loading}
              onClick={() => {
                setLoading(true);
                load()
                  .catch((e) =>
                    setError(getApiErrorMessage(e, "Could not refresh logs."))
                  )
                  .finally(() => setLoading(false));
              }}
            >
              Refresh
            </button>
          </>
        }
      />

      {error ? (
        <div className="swi-error" role="alert">
          {error}
        </div>
      ) : null}

      <div className="swi-admin-assign-toolbar swi-panel">
        <div className="swi-admin-assign-stats">
          <span className="swi-admin-assign-stat">
            <strong>{logs.length}</strong> log entries
          </span>
          <span className="swi-admin-assign-stat">
            <strong>{uniqueTickets}</strong> tickets
          </span>
          <span className="swi-admin-assign-stat">
            <strong>{statusCounts.open}</strong> open events
          </span>
          <span className="swi-admin-assign-stat">
            <strong>{statusCounts.inProgress}</strong> in progress
          </span>
          <span className="swi-admin-assign-stat">
            <strong>{statusCounts.resolved}</strong> resolved
          </span>
        </div>
        <div className="swi-admin-tickets__filters">
          <input
            type="number"
            min={1}
            className="swi-input swi-admin-ticket-logs__ticket-id"
            placeholder="Ticket ID"
            value={ticketFilter}
            onChange={(e) => setTicketFilter(e.target.value)}
            aria-label="Filter by ticket ID"
          />
          <select
            className="swi-select swi-admin-tickets__status"
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            aria-label="Filter by status"
          >
            <option value={STATUS_ALL}>All statuses</option>
            <option value={TICKET_STATUS.OPEN}>Open</option>
            <option value={TICKET_STATUS.IN_PROGRESS}>In progress</option>
            <option value={TICKET_STATUS.RESOLVED}>Resolved</option>
          </select>
          <input
            type="search"
            className="swi-input swi-admin-tickets__search"
            placeholder="Search logs…"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        </div>
      </div>

      <section className="swi-panel swi-admin-assign-content">
        {loading ? (
          <p className="swi-muted swi-admin-assign-empty">Loading ticket logs…</p>
        ) : !filtered.length ? (
          <p className="swi-muted swi-admin-assign-empty">
            {logs.length
              ? "No logs match your filters."
              : "No ticket logs yet. Logs are created when tickets are raised or updated."}
          </p>
        ) : (
          <div className="swi-table-wrap swi-admin-assign-table-wrap">
            <table className="swi-table swi-admin-assign-table swi-admin-ticket-logs-table">
              <thead>
                <tr>
                  <th>Log ID</th>
                  <th>Ticket</th>
                  <th>Type</th>
                  <th>Status</th>
                  <th>Description</th>
                  <th>User</th>
                  <th>Created</th>
                  <th>Closed</th>
                  <th aria-label="Actions" />
                </tr>
              </thead>
              <tbody>
                {filtered.map((log) => {
                  const summary = ticketSummary(log);
                  return (
                    <tr key={log.id}>
                      <td data-label="Log ID">#{log.id}</td>
                      <td data-label="Ticket">
                        <span className="swi-admin-ticket-logs-table__ticket">
                          #{log.ticket_id}
                        </span>
                        {summary ? (
                          <span className="swi-muted small">{summary}</span>
                        ) : null}
                      </td>
                      <td data-label="Type">{log.ticket_type_name || "—"}</td>
                      <td data-label="Status">
                        <span
                          className={`swi-status-badge ${ticketStatusBadgeClass(log.status_id)}`}
                        >
                          {log.status_type || "—"}
                        </span>
                      </td>
                      <td data-label="Description" className="swi-admin-ticket-logs-table__desc">
                        {log.description || "—"}
                      </td>
                      <td data-label="User">{log.user_name || "—"}</td>
                      <td data-label="Created">{formatDateTime(log.created_at)}</td>
                      <td data-label="Closed">{formatDateTime(log.closed_at)}</td>
                      <td data-label="Actions">
                        <button
                          type="button"
                          className="swi-btn swi-btn--compact"
                          onClick={() => setDetailId(log.ticket_id)}
                        >
                          View ticket
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </section>

      <TicketDetailModal
        open={detailId != null}
        ticketId={detailId}
        onClose={() => setDetailId(null)}
        onUpdated={() => load().catch(() => {})}
        onDeleted={() => {
          setDetailId(null);
          load().catch(() => {});
        }}
      />
    </div>
  );
}
