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

const TicketsList = () => {
  const navigate = useNavigate();
  const [tickets, setTickets] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [closingId, setClosingId] = useState(null);

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

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

  const handleCloseTicket = async (id) => {
    setClosingId(id);
    try {
      const res = await axiosInstance.put(`${TICKETS_URL}/${id}/close`);
      if (res.data.success) {
        setTickets((prev) =>
          prev.map((t) =>
            t.id === id ? { ...t, status_id: 3, status_type: 'Resolved', closed_at: new Date().toISOString() } : t
          )
        );
      } else {
        setError(res.data.message || 'Failed to close ticket.');
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to close ticket.');
    } finally {
      setClosingId(null);
    }
  };

  const statusBadgeClass = (statusType) => {
    if (!statusType) return 'ticket-status';
    const s = String(statusType).toLowerCase();
    if (s === 'open') return 'ticket-status ticket-status-open';
    if (s === 'in progress') return 'ticket-status ticket-status-in-progress';
    if (s === 'resolved') return 'ticket-status ticket-status-resolved';
    return 'ticket-status';
  };

  const isOpen = (t) => Number(t.status_id) === 1;

  if (loading) {
    return (
      <div className="tickets-list-page">
        <div className="tickets-list-loading">Loading tickets...</div>
      </div>
    );
  }

  return (
    <div className="tickets-list-page">
      <div className="tickets-list-header">
        <h1>My Tickets</h1>
        <button type="button" className="btn-raise" onClick={() => navigate('/raise-ticket')}>
          Raise Ticket
        </button>
      </div>
      {error && <div className="tickets-list-error">{error}</div>}
      <div className="tickets-list-table-wrap">
        <table className="tickets-list-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>Subject</th>
              <th>Type</th>
              <th>Raised by</th>
              <th>Status</th>
              <th>Created</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {tickets.length === 0 ? (
              <tr className="tickets-list-empty-row">
                <td colSpan={7} className="tickets-empty">
                  No tickets yet. <button type="button" className="link-btn" onClick={() => navigate('/raise-ticket')}>Raise a ticket</button>
                </td>
              </tr>
            ) : (
              tickets.map((t) => (
                <tr key={t.id} className="tickets-list-row">
                  <td data-label="ID">{t.id}</td>
                  <td data-label="Subject">{t.subject || '-'}</td>
                  <td data-label="Type">{t.ticket_type_name || '-'}</td>
                  <td data-label="Raised by">{t.user_name || '-'}</td>
                  <td data-label="Status">
                    <span className={statusBadgeClass(t.status_type)}>{t.status_type || '-'}</span>
                  </td>
                  <td data-label="Created">{t.created_at ? new Date(t.created_at).toLocaleString() : '-'}</td>
                  <td data-label="Actions">
                    {isOpen(t) ? (
                      <button
                        type="button"
                        className="btn-close-ticket"
                        onClick={() => handleCloseTicket(t.id)}
                        disabled={closingId === t.id}
                      >
                        {closingId === t.id ? 'Closing...' : 'Close'}
                      </button>
                    ) : (
                      <span className="ticket-closed-label">Closed</span>
                    )}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default TicketsList;
