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

const STATUS_ALL = "all";

function formatDate(value) {
  if (!value) return "—";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return "—";
  return d.toLocaleDateString(undefined, {
    year: "numeric",
    month: "short",
    day: "numeric",
  });
}

export default function AdminTicketsPage() {
  const [tickets, setTickets] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [statusFilter, setStatusFilter] = useState(STATUS_ALL);
  const [query, setQuery] = useState("");
  const [raiseOpen, setRaiseOpen] = useState(false);
  const [detailId, setDetailId] = useState(null);

  const load = useCallback(async () => {
    setError("");
    const rows = await fetchTickets();
    setTickets(Array.isArray(rows) ? rows : []);
  }, []);

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

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return tickets.filter((t) => {
      if (
        statusFilter !== STATUS_ALL &&
        Number(t.status_id) !== Number(statusFilter)
      ) {
        return false;
      }
      if (!q) return true;
      const desc = (t.description || "").toLowerCase();
      const user = (t.user_name || "").toLowerCase();
      const type = (t.ticket_type_name || "").toLowerCase();
      return (
        desc.includes(q) ||
        user.includes(q) ||
        type.includes(q) ||
        desc.includes(q) ||
        String(t.id).includes(q)
      );
    });
  }, [tickets, statusFilter, query]);

  const counts = useMemo(
    () => ({
      open: tickets.filter((t) => Number(t.status_id) === TICKET_STATUS.OPEN)
        .length,
      inProgress: tickets.filter(
        (t) => Number(t.status_id) === TICKET_STATUS.IN_PROGRESS
      ).length,
      resolved: tickets.filter(
        (t) => Number(t.status_id) === TICKET_STATUS.RESOLVED
      ).length,
    }),
    [tickets]
  );

  const handleCreated = (ticket) => {
    setSuccess(`Ticket #${ticket.id} created.`);
    load().catch(() => {});
  };

  const handleUpdated = () => {
    setSuccess("Ticket updated.");
    load().catch(() => {});
  };

  const handleDeleted = (id) => {
    setSuccess(`Ticket #${id} deleted.`);
    setDetailId(null);
    load().catch(() => {});
  };

  return (
    <div className="swi-admin-tickets">
      <AdminPageHeader
        title="Tickets"
        subtitle="Create, track, and resolve support tickets."
        actions={
          <button
            type="button"
            className="swi-btn swi-btn--primary"
            onClick={() => setRaiseOpen(true)}
          >
            Raise ticket
          </button>
        }
      />

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

      <div className="swi-admin-assign-toolbar swi-panel">
        <div className="swi-admin-assign-stats">
          <span className="swi-admin-assign-stat">
            <strong>{counts.open}</strong> open
          </span>
          <span className="swi-admin-assign-stat">
            <strong>{counts.inProgress}</strong> in progress
          </span>
          <span className="swi-admin-assign-stat">
            <strong>{counts.resolved}</strong> resolved
          </span>
        </div>
        <div className="swi-admin-tickets__filters">
          <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 tickets…"
            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 tickets…</p>
        ) : !filtered.length ? (
          <p className="swi-muted swi-admin-assign-empty">
            {tickets.length
              ? "No tickets match your filters."
              : "No tickets yet. Click Raise ticket to create one."}
          </p>
        ) : (
          <div className="swi-table-wrap swi-admin-assign-table-wrap">
            <table className="swi-table swi-admin-assign-table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Subject</th>
                  <th>Type</th>
                  <th>Raised by</th>
                  <th>Created</th>
                  <th>Status</th>
                  <th aria-label="Actions" />
                </tr>
              </thead>
              <tbody>
                {filtered.map((t) => (
                  <tr key={t.id}>
                    <td data-label="ID">#{t.id}</td>
                    <td data-label="Subject">
                      {t.description?.split(/\r?\n/)[0]?.slice(0, 80) || "—"}
                    </td>
                    <td data-label="Type">{t.ticket_type_name || "—"}</td>
                    <td data-label="Raised by">{t.user_name || "—"}</td>
                    <td data-label="Created">{formatDate(t.created_at)}</td>
                    <td data-label="Status">
                      <span
                        className={`swi-status-badge ${ticketStatusBadgeClass(t.status_id)}`}
                      >
                        {t.status_type || "Unknown"}
                      </span>
                    </td>
                    <td data-label="Actions">
                      <button
                        type="button"
                        className="swi-btn swi-btn--compact"
                        onClick={() => setDetailId(t.id)}
                      >
                        View
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      <RaiseTicketModal
        open={raiseOpen}
        onClose={() => setRaiseOpen(false)}
        onCreated={handleCreated}
      />

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