import React from 'react';
import { AlertCircle, Plus, Edit2, Trash2, CheckCircle } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';

function isClosedStatus(status) {
  if (!status) return false;
  const lower = status.toLowerCase();
  return ['closed', 'done', 'resolved', 'complete', 'completed', 'cancelled', 'canceled', "won't do", 'declined'].some(s => lower.includes(s));
}

function getTicketStatusDotClass(status) {
  if (!status) return 'glow-dot--high';
  if (isClosedStatus(status)) return 'glow-dot--low';
  const lower = status.toLowerCase();
  if (['open', 'to do', 'backlog', 'new'].some(s => lower === s)) return 'glow-dot--high';
  return 'glow-dot--medium';
}

export default function OpenTicketsPanel({ tickets, onAdd, onEdit, onDelete, embedded = false }) {
  const { canWrite, canDelete } = useAuth();
  const openTickets = tickets.filter(t => !isClosedStatus(t.status));

  const content = (
    <>
      <div className="flex justify-between items-center mb-4">
        <h2 className="section-heading section-heading--warning">
          <AlertCircle className="w-5 h-5" />
          Open Tickets
        </h2>
        {canWrite() && (
          <button
            onClick={onAdd}
            className="intel-button intel-button-primary flex items-center gap-1 text-xs px-2 py-1"
            aria-label="Add ticket"
          >
            <Plus className="w-3 h-3" />
          </button>
        )}
      </div>

      <div className="text-center mb-3">
        <div className="big-counter big-counter--warning">{openTickets.length}</div>
        <div className="text-xs text-gray-400 uppercase tracking-wider">Active</div>
      </div>

      <div className="space-y-2 max-h-96 overflow-y-auto">
        {openTickets.slice(0, 10).map(ticket => (
          <div key={ticket.id} className="sidebar-ticket">
            <div className="flex items-start justify-between gap-2 mb-1">
              <a
                href={ticket.url || '#'}
                target="_blank"
                rel="noopener noreferrer"
                className="font-mono text-xs font-semibold text-intel-accent hover:text-intel-warning transition-colors"
              >
                {ticket.ticket_key}
              </a>
              {canWrite() && (
                <div className="flex gap-1">
                  <button onClick={() => onEdit(ticket)} className="text-gray-400 hover:text-intel-warning transition-colors" aria-label={`Edit ${ticket.ticket_key}`}>
                    <Edit2 className="w-3 h-3" />
                  </button>
                  {canDelete(ticket) && (
                    <button onClick={() => onDelete(ticket)} className="text-gray-400 hover:text-intel-danger transition-colors" aria-label={`Delete ${ticket.ticket_key}`}>
                      <Trash2 className="w-3 h-3" />
                    </button>
                  )}
                </div>
              )}
            </div>
            <div className="text-xs text-white font-mono mb-1">{ticket.cve_id}</div>
            <div className="text-xs text-gray-400">{ticket.vendor}</div>
            {ticket.summary && <div className="text-xs text-gray-300 mt-1 truncate">{ticket.summary}</div>}
            <div className="mt-2">
              <span className="ticket-status-badge severity-badge--high">
                <span className={`glow-dot ${getTicketStatusDotClass(ticket.status)}`} style={{ width: '6px', height: '6px' }}></span>
                {ticket.status}
              </span>
            </div>
          </div>
        ))}
        {openTickets.length === 0 && (
          <div className="text-center py-8">
            <CheckCircle className="w-8 h-8 text-intel-success mx-auto mb-2" />
            <p className="text-sm text-gray-400 italic font-mono">No open tickets</p>
          </div>
        )}
      </div>
    </>
  );

  if (embedded) return content;
  return <div className="panel-card panel-card--warning">{content}</div>;
}
