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

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

const TicketProgress = () => {
  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 [closingId, setClosingId] = useState(null);
  const [workingOnId, setWorkingOnId] = useState(null);
  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 tickets.');
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load tickets.');
      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 handleSetInProgress = async (id) => {
    setWorkingOnId(id);
    setError(null);
    try {
      const res = await axiosInstance.put(`${TICKETS_URL}/${id}`, { status_id: STATUS_IN_PROGRESS });
      if (res.data.success) {
        setTickets((prev) =>
          prev.map((t) =>
            t.id === id
              ? { ...t, status_id: STATUS_IN_PROGRESS, status_type: 'In Progress' }
              : t
          )
        );
        if (detailTicket?.id === id) {
          setDetailTicket((prev) =>
            prev ? { ...prev, status_id: STATUS_IN_PROGRESS, status_type: 'In Progress' } : null
          );
        }
      } else {
        setError(res.data.message || 'Failed to set ticket in progress.');
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to set ticket in progress.');
    } finally {
      setWorkingOnId(null);
    }
  };

  const handleResolveTicket = 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: STATUS_RESOLVED, status_type: 'Resolved', closed_at: new Date().toISOString() }
              : t
          )
        );
        if (detailTicket?.id === id) {
          setDetailTicket((prev) =>
            prev ? { ...prev, status_id: STATUS_RESOLVED, status_type: 'Resolved', closed_at: new Date().toISOString() } : null
          );
        }
      } else {
        setError(res.data.message || 'Failed to resolve ticket.');
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to resolve ticket.');
    } finally {
      setClosingId(null);
    }
  };

  const openDetail = 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 details.');
    } finally {
      setDetailLoading(false);
    }
  };

  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) === STATUS_OPEN;
  const isInProgress = (t) => Number(t.status_id) === STATUS_IN_PROGRESS;

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

  return (
    <div className="ticket-progress-page">
      <div className="ticket-progress-header">
        <h1>Ticket Progress</h1>
        <button type="button" className="btn-raise" onClick={() => navigate('/raise-ticket')}>
          Raise Ticket
        </button>
      </div>

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

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

      {error && <div className="ticket-progress-error">{error}</div>}

      <div className="ticket-progress-table-wrap">
        <table className="ticket-progress-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>Subject</th>
              <th>Type</th>
              <th>Raised by</th>
              <th>Status</th>
              <th>Created</th>
              <th>Resolved</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {filteredTickets.length === 0 ? (
              <tr>
                <td colSpan={8} className="tickets-empty">
                  <p style={{ margin: '0 0 0.5rem 0' }}>
                    {tickets.length === 0
                      ? 'No tickets yet.'
                      : 'No tickets with selected status.'}
                  </p>
                  <button type="button" className="link-btn" onClick={() => navigate('/raise-ticket')}>
                    Raise a ticket
                  </button>
                </td>
              </tr>
            ) : (
              filteredTickets.map((t) => (
                <tr key={t.id} className="ticket-progress-row">
                  <td className="col-id" data-label="ID">{t.id}</td>
                  <td className="col-subject" data-label="Subject" title={t.subject || ''}>
                    <span className="subject-text">{t.subject || '-'}</span>
                  </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="col-created" data-label="Created">{t.created_at ? new Date(t.created_at).toLocaleString() : '-'}</td>
                  <td className="col-resolved" data-label="Resolved">{t.closed_at ? new Date(t.closed_at).toLocaleString() : '-'}</td>
                  <td className="actions-cell" data-label="Actions">
                    <button
                      type="button"
                      className="btn-view"
                      onClick={() => openDetail(t.id)}
                      title="View details"
                    >
                      View
                    </button>
                    {isOpen(t) && (
                      <button
                        type="button"
                        className="btn-working-on"
                        onClick={() => handleSetInProgress(t.id)}
                        disabled={workingOnId === t.id}
                      >
                        {workingOnId === t.id ? 'Updating...' : 'Working on'}
                      </button>
                    )}
                    {(isOpen(t) || isInProgress(t)) && (
                      <button
                        type="button"
                        className="btn-close-ticket"
                        onClick={() => handleResolveTicket(t.id)}
                        disabled={closingId === t.id}
                      >
                        {closingId === t.id ? 'Resolving...' : 'Resolve'}
                      </button>
                    )}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {detailTicket && (
        <div className="ticket-detail-overlay" onClick={() => setDetailTicket(null)} role="presentation">
          <div
            className="ticket-detail-modal"
            onClick={(e) => e.stopPropagation()}
            role="dialog"
            aria-modal="true"
            aria-label="Ticket details"
          >
            <div className="ticket-detail-header">
              <h2>Ticket #{detailTicket.id}</h2>
              <button type="button" className="btn-close-modal" onClick={() => setDetailTicket(null)} aria-label="Close">
                ×
              </button>
            </div>
            {detailLoading ? (
              <div className="ticket-detail-loading">Loading...</div>
            ) : (
              <div className="ticket-detail-body">
                <div className="detail-row">
                  <span className="detail-label">Subject</span>
                  <span className="detail-value">{detailTicket.subject || '-'}</span>
                </div>
                <div className="detail-row">
                  <span className="detail-label">Type</span>
                  <span className="detail-value">{detailTicket.ticket_type_name || '-'}</span>
                </div>
                <div className="detail-row">
                  <span className="detail-label">Status</span>
                  <span className={statusBadgeClass(detailTicket.status_type)}>{detailTicket.status_type || '-'}</span>
                </div>
                <div className="detail-row">
                  <span className="detail-label">Raised by</span>
                  <span className="detail-value">
                    {detailTicket.user_name || '-'} {detailTicket.user_email ? `(${detailTicket.user_email})` : ''}
                  </span>
                </div>
                <div className="detail-row">
                  <span className="detail-label">Receiver</span>
                  <span className="detail-value">{detailTicket.recipient_email || '-'}</span>
                </div>
                <div className="detail-row">
                  <span className="detail-label">Created</span>
                  <span className="detail-value">
                    {detailTicket.created_at ? new Date(detailTicket.created_at).toLocaleString() : '-'}
                  </span>
                </div>
                <div className="detail-row">
                  <span className="detail-label">Resolved</span>
                  <span className="detail-value">
                    {detailTicket.closed_at ? new Date(detailTicket.closed_at).toLocaleString() : '-'}
                  </span>
                </div>
                <div className="detail-block">
                  <span className="detail-label">Description</span>
                  <p className="detail-description">{detailTicket.description || '-'}</p>
                </div>
                {detailTicket.logs && detailTicket.logs.length > 0 && (
                  <div className="detail-block detail-timeline">
                    <span className="detail-label">Progress / Activity</span>
                    <ul className="timeline-list">
                      {detailTicket.logs.map((log) => (
                        <li key={log.id} className="timeline-item">
                          <span className="timeline-date">
                            {log.created_at ? new Date(log.created_at).toLocaleString() : '-'}
                          </span>
                          <span className="timeline-desc">{log.description || '—'}</span>
                          {log.user_name && <span className="timeline-user">by {log.user_name}</span>}
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
                <div className="ticket-detail-actions">
                  {isOpen(detailTicket) && (
                    <button
                      type="button"
                      className="btn-working-on"
                      onClick={() => handleSetInProgress(detailTicket.id)}
                      disabled={workingOnId === detailTicket.id}
                    >
                      {workingOnId === detailTicket.id ? 'Updating...' : 'Working on'}
                    </button>
                  )}
                  {(isOpen(detailTicket) || isInProgress(detailTicket)) && (
                    <button
                      type="button"
                      className="btn-close-ticket"
                      onClick={() => handleResolveTicket(detailTicket.id)}
                      disabled={closingId === detailTicket.id}
                    >
                      {closingId === detailTicket.id ? 'Resolving...' : 'Resolve ticket'}
                    </button>
                  )}
                  <button type="button" className="btn-secondary" onClick={() => setDetailTicket(null)}>
                    Done
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default TicketProgress;
