import React, { useState } from 'react';
import { ChevronDown, FileText, Eye, Edit2, Trash2, Plus, AlertCircle } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { useToast } from '../contexts/ToastContext';
import DocumentDropZone from './DocumentDropZone';

const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';

function getSeverityClass(severity) {
  switch (severity?.toLowerCase()) {
    case 'critical': return 'critical';
    case 'high': return 'high';
    case 'medium': return 'medium';
    case 'low': return 'low';
    default: return 'medium';
  }
}

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';
}

// ⚠️ CONVENTION: Uses CSS classes (intel-card, vendor-card, severity-badge, glow-dot, jira-ticket-item, cve-header)
// that are not defined as inline styles or in App.css. Project convention is inline style objects or App.css classes.
// These classes must be added to App.css or converted back to inline style constants.

export default function CVECard({
  cveId,
  vendorEntries,
  jiraTickets,
  onEditCVE,
  onDeleteEntry,
  onDeleteAll,
  onEditTicket,
  onDeleteTicket,
  onAddTicket,
  onRequestConfirm,
}) {
  const { canWrite, canDelete, isAdmin } = useAuth();
  const toast = useToast();
  const [expanded, setExpanded] = useState(false);
  const [docExpanded, setDocExpanded] = useState(null);
  const [documents, setDocuments] = useState({});
  const [selectedDocuments, setSelectedDocuments] = useState([]);

  const severityOrder = { Critical: 0, High: 1, Medium: 2, Low: 3 };
  const highestSeverity = vendorEntries.reduce((highest, entry) => {
    const cur = severityOrder[entry.severity] ?? 4;
    const hi = severityOrder[highest] ?? 4;
    return cur < hi ? entry.severity : highest;
  }, vendorEntries[0].severity);
  const totalDocCount = vendorEntries.reduce((sum, e) => sum + (e.document_count || 0), 0);
  const overallStatuses = [...new Set(vendorEntries.map(e => e.status))];

  // ⚠️ CONVENTION: Missing loading state — no visual indicator while documents are being fetched.
  // Add a loading flag (e.g. loadingDocs state) and render a spinner/skeleton while the fetch is in flight.
  const fetchDocuments = async (cveId, vendor) => {
    const key = `${cveId}-${vendor}`;
    if (documents[key]) return;
    try {
      const response = await fetch(`${API_BASE}/cves/${cveId}/documents?vendor=${vendor}`, { credentials: 'include' });
      if (!response.ok) throw new Error('Failed to fetch documents');
      const data = await response.json();
      setDocuments(prev => ({ ...prev, [key]: data }));
    } catch (err) {
      toast.error(err.message);
    }
  };

  const handleViewDocuments = async (cveId, vendor) => {
    const key = `${cveId}-${vendor}`;
    if (docExpanded === key) {
      setDocExpanded(null);
    } else {
      setDocExpanded(key);
      await fetchDocuments(cveId, vendor);
    }
  };

  const handleDeleteDocument = (docId, cveId, vendor) => {
    onRequestConfirm({
      title: 'Delete Document',
      message: 'Are you sure you want to delete this document?',
      confirmText: 'Delete',
      onConfirm: async () => {
        try {
          const response = await fetch(`${API_BASE}/documents/${docId}`, { method: 'DELETE', credentials: 'include' });
          if (!response.ok) throw new Error('Failed to delete document');
          toast.success('Document deleted');
          const key = `${cveId}-${vendor}`;
          setDocuments(prev => { const next = { ...prev }; delete next[key]; return next; });
          await fetchDocuments(cveId, vendor);
        } catch (err) {
          toast.error(err.message);
        }
      },
    });
  };

  const toggleDocSelection = (docId) => {
    setSelectedDocuments(prev => prev.includes(docId) ? prev.filter(id => id !== docId) : [...prev, docId]);
  };

  const highSevClass = getSeverityClass(highestSeverity);

  return (
    <div className="intel-card rounded-lg">
      {/* Clickable CVE Header */}
      <div
        className="cve-header"
        style={{ padding: '1.5rem', cursor: 'pointer', userSelect: 'none' }}
        onClick={() => setExpanded(prev => !prev)}
        role="button"
        aria-expanded={expanded}
        aria-label={`${cveId} - ${highestSeverity} severity, ${vendorEntries.length} vendors`}
      >
        <div className="flex items-start justify-between">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-3 mb-1">
              <ChevronDown className={`w-5 h-5 text-intel-accent transition-transform duration-200 flex-shrink-0 ${expanded ? 'rotate-0' : '-rotate-90'}`} />
              <h3 className="text-2xl font-bold text-intel-accent font-mono tracking-tight">{cveId}</h3>
            </div>

            {!expanded && (
              <div className="ml-8">
                <p className="text-sm text-gray-200 truncate mb-2">{vendorEntries[0].description}</p>
                <div className="flex items-center gap-3 flex-wrap">
                  <span className={`severity-badge severity-badge--${highSevClass}`}>
                    <span className={`glow-dot glow-dot--${highSevClass}`}></span>
                    {highestSeverity}
                  </span>
                  <span className="text-xs text-gray-200 font-mono">
                    {vendorEntries.length} vendor{vendorEntries.length > 1 ? 's' : ''}
                  </span>
                  <span className="text-xs text-gray-200 font-mono flex items-center gap-1">
                    <FileText className="w-3 h-3" />
                    {totalDocCount} doc{totalDocCount !== 1 ? 's' : ''}
                  </span>
                  <span className="text-xs text-gray-200 font-mono">
                    {overallStatuses.join(', ')}
                  </span>
                </div>
              </div>
            )}

            {expanded && (
              <div className="ml-8">
                <p className="text-white mb-3">{vendorEntries[0].description}</p>
                <div className="flex items-center gap-2 text-sm text-gray-300 font-mono">
                  <span>Published: {vendorEntries[0].published_date}</span>
                  <span className="text-intel-accent">•</span>
                  <span>{vendorEntries.length} affected vendor{vendorEntries.length > 1 ? 's' : ''}</span>
                  {isAdmin() && vendorEntries.length >= 2 && (
                    <button
                      onClick={(e) => { e.stopPropagation(); onDeleteAll(cveId, vendorEntries.length); }}
                      className="ml-2 px-3 py-1 text-xs intel-button intel-button-danger flex items-center gap-1"
                    >
                      <Trash2 className="w-3 h-3" />
                      Delete All
                    </button>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Expanded vendor entries */}
      {expanded && (
        <div className="px-6 pb-6">
          <div className="space-y-3">
            {vendorEntries.map((cve) => {
              const key = `${cve.cve_id}-${cve.vendor}`;
              const docs = documents[key] || [];
              const isDocOpen = docExpanded === key;
              const vendorTickets = jiraTickets.filter(t => t.cve_id === cve.cve_id && t.vendor === cve.vendor);
              const sevClass = getSeverityClass(cve.severity);

              return (
                <div key={cve.id} className="vendor-card">
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <h4 className="text-lg font-semibold text-white">{cve.vendor}</h4>
                        <span className={`severity-badge severity-badge--${sevClass}`}>
                          <span className={`glow-dot glow-dot--${sevClass}`}></span>
                          {cve.severity}
                        </span>
                      </div>
                      <div className="flex items-center gap-4 text-sm text-gray-200 font-mono">
                        <span>Status: <span className="font-medium text-white">{cve.status}</span></span>
                        <span className="flex items-center gap-1">
                          <FileText className="w-4 h-4" />
                          {cve.document_count} doc{cve.document_count !== 1 ? 's' : ''}
                        </span>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <button
                        onClick={() => handleViewDocuments(cve.cve_id, cve.vendor)}
                        className="px-4 py-2 text-intel-accent hover:bg-intel-medium rounded border border-intel-accent/50 transition-all flex items-center gap-2 font-mono text-xs uppercase tracking-wider"
                      >
                        <Eye className="w-4 h-4" />
                        {isDocOpen ? 'Hide' : 'View'}
                      </button>
                      {canWrite() && (
                        <button
                          onClick={() => onEditCVE(cve)}
                          className="px-3 py-2 text-intel-warning hover:bg-intel-medium rounded border border-intel-warning/50 transition-all flex items-center gap-1"
                          title="Edit CVE entry"
                        >
                          <Edit2 className="w-4 h-4" />
                        </button>
                      )}
                      {canDelete(cve) && (
                        <button
                          onClick={() => onDeleteEntry(cve)}
                          className="px-3 py-2 text-intel-danger hover:bg-intel-medium rounded border border-intel-danger/50 transition-all flex items-center gap-1"
                          title="Delete this vendor entry"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      )}
                    </div>
                  </div>

                  {/* Documents */}
                  {isDocOpen && (
                    <div className="mt-4 pt-4 border-t border-intel-accent/30">
                      <h5 className="text-sm font-semibold text-white mb-3 flex items-center gap-2 font-mono uppercase tracking-wider">
                        <FileText className="w-4 h-4 text-intel-accent" />
                        Documents ({docs.length})
                      </h5>
                      {docs.length > 0 ? (
                        <div className="space-y-2">
                          {docs.map(doc => (
                            <div key={doc.id} className="document-item flex items-center justify-between">
                              <div className="flex items-center gap-3 flex-1">
                                <input
                                  type="checkbox"
                                  checked={selectedDocuments.includes(doc.id)}
                                  onChange={() => toggleDocSelection(doc.id)}
                                  className="w-4 h-4 text-intel-accent rounded focus:ring-2 focus:ring-intel-accent bg-intel-dark border-intel-accent/50"
                                  aria-label={`Select document ${doc.name}`}
                                />
                                <FileText className="w-5 h-5 text-intel-accent" />
                                <div className="flex-1">
                                  <p className="text-sm font-medium text-white font-mono">{doc.name}</p>
                                  <p className="text-xs text-gray-300 capitalize font-mono">
                                    {doc.type} <span className="text-intel-accent">•</span> {doc.file_size}
                                    {doc.notes && <span> <span className="text-intel-accent">•</span> {doc.notes}</span>}
                                  </p>
                                </div>
                              </div>
                              <div className="flex gap-2">
                                <a
                                  href={`/${doc.file_path}`}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="px-3 py-1 text-sm text-intel-accent hover:bg-intel-medium rounded transition-all border border-intel-accent/50 font-mono uppercase tracking-wider"
                                >
                                  View
                                </a>
                                {isAdmin() && (
                                  <button
                                    onClick={() => handleDeleteDocument(doc.id, cve.cve_id, cve.vendor)}
                                    className="px-3 py-1 text-sm text-intel-danger hover:bg-intel-medium rounded transition-all border border-intel-danger/50 flex items-center gap-1 font-mono uppercase tracking-wider"
                                  >
                                    <Trash2 className="w-3 h-3" />
                                    Del
                                  </button>
                                )}
                              </div>
                            </div>
                          ))}
                        </div>
                      ) : (
                        <p className="text-sm text-gray-400 italic font-mono">No documents attached</p>
                      )}
                      {canWrite() && (
                        <DocumentDropZone
                          cveId={cve.cve_id}
                          vendor={cve.vendor}
                          onUploadComplete={async () => {
                            const key = `${cve.cve_id}-${cve.vendor}`;
                            setDocuments(prev => { const next = { ...prev }; delete next[key]; return next; });
                            await fetchDocuments(cve.cve_id, cve.vendor);
                          }}
                        />
                      )}
                    </div>
                  )}

                  {/* JIRA Tickets */}
                  {(vendorTickets.length > 0 || canWrite()) && (
                    <div className="mt-4 pt-4 border-t border-intel-warning/30">
                      <div className="flex justify-between items-center mb-3">
                        <h5 className="text-sm font-semibold text-white flex items-center gap-2 font-mono uppercase tracking-wider">
                          <AlertCircle className="w-4 h-4 text-intel-warning" />
                          JIRA Tickets ({vendorTickets.length})
                        </h5>
                        {canWrite() && (
                          <button
                            onClick={() => onAddTicket(cve.cve_id, cve.vendor)}
                            className="text-xs px-3 py-1 intel-button intel-button-primary flex items-center gap-1"
                          >
                            <Plus className="w-3 h-3" />
                            Add Ticket
                          </button>
                        )}
                      </div>
                      {vendorTickets.length > 0 ? (
                        <div className="space-y-2">
                          {vendorTickets.map(ticket => (
                            <div key={ticket.id} className="jira-ticket-item flex items-center justify-between">
                              <div className="flex items-center gap-3 flex-1">
                                <a
                                  href={ticket.url || '#'}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="font-mono text-sm font-semibold text-intel-accent hover:text-intel-warning transition-colors"
                                >
                                  {ticket.ticket_key}
                                </a>
                                {ticket.summary && (
                                  <span className="text-sm text-gray-200 truncate max-w-xs">
                                    {ticket.summary}
                                  </span>
                                )}
                                <span className={`severity-badge severity-badge--${isClosedStatus(ticket.status) ? 'low' : 'high'}`}>
                                  <span className={`glow-dot ${getTicketStatusDotClass(ticket.status)}`}></span>
                                  {ticket.status}
                                </span>
                              </div>
                              {canWrite() && (
                                <div className="flex gap-2">
                                  <button onClick={() => onEditTicket(ticket)} className="p-1 text-gray-400 hover:text-intel-warning transition-colors">
                                    <Edit2 className="w-4 h-4" />
                                  </button>
                                  {canDelete(ticket) && (
                                    <button onClick={() => onDeleteTicket(ticket)} className="p-1 text-gray-400 hover:text-intel-danger transition-colors">
                                      <Trash2 className="w-4 h-4" />
                                    </button>
                                  )}
                                </div>
                              )}
                            </div>
                          ))}
                        </div>
                      ) : (
                        <p className="text-sm text-gray-400 italic font-mono">No JIRA tickets linked</p>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}
