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 './styles/TicketLogs.css';

const STATUS_FILTER_ALL = 'all';
const STATUS_OPEN = 1;
const STATUS_IN_PROGRESS = 2;
const STATUS_RESOLVED = 3;

const TicketLogs = () => {
  const navigate = useNavigate();
  const [tickets, setTickets] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [statusFilter, setStatusFilter] = useState(STATUS_FILTER_ALL);
  const [detailTicket, setDetailTicket] = useState(null);
  const [detailLoading, setDetailLoading] = useState(false);

  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 ticket logs.');
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load ticket logs.');
      setTickets([]);
    } finally {
      setLoading(false);
    }
  };

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

  const filteredTickets = tickets.filter((t) => {
    if (statusFilter === STATUS_FILTER_ALL) return true;
    return Number(t.status_id) === Number(statusFilter);
  });

  const stats = {
    open: tickets.filter((t) => Number(t.status_id) === STATUS_OPEN).length,
    inProgress: tickets.filter((t) => Number(t.status_id) === STATUS_IN_PROGRESS).length,
    resolved: tickets.filter((t) => Number(t.status_id) === STATUS_RESOLVED).length
  };

  const openLogDetail = async (id) => {
    setDetailLoading(true);
    setDetailTicket(null);
    try {
      const res = await axiosInstance.get(`${TICKETS_URL}/${id}`);
      if (res.data.success) setDetailTicket(res.data.data);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load ticket activity.');
    } finally {
      setDetailLoading(false);
    }
  };

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

  // Build timeline: created + logs (newest first in API, we show chronological) + closed
  const getTimeline = (ticket) => {
    const items = [];
    if (ticket.created_at) {
      items.push({
        id: 'created',
        date: ticket.created_at,
        label: 'Ticket created',
        description: 'Ticket was raised.',
        user_name: ticket.user_name
      });
    }
    if (ticket.logs && ticket.logs.length > 0) {
      const sortedLogs = [...ticket.logs].sort(
        (a, b) => new Date(a.created_at) - new Date(b.created_at)
      );
      sortedLogs.forEach((log, idx) => {
        if (log.description && log.description !== 'Ticket created') {
          items.push({
            id: `log-${log.id}-${idx}`,
            date: log.created_at,
            label: 'Activity',
            description: log.description,
            user_name: log.user_name
          });
        }
      });
    }
    if (ticket.closed_at) {
      items.push({
        id: 'closed',
        date: ticket.closed_at,
        label: 'Ticket closed',
        description: 'Ticket was resolved.',
        user_name: null
      });
    }
    items.sort((a, b) => new Date(a.date) - new Date(b.date));
    return items;
  };

  if (loading) {
    return (
      <div className="ticket-logs-page">
        <div className="ticket-logs-loading-wrap">
          <div className="ticket-logs-spinner" aria-hidden="true" />
          <p className="ticket-logs-loading-text">Loading ticket logs...</p>
        </div>
      </div>
    );
  }

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

      <header className="ticket-logs-header">
        <div className="ticket-logs-header-text">
          <h1>Ticket Logs</h1>
          <p className="ticket-logs-subtitle">
            View all ticket activity: when each ticket was generated, updated, and closed.
          </p>
        </div>
        <div className="ticket-logs-header-actions">
          <button
            type="button"
            className="ticket-logs-btn-secondary"
            onClick={() => navigate('/tickets')}
          >
            Ticket Progress
          </button>
          <button
            type="button"
            className="ticket-logs-btn-primary"
            onClick={() => navigate('/raise-ticket')}
          >
            Raise Ticket
          </button>
        </div>
      </header>

      <div className="ticket-logs-stats">
        <div className="ticket-logs-stat-card ticket-logs-stat-open">
          <span className="ticket-logs-stat-value">{stats.open}</span>
          <span className="ticket-logs-stat-label">Open</span>
        </div>
        <div className="ticket-logs-stat-card ticket-logs-stat-in-progress">
          <span className="ticket-logs-stat-value">{stats.inProgress}</span>
          <span className="ticket-logs-stat-label">In Progress</span>
        </div>
        <div className="ticket-logs-stat-card ticket-logs-stat-resolved">
          <span className="ticket-logs-stat-value">{stats.resolved}</span>
          <span className="ticket-logs-stat-label">Resolved</span>
        </div>
      </div>

      <div className="ticket-logs-filters">
        <span className="ticket-logs-filter-label">Status:</span>
        <button
          type="button"
          className={`ticket-logs-filter-btn ${statusFilter === STATUS_FILTER_ALL ? 'active' : ''}`}
          onClick={() => setStatusFilter(STATUS_FILTER_ALL)}
        >
          All
        </button>
        <button
          type="button"
          className={`ticket-logs-filter-btn ${statusFilter === String(STATUS_OPEN) ? 'active' : ''}`}
          onClick={() => setStatusFilter(String(STATUS_OPEN))}
        >
          Open
        </button>
        <button
          type="button"
          className={`ticket-logs-filter-btn ${statusFilter === String(STATUS_IN_PROGRESS) ? 'active' : ''}`}
          onClick={() => setStatusFilter(String(STATUS_IN_PROGRESS))}
        >
          In Progress
        </button>
        <button
          type="button"
          className={`ticket-logs-filter-btn ${statusFilter === String(STATUS_RESOLVED) ? 'active' : ''}`}
          onClick={() => setStatusFilter(String(STATUS_RESOLVED))}
        >
          Resolved
        </button>
      </div>

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

      <section className="ticket-logs-section" aria-labelledby="ticket-logs-title">
        <div className="ticket-logs-section-header">
          <h2 id="ticket-logs-title" className="ticket-logs-section-title">All tickets</h2>
          {tickets.length > 0 && (
            <span className="ticket-logs-section-count">
              {filteredTickets.length} of {tickets.length} ticket{tickets.length !== 1 ? 's' : ''}
            </span>
          )}
        </div>

        <div className="ticket-logs-table-wrap">
          <table className="ticket-logs-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Subject</th>
                <th>Type</th>
                <th>Raised by</th>
                <th>Status</th>
                <th>Created</th>
                <th>Closed</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {filteredTickets.length === 0 ? (
                <tr>
                  <td colSpan={8} className="ticket-logs-empty-cell">
                    <p>
                      {tickets.length === 0
                        ? 'No tickets yet. Raise a ticket to see logs here.'
                        : 'No tickets match the selected status.'}
                    </p>
                    {tickets.length === 0 && (
                      <button
                        type="button"
                        className="ticket-logs-empty-btn"
                        onClick={() => navigate('/raise-ticket')}
                      >
                        Raise a ticket
                      </button>
                    )}
                  </td>
                </tr>
              ) : (
                filteredTickets.map((t) => (
                  <tr key={t.id} className="ticket-logs-row">
                    <td className="ticket-logs-col-id" data-label="ID">#{t.id}</td>
                    <td className="ticket-logs-col-subject" data-label="Subject" title={t.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 className="ticket-logs-col-date" data-label="Created">
                      {t.created_at ? new Date(t.created_at).toLocaleString() : '—'}
                    </td>
                    <td className="ticket-logs-col-date" data-label="Closed">
                      {t.closed_at ? new Date(t.closed_at).toLocaleString() : '—'}
                    </td>
                    <td className="ticket-logs-col-actions" data-label="Actions">
                      <button
                        type="button"
                        className="ticket-logs-btn-view"
                        onClick={() => openLogDetail(t.id)}
                        title="View full activity log"
                      >
                        View log
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </section>

      {detailTicket && (
        <div
          className="ticket-logs-overlay"
          onClick={() => setDetailTicket(null)}
          role="presentation"
        >
          <div
            className="ticket-logs-modal"
            onClick={(e) => e.stopPropagation()}
            role="dialog"
            aria-modal="true"
            aria-label="Ticket activity log"
          >
            <div className="ticket-logs-modal-header">
              <h2>Ticket #{detailTicket.id} – Activity log</h2>
              <button
                type="button"
                className="ticket-logs-modal-close"
                onClick={() => setDetailTicket(null)}
                aria-label="Close"
              >
                ×
              </button>
            </div>
            {detailLoading ? (
              <div className="ticket-logs-modal-loading">Loading activity...</div>
            ) : (
              <div className="ticket-logs-modal-body">
                <div className="ticket-logs-modal-meta">
                  <div className="ticket-logs-modal-meta-row">
                    <span className="ticket-logs-modal-label">Subject</span>
                    <span className="ticket-logs-modal-value">{detailTicket.subject || '—'}</span>
                  </div>
                  <div className="ticket-logs-modal-meta-row">
                    <span className="ticket-logs-modal-label">Type</span>
                    <span className="ticket-logs-modal-value">{detailTicket.ticket_type_name || '—'}</span>
                  </div>
                  <div className="ticket-logs-modal-meta-row">
                    <span className="ticket-logs-modal-label">Status</span>
                    <span className={statusBadgeClass(detailTicket.status_type)}>
                      {detailTicket.status_type || '—'}
                    </span>
                  </div>
                  <div className="ticket-logs-modal-meta-row">
                    <span className="ticket-logs-modal-label">Raised by</span>
                    <span className="ticket-logs-modal-value">
                      {detailTicket.user_name || '—'}
                      {detailTicket.user_email ? ` (${detailTicket.user_email})` : ''}
                    </span>
                  </div>
                </div>
                <div className="ticket-logs-timeline-block">
                  <h3 className="ticket-logs-timeline-title">Timeline</h3>
                  <ul className="ticket-logs-timeline">
                    {getTimeline(detailTicket).length === 0 ? (
                      <li className="ticket-logs-timeline-item ticket-logs-timeline-empty">
                        No activity recorded.
                      </li>
                    ) : (
                      getTimeline(detailTicket).map((item) => (
                        <li key={item.id} className="ticket-logs-timeline-item">
                          <time className="ticket-logs-timeline-date" dateTime={item.date}>
                            {new Date(item.date).toLocaleString()}
                          </time>
                          <span className="ticket-logs-timeline-label">{item.label}</span>
                          <p className="ticket-logs-timeline-desc">{item.description}</p>
                          {item.user_name && (
                            <span className="ticket-logs-timeline-user">by {item.user_name}</span>
                          )}
                        </li>
                      ))
                    )}
                  </ul>
                </div>
                <div className="ticket-logs-modal-actions">
                  <button
                    type="button"
                    className="ticket-logs-btn-secondary"
                    onClick={() => setDetailTicket(null)}
                  >
                    Close
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default TicketLogs;
