import React, { useEffect, useState } from "react";
import {
  TICKET_STATUS,
  ticketStatusBadgeClass,
} from "../../../constants/ticketStatus.js";
import {
  closeTicket,
  deleteTicket,
  fetchTicket,
  startTicket,
} from "../../../services/ticketsApi.js";
import { getApiErrorMessage } from "../../../utils/apiError.js";

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",
  });
}

export default function TicketDetailModal({
  open,
  ticketId,
  onClose,
  onUpdated,
  onDeleted,
}) {
  const [ticket, setTicket] = useState(null);
  const [loading, setLoading] = useState(false);
  const [acting, setActing] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!open || !ticketId) return undefined;
    let cancelled = false;
    setLoading(true);
    setError("");
    fetchTicket(ticketId)
      .then((row) => {
        if (!cancelled) setTicket(row);
      })
      .catch((e) => {
        if (!cancelled) {
          setError(getApiErrorMessage(e, "Could not load ticket."));
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [open, ticketId]);

  useEffect(() => {
    if (!open) {
      setTicket(null);
      setError("");
    }
  }, [open]);

  if (!open) return null;

  const runAction = async (action) => {
    setActing(true);
    setError("");
    try {
      const updated = await action();
      setTicket(updated);
      onUpdated?.(updated);
    } catch (e) {
      setError(getApiErrorMessage(e, "Action failed."));
    } finally {
      setActing(false);
    }
  };

  const handleDelete = async () => {
    if (!window.confirm("Delete this ticket and all its logs?")) return;
    setActing(true);
    setError("");
    try {
      await deleteTicket(ticketId);
      onDeleted?.(ticketId);
      onClose();
    } catch (e) {
      setError(getApiErrorMessage(e, "Could not delete ticket."));
    } finally {
      setActing(false);
    }
  };

  const statusId = Number(ticket?.status_id);

  return (
    <div
      className="swi-modal-backdrop"
      role="presentation"
      onClick={acting ? undefined : onClose}
    >
      <div
        className="swi-modal swi-ticket-detail-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="ticket-detail-title"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="swi-modal__head">
          <h2 id="ticket-detail-title" className="swi-modal__title">
            Ticket #{ticketId}
          </h2>
          <button
            type="button"
            className="swi-modal__close"
            aria-label="Close"
            disabled={acting}
            onClick={onClose}
          >
            ×
          </button>
        </header>

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

        {loading ? (
          <p className="swi-muted">Loading ticket…</p>
        ) : ticket ? (
          <>
            <div className="swi-ticket-detail__head">
              <div>
                <h3 className="swi-ticket-detail__subject">
                  {ticket.description?.split(/\r?\n/)[0]?.trim() || "Ticket"}
                </h3>
                <p className="swi-muted small">
                  {ticket.ticket_type_name || "—"} · Raised by{" "}
                  {ticket.user_name || "—"}
                </p>
              </div>
              <span
                className={`swi-status-badge ${ticketStatusBadgeClass(ticket.status_id)}`}
              >
                {ticket.status_type || "Unknown"}
              </span>
            </div>

            <dl className="swi-ticket-detail__meta">
              <div>
                <dt>Created</dt>
                <dd>{formatDateTime(ticket.created_at)}</dd>
              </div>
              <div>
                <dt>Closed</dt>
                <dd>{formatDateTime(ticket.closed_at)}</dd>
              </div>
            </dl>

            <div className="swi-ticket-detail__description">
              <h4>Description</h4>
              <p>{ticket.description || "—"}</p>
            </div>

            <div className="swi-ticket-detail__actions">
              {statusId === TICKET_STATUS.OPEN ? (
                <button
                  type="button"
                  className="swi-btn swi-btn--ghost"
                  disabled={acting}
                  onClick={() => runAction(() => startTicket(ticketId))}
                >
                  Set in progress
                </button>
              ) : null}
              {statusId === TICKET_STATUS.IN_PROGRESS ? (
                <button
                  type="button"
                  className="swi-btn swi-btn--primary"
                  disabled={acting}
                  onClick={() => runAction(() => closeTicket(ticketId))}
                >
                  Resolve ticket
                </button>
              ) : null}
              <button
                type="button"
                className="swi-btn swi-btn--danger"
                disabled={acting}
                onClick={handleDelete}
              >
                Delete
              </button>
            </div>

            <section className="swi-ticket-detail__logs">
              <h4>Activity log</h4>
              {!ticket.logs?.length ? (
                <p className="swi-muted small">No log entries.</p>
              ) : (
                <ul className="swi-ticket-log-list">
                  {ticket.logs.map((log) => (
                    <li key={log.id}>
                      <div className="swi-ticket-log-list__top">
                        <strong>
                          {log.ticket_type_name ? `${log.ticket_type_name} · ` : ""}
                          {log.status_type || "Update"}
                        </strong>
                        <span className="swi-muted small">
                          {formatDateTime(log.created_at)}
                        </span>
                      </div>
                      <p>{log.description || "—"}</p>
                      {log.user_name ? (
                        <span className="swi-muted small">By {log.user_name}</span>
                      ) : null}
                      {log.closed_at ? (
                        <span className="swi-muted small">
                          {" "}
                          · Closed {formatDateTime(log.closed_at)}
                        </span>
                      ) : null}
                    </li>
                  ))}
                </ul>
              )}
            </section>
          </>
        ) : null}
      </div>
    </div>
  );
}
