import React, { useMemo, useState } from "react";
import PageHeader from "../../components/common/PageHeader.jsx";
import ErrorBanner from "../../components/common/ErrorBanner.jsx";
import useMasterData from "../../hooks/useMasterData.js";
import { listUsers } from "../../services/usersApi.js";
import { createTicket } from "../../services/ticketsApi.js";

export default function AdminRaiseTicketPage({ onNavigate }) {
  const { data } = useMasterData();
  const [users, setUsers] = useState([]);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [draft, setDraft] = useState({ description: "", user_id: "", ticket_type_id: "", status_id: "" });

  React.useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const list = await listUsers();
        if (mounted) setUsers(list);
      } catch (err) {
        if (mounted) setError(err?.response?.data?.message || err.message);
      }
    })();
    return () => {
      mounted = false;
    };
  }, []);

  const statusOptions = useMemo(() => data.tickets_status || [], [data.tickets_status]);
  const typeOptions = useMemo(() => data.tickets_type || [], [data.tickets_type]);

  const defaultOpenStatus = useMemo(
    () => statusOptions.find((row) => /open/i.test(row.status_type || ""))?.status_id || "",
    [statusOptions]
  );

  React.useEffect(() => {
    if (!draft.status_id && defaultOpenStatus) {
      setDraft((prev) => ({ ...prev, status_id: String(defaultOpenStatus) }));
    }
  }, [defaultOpenStatus, draft.status_id]);

  const submit = async () => {
    if (!draft.description.trim()) {
      setError("Please enter a description for the ticket.");
      return;
    }
    try {
      setSubmitting(true);
      setError("");
      setSuccess("");
      await createTicket({
        description: draft.description.trim(),
        user_id: draft.user_id ? Number(draft.user_id) : null,
        ticket_type_id: draft.ticket_type_id ? Number(draft.ticket_type_id) : null,
        status_id: draft.status_id ? Number(draft.status_id) : null
      });
      setSuccess("Ticket raised successfully. It is now visible in the ticket list.");
      setDraft({ description: "", user_id: "", ticket_type_id: "", status_id: String(defaultOpenStatus || "") });
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="portal-page ptw-ticket-raise-page">
      <PageHeader
        title="Raise Ticket"
        subtitle="Submit a structured support request for the PTW administration team."
        actions={(
          <button type="button" className="swi-btn swi-btn--ghost" onClick={() => onNavigate("ticket-list")}>
            View ticket list
          </button>
        )}
      />

      <ErrorBanner message={error} />
      {success ? <p className="ptw-mgmt-success-banner" role="status">{success}</p> : null}

      <div className="ptw-ticket-raise">
        <aside className="ptw-ticket-raise__aside" aria-label="Submission guidance">
          <div className="ptw-ticket-raise__aside-card">
            <h2 className="ptw-ticket-raise__aside-title">Submission guidelines</h2>
            <p className="ptw-ticket-raise__aside-lead">
              Provide enough detail for the support team to triage and assign your request promptly.
            </p>
            <ul className="ptw-ticket-raise__aside-list">
              <li>Describe the issue, affected permit or form, and when it occurred.</li>
              <li>Select the requester and ticket type so routing is accurate.</li>
              <li>Leave the initial status as Open unless instructed otherwise.</li>
            </ul>
          </div>
        </aside>

        <section className="ptw-ticket-raise__form" aria-labelledby="ptw-ticket-raise-form-title">
          <header className="ptw-ticket-raise__form-head">
            <div>
              <h2 id="ptw-ticket-raise-form-title" className="ptw-ticket-raise__form-title">Ticket request form</h2>
              <p className="ptw-ticket-raise__form-subtitle">All fields marked with * are required.</p>
            </div>
          </header>

          <div className="ptw-ticket-raise__section">
            <h3 className="ptw-ticket-raise__section-title">Issue description</h3>
            <label className="ptw-ticket-raise__field ptw-ticket-raise__field--full">
              <span className="ptw-ticket-raise__label">
                Description <span className="ptw-ticket-raise__required" aria-hidden>*</span>
              </span>
              <textarea
                className="swi-input swi-textarea ptw-ticket-raise__control"
                rows={5}
                value={draft.description}
                placeholder="Summarize the issue, steps to reproduce, and any permit or form references."
                onChange={(e) => setDraft((prev) => ({ ...prev, description: e.target.value }))}
              />
            </label>
          </div>

          <div className="ptw-ticket-raise__section">
            <h3 className="ptw-ticket-raise__section-title">Classification</h3>
            <div className="ptw-ticket-raise__grid">
              <label className="ptw-ticket-raise__field">
                <span className="ptw-ticket-raise__label">Requested by user</span>
                <select
                  className="swi-input ptw-ticket-raise__control"
                  value={draft.user_id}
                  onChange={(e) => setDraft((prev) => ({ ...prev, user_id: e.target.value }))}
                >
                  <option value="">Select user</option>
                  {users.map((u) => (
                    <option key={u.user_id} value={u.user_id}>
                      {u.employee_name || `User #${u.user_id}`}
                    </option>
                  ))}
                </select>
              </label>
              <label className="ptw-ticket-raise__field">
                <span className="ptw-ticket-raise__label">Ticket type</span>
                <select
                  className="swi-input ptw-ticket-raise__control"
                  value={draft.ticket_type_id}
                  onChange={(e) => setDraft((prev) => ({ ...prev, ticket_type_id: e.target.value }))}
                >
                  <option value="">Select type</option>
                  {typeOptions.map((t) => (
                    <option key={t.type_id} value={t.type_id}>{t.type_name}</option>
                  ))}
                </select>
              </label>
              <label className="ptw-ticket-raise__field">
                <span className="ptw-ticket-raise__label">Initial status</span>
                <select
                  className="swi-input ptw-ticket-raise__control"
                  value={draft.status_id}
                  onChange={(e) => setDraft((prev) => ({ ...prev, status_id: e.target.value }))}
                >
                  <option value="">Select status</option>
                  {statusOptions.map((s) => (
                    <option key={s.status_id} value={s.status_id}>{s.status_type}</option>
                  ))}
                </select>
              </label>
            </div>
          </div>

          <footer className="ptw-ticket-raise__footer">
            <p className="ptw-ticket-raise__footer-note">
              Submitted tickets are logged and can be tracked from the ticket list.
            </p>
            <div className="ptw-ticket-raise__footer-actions">
              <button
                type="button"
                className="swi-btn swi-btn--ghost"
                onClick={() => onNavigate("ticket-list")}
              >
                Cancel
              </button>
              <button
                type="button"
                className="swi-btn swi-btn--primary"
                onClick={submit}
                disabled={submitting}
              >
                {submitting ? "Submitting…" : "Raise ticket"}
              </button>
            </div>
          </footer>
        </section>
      </div>
    </div>
  );
}
