import React, { useEffect, useState } from "react";
import GlassSelect from "../../common/GlassSelect.jsx";
import { createTicket, fetchTicketTypes } from "../../../services/ticketsApi.js";
import { fetchUsers } from "../../../services/swiApi.js";
import { getApiErrorMessage } from "../../../utils/apiError.js";

function labelForUser(u) {
  return u.employee_name || u.email_id || `User #${u.user_id}`;
}

export default function RaiseTicketModal({ open, onClose, onCreated }) {
  const [types, setTypes] = useState([]);
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [form, setForm] = useState({
    user_id: "",
    ticket_type_id: "",
    subject: "",
    description: "",
    recipient_email: "",
  });

  useEffect(() => {
    if (!open) return undefined;
    let cancelled = false;
    setError("");
    setLoading(true);
    Promise.all([fetchTicketTypes(), fetchUsers()])
      .then(([typeRows, userRows]) => {
        if (cancelled) return;
        setTypes(typeRows || []);
        setUsers(userRows || []);
      })
      .catch((e) => {
        if (!cancelled) {
          setError(getApiErrorMessage(e, "Could not load form data."));
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [open]);

  useEffect(() => {
    if (!open) {
      setForm({
        user_id: "",
        ticket_type_id: "",
        subject: "",
        description: "",
        recipient_email: "",
      });
      setError("");
    }
  }, [open]);

  if (!open) return null;

  const submit = async (event) => {
    event.preventDefault();
    if (!form.user_id || !form.ticket_type_id || !form.description.trim()) {
      setError("User, type, and description are required.");
      return;
    }
    setSaving(true);
    setError("");
    try {
      const ticket = await createTicket({
        user_id: Number(form.user_id),
        ticket_type_id: Number(form.ticket_type_id),
        subject: form.subject.trim() || undefined,
        description: form.description.trim(),
        recipient_email: form.recipient_email.trim() || undefined,
      });
      onCreated?.(ticket);
      onClose();
    } catch (e) {
      setError(getApiErrorMessage(e, "Could not create ticket."));
    } finally {
      setSaving(false);
    }
  };

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

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

        {loading ? (
          <p className="swi-muted">Loading form…</p>
        ) : (
          <form onSubmit={submit}>
            <div className="swi-form-row">
              <label htmlFor="ticket_user">Raised for (user) *</label>
              <GlassSelect
                id="ticket_user"
                value={form.user_id}
                onChange={(value) =>
                  setForm((f) => ({ ...f, user_id: value }))
                }
                placeholder="Select user"
                options={users.map((u) => ({
                  value: u.user_id,
                  label: labelForUser(u),
                }))}
                aria-label="User"
              />
            </div>
            <div className="swi-form-row">
              <label htmlFor="ticket_type">Ticket type *</label>
              <GlassSelect
                id="ticket_type"
                value={form.ticket_type_id}
                onChange={(value) =>
                  setForm((f) => ({ ...f, ticket_type_id: value }))
                }
                placeholder="Select type"
                options={types.map((t) => ({
                  value: t.type_id,
                  label: t.type_name,
                }))}
                aria-label="Ticket type"
              />
            </div>
            <div className="swi-form-row">
              <label htmlFor="ticket_subject">Subject</label>
              <input
                id="ticket_subject"
                className="swi-input"
                value={form.subject}
                onChange={(e) =>
                  setForm((f) => ({ ...f, subject: e.target.value }))
                }
                placeholder="Brief summary"
              />
            </div>
            <div className="swi-form-row">
              <label htmlFor="ticket_description">Description *</label>
              <textarea
                id="ticket_description"
                className="swi-textarea"
                value={form.description}
                onChange={(e) =>
                  setForm((f) => ({ ...f, description: e.target.value }))
                }
                placeholder="Describe the issue or request…"
                required
              />
            </div>
            <div className="swi-form-row">
              <label htmlFor="ticket_recipient">Recipient email</label>
              <input
                id="ticket_recipient"
                type="email"
                className="swi-input"
                value={form.recipient_email}
                onChange={(e) =>
                  setForm((f) => ({ ...f, recipient_email: e.target.value }))
                }
                placeholder="Optional notification email"
              />
            </div>
            <div className="swi-modal-actions">
              <button
                type="button"
                className="swi-btn swi-btn--ghost"
                disabled={saving}
                onClick={onClose}
              >
                Cancel
              </button>
              <button
                type="submit"
                className="swi-btn swi-btn--primary"
                disabled={saving}
              >
                {saving ? "Creating…" : "Create ticket"}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
