import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import axiosInstance from '../../../utils/axiosConfig';
import { TICKETS_URL } from '../../../utils/config';
import SuccessPopup from '../../common/SuccessPopup';
import './styles/CloseTicket.css';

const STATUS_OPEN = 1;
const STATUS_IN_PROGRESS = 2;

const CheckIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
    <polyline points="22 4 12 14.01 9 11.01" />
  </svg>
);

const TicketIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" />
    <polyline points="14 2 14 8 20 8" />
    <line x1="16" y1="13" x2="8" y2="13" />
    <line x1="16" y1="17" x2="8" y2="17" />
  </svg>
);

const CloseTicket = () => {
  const navigate = useNavigate();
  const [tickets, setTickets] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [closingId, setClosingId] = useState(null);
  const [showPopup, setShowPopup] = useState(false);
  const [popupMessage, setPopupMessage] = useState('');
  const [closeById, setCloseById] = useState('');
  const [closingById, setClosingById] = useState(false);

  const fetchTickets = async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await axiosInstance.get(TICKETS_URL);
      if (res.data.success) {
        const all = res.data.data || [];
        setTickets(all.filter((t) => Number(t.status_id) === STATUS_OPEN || Number(t.status_id) === STATUS_IN_PROGRESS));
      } else {
        setError('Failed to load tickets.');
        setTickets([]);
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load tickets.');
      setTickets([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTickets();
  }, []);

  const handleResolveTicket = async (id) => {
    setClosingId(id);
    setError(null);
    try {
      const res = await axiosInstance.put(`${TICKETS_URL}/${id}/close`);
      if (res.data.success) {
        setTickets((prev) => prev.filter((t) => t.id !== id));
        setPopupMessage(`Ticket #${id} has been resolved successfully.`);
        setShowPopup(true);
      } else {
        setError(res.data.message || 'Failed to resolve ticket.');
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to resolve ticket.');
    } finally {
      setClosingId(null);
    }
  };

  const handleCloseById = async (e) => {
    e.preventDefault();
    const id = closeById.trim();
    if (!id) {
      setError('Enter a ticket ID.');
      return;
    }
    setClosingById(true);
    setError(null);
    try {
      const res = await axiosInstance.put(`${TICKETS_URL}/${id}/close`);
      if (res.data.success) {
        setCloseById('');
        setTickets((prev) => prev.filter((t) => String(t.id) !== id));
        setPopupMessage(`Ticket #${id} has been resolved successfully.`);
        setShowPopup(true);
        fetchTickets();
      } else {
        setError(res.data.message || 'Failed to resolve ticket.');
      }
    } catch (err) {
      const msg = err.response?.data?.message || err.message || 'Failed to resolve ticket.';
      setError(err.response?.status === 404 ? `Ticket #${id} not found or already resolved.` : msg);
    } finally {
      setClosingById(false);
    }
  };

  if (loading) {
    return (
      <div className="close-ticket-page">
        <div className="close-ticket-loading-wrap">
          <div className="close-ticket-spinner" aria-hidden="true" />
          <p className="close-ticket-loading-text">Loading open and in-progress tickets...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="close-ticket-page">
      <nav className="close-ticket-breadcrumb" aria-label="Breadcrumb">
        <Link to="/tickets" className="close-ticket-breadcrumb-link">Tickets</Link>
        <span className="close-ticket-breadcrumb-sep">/</span>
        <span className="close-ticket-breadcrumb-current">Resolve Ticket</span>
      </nav>

      <header className="close-ticket-header">
        <div className="close-ticket-header-icon" aria-hidden="true">
          <CheckIcon />
        </div>
        <div className="close-ticket-header-text">
          <h1>Resolve Ticket</h1>
          <p className="close-ticket-subtitle">
            Mark tickets as resolved once the issue is fixed. Only <strong>Open</strong> or <strong>In Progress</strong> tickets appear below.
          </p>
        </div>
        <div className="close-ticket-header-actions">
          <button type="button" className="close-ticket-btn-secondary" onClick={() => navigate('/tickets')}>
            Ticket Progress
          </button>
          <button type="button" className="close-ticket-btn-primary" onClick={() => navigate('/raise-ticket')}>
            Raise Ticket
          </button>
        </div>
      </header>

      <section className="close-by-id-section" aria-labelledby="resolve-by-id-title">
        <div className="close-by-id-header">
          <span className="close-by-id-icon" aria-hidden="true"><TicketIcon /></span>
          <h2 id="resolve-by-id-title" className="close-by-id-title">Resolve by ticket ID</h2>
        </div>
        <form onSubmit={handleCloseById} className="close-by-id-form">
          <input
            type="text"
            inputMode="numeric"
            pattern="[0-9]*"
            placeholder="Enter ticket ID (e.g. 1)"
            value={closeById}
            onChange={(e) => setCloseById(e.target.value)}
            className="close-by-id-input"
            aria-label="Ticket ID"
          />
          <button type="submit" className="close-by-id-submit" disabled={closingById || !closeById.trim()}>
            {closingById ? (
              <>
                <span className="close-by-id-btn-spinner" aria-hidden="true" />
                Resolving...
              </>
            ) : (
              'Resolve ticket'
            )}
          </button>
        </form>
      </section>

      {error && (
        <div className="close-ticket-error" role="alert">
          <span className="close-ticket-error-icon" aria-hidden="true">!</span>
          {error}
        </div>
      )}

      <section className="close-ticket-list-section" aria-labelledby="tickets-list-title">
        <div className="close-ticket-list-header">
          <h2 id="tickets-list-title" className="close-ticket-list-title">Open / In Progress tickets</h2>
          {tickets.length > 0 && (
            <span className="close-ticket-list-count">{tickets.length} ticket{tickets.length !== 1 ? 's' : ''}</span>
          )}
        </div>
        <div className="close-ticket-list-wrap">
          {tickets.length === 0 ? (
            <div className="close-ticket-empty">
              <div className="close-ticket-empty-icon" aria-hidden="true"><CheckIcon /></div>
              <p className="close-ticket-empty-title">No tickets to resolve</p>
              <p className="close-ticket-empty-desc">There are no open or in-progress tickets at the moment.</p>
              <button type="button" className="close-ticket-empty-link" onClick={() => navigate('/tickets')}>
                View all tickets
              </button>
            </div>
          ) : (
            <div className="close-ticket-cards">
              {tickets.map((t) => (
                <article key={t.id} className="close-ticket-card">
                  <div className="close-ticket-card-main">
                    <div className="close-ticket-card-id">#{t.id}</div>
                    <h3 className="close-ticket-card-subject">{t.subject || 'No subject'}</h3>
                    <div className="close-ticket-card-meta">
                      <span className="close-ticket-card-type">{t.ticket_type_name || '-'}</span>
                      <span className="close-ticket-card-sep">·</span>
                      <span className="close-ticket-card-user">{t.user_name || '-'}</span>
                    </div>
                    <time className="close-ticket-card-date" dateTime={t.created_at || ''}>
                      {t.created_at ? new Date(t.created_at).toLocaleString() : '-'}
                    </time>
                  </div>
                  <div className="close-ticket-card-action">
                    <button
                      type="button"
                      className="close-ticket-card-btn"
                      onClick={() => handleResolveTicket(t.id)}
                      disabled={closingId === t.id}
                    >
                      {closingId === t.id ? (
                        <>
                          <span className="close-ticket-card-btn-spinner" aria-hidden="true" />
                          Resolving...
                        </>
                      ) : (
                        'Resolve'
                      )}
                    </button>
                  </div>
                </article>
              ))}
            </div>
          )}
        </div>
      </section>

      <SuccessPopup
        show={showPopup}
        message={popupMessage}
        onClose={() => {
          setShowPopup(false);
          fetchTickets();
        }}
      />
    </div>
  );
};

export default CloseTicket;
