import React, { useState, useEffect, useCallback } from 'react';
import { Activity, RefreshCw, Loader, AlertCircle, CheckCircle, AlertTriangle } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import ArchiveSummaryBar from './pages/ArchiveSummaryBar';

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

export default function IvantiWorkflowPanel({ embedded = false }) {
  const { canWrite, getActiveTeamsParam } = useAuth();
  const [total, setTotal] = useState(null);
  const [workflows, setWorkflows] = useState([]);
  const [syncedAt, setSyncedAt] = useState(null);
  const [syncStatus, setSyncStatus] = useState(null);
  const [syncError, setSyncError] = useState(null);
  const [loading, setLoading] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [archiveFilter, setArchiveFilter] = useState(null);
  const [archiveRefreshKey, setArchiveRefreshKey] = useState(0);
  const [archiveList, setArchiveList] = useState([]);
  const [archiveListLoading, setArchiveListLoading] = useState(false);

  const applyState = (data) => {
    setTotal(data.total ?? 0);
    setWorkflows(data.workflows || []);
    setSyncedAt(data.synced_at || null);
    setSyncStatus(data.sync_status || null);
    setSyncError(data.error_message || null);
  };

  const fetchWorkflows = useCallback(async () => {
    setLoading(true);
    try {
      const response = await fetch(`${API_BASE}/ivanti/workflows`, { credentials: 'include' });
      const data = await response.json();
      if (response.ok) applyState(data);
    } catch (err) {
      console.error('Error loading Ivanti workflows:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  const syncWorkflows = async () => {
    setSyncing(true);
    try {
      const response = await fetch(`${API_BASE}/ivanti/workflows/sync`, { method: 'POST', credentials: 'include' });
      const data = await response.json();
      if (response.ok) applyState(data);
    } catch (err) {
      console.error('Error syncing Ivanti workflows:', err);
    } finally {
      setSyncing(false);
      setArchiveRefreshKey(k => k + 1);
    }
  };

  const handleArchiveStateClick = (state) => {
    const newFilter = archiveFilter === state ? null : state;
    setArchiveFilter(newFilter);
    if (newFilter) {
      setArchiveListLoading(true);
      const teamsParam = getActiveTeamsParam();
      const url = teamsParam
        ? `${API_BASE}/ivanti/archive?state=${newFilter}&teams=${encodeURIComponent(teamsParam)}`
        : `${API_BASE}/ivanti/archive?state=${newFilter}`;
      fetch(url, { credentials: 'include' })
        .then(res => res.ok ? res.json() : Promise.reject())
        .then(data => setArchiveList(data.archives || []))
        .catch(() => setArchiveList([]))
        .finally(() => setArchiveListLoading(false));
    } else {
      setArchiveList([]);
    }
  };

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

  const content = (
    <>
      <div className="flex justify-between items-center mb-1">
        <h2 className="section-heading section-heading--teal">
          <Activity className="w-5 h-5" />
          Ivanti Workflows
        </h2>
        {canWrite() && (
          <button
            onClick={syncWorkflows}
            disabled={syncing || loading}
            className="intel-button intel-button-primary flex items-center gap-1 text-xs px-2 py-1"
            title="Sync now"
          >
            <RefreshCw className={`w-3 h-3 ${syncing ? 'animate-spin' : ''}`} />
            {syncing ? 'Syncing…' : 'Sync'}
          </button>
        )}
      </div>

      <div className="text-xs text-gray-500 font-mono mb-4">
        {syncedAt ? `Synced ${new Date(syncedAt).toLocaleString()}` : 'Never synced'}
      </div>

      {/* Archive Summary */}
      <ArchiveSummaryBar onStateClick={handleArchiveStateClick} activeFilter={archiveFilter} refreshKey={archiveRefreshKey} teamsParam={getActiveTeamsParam()} />

      {/* Archive list */}
      {archiveFilter && (
        <div style={{ marginBottom: '1rem' }}>
          <div className="flex justify-between items-center mb-2">
            <span className="font-mono text-xs text-gray-400 uppercase tracking-wider">
              {archiveFilter} findings
            </span>
            <button
              onClick={() => { setArchiveFilter(null); setArchiveList([]); }}
              className="font-mono text-xs text-gray-400 hover:text-white"
              style={{ background: 'none', border: 'none', cursor: 'pointer' }}
            >
              ✕ Clear
            </button>
          </div>
          {archiveListLoading ? (
            <div className="text-center p-4 text-gray-400 font-mono text-xs">Loading…</div>
          ) : archiveList.length === 0 ? (
            <div className="text-center p-4 text-gray-500 font-mono text-xs" style={{ border: '1px dashed rgba(100, 116, 139, 0.3)', borderRadius: '0.375rem' }}>
              No {archiveFilter.toLowerCase()} findings
            </div>
          ) : (
            <div style={{ maxHeight: '240px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '0.375rem' }}>
              {archiveList.map((a) => (
                <div key={a.id} className={`archive-item ${a.related_active ? 'archive-item--active' : 'archive-item--resolved'}`}>
                  <div className="flex justify-between items-start gap-2 mb-1">
                    <div className="flex items-start gap-1.5 flex-1 min-w-0">
                      {a.related_active ? (
                        <AlertTriangle className="w-3 h-3 text-intel-warning flex-shrink-0 mt-0.5" />
                      ) : (
                        <CheckCircle className="w-3 h-3 text-intel-success flex-shrink-0 mt-0.5" />
                      )}
                      <div className="min-w-0">
                        <span className="font-mono text-xs font-semibold text-gray-200 block">{a.finding_title || a.finding_id}</span>
                        {a.finding_id && (
                          <span title={a.finding_id} className="font-mono text-xs text-gray-500 block mt-0.5" style={{ fontSize: '0.6rem' }}>
                            {a.finding_id.length > 20 ? a.finding_id.slice(0, 20) + '…' : a.finding_id}
                          </span>
                        )}
                      </div>
                    </div>
                    <span className="font-mono text-gray-400 whitespace-nowrap" style={{ fontSize: '0.55rem', padding: '0.15rem 0.35rem', borderRadius: '0.25rem', background: 'rgba(100, 116, 139, 0.2)', border: '1px solid rgba(100, 116, 139, 0.4)' }}>
                      Last seen: {(a.last_severity && Number(a.last_severity) !== 0) ? Number(a.last_severity).toFixed(1) : '—'}
                    </span>
                  </div>
                  <div className="font-mono text-gray-500 ml-5" style={{ fontSize: '0.65rem' }}>
                    {a.host_name}{a.ip_address ? ` (${a.ip_address})` : ''}
                  </div>
                  {a.related_active && (
                    <div className="font-mono text-intel-accent mt-1 ml-5 inline-block" style={{ fontSize: '0.6rem', padding: '0.2rem 0.4rem', background: 'rgba(14, 165, 233, 0.1)', border: '1px solid rgba(14, 165, 233, 0.25)', borderRadius: '0.25rem' }}>
                      Similar finding active — ID: {a.related_active.id} ({a.related_active.severity ? Number(a.related_active.severity).toFixed(1) : '—'})
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Main content */}
      {loading ? (
        <div className="text-center py-8">
          <Loader className="w-6 h-6 text-teal-400 animate-spin mx-auto mb-2" />
          <p className="text-xs text-gray-400 font-mono">Loading...</p>
        </div>
      ) : syncStatus === 'error' ? (
        <>
          <div className="text-center mb-3">
            <div className="big-counter big-counter--teal">{total ?? '—'}</div>
            <div className="text-xs text-gray-400 uppercase tracking-wider">Total Workflows</div>
          </div>
          <div className="flex items-start gap-2 p-2 rounded" style={{ background: 'rgba(239, 68, 68, 0.1)', border: '1px solid rgba(239, 68, 68, 0.3)' }}>
            <AlertCircle className="w-4 h-4 text-intel-danger mt-0.5 shrink-0" />
            <p className="text-xs text-red-400 font-mono">{syncError}</p>
          </div>
        </>
      ) : (
        <>
          <div className="text-center mb-3">
            <div className="big-counter big-counter--teal">
              {syncStatus === 'never' ? '—' : (total ?? '—')}
            </div>
            <div className="text-xs text-gray-400 uppercase tracking-wider">Total Workflows</div>
          </div>
          <div className="space-y-2 max-h-64 overflow-y-auto">
            {workflows.slice(0, 10).map((wf, idx) => (
              <div key={wf.uuid ?? idx} className="workflow-item">
                <div className="flex items-start justify-between gap-2 mb-1">
                  <span className="font-mono text-xs font-semibold text-teal-300">
                    {wf.id?.value || wf.uuid?.slice(0, 8)}
                  </span>
                  {wf.currentState && (
                    <span className="workflow-state-badge">{wf.currentState}</span>
                  )}
                </div>
                <div className="text-xs text-white truncate mb-1">{wf.name}</div>
                <div className="flex items-center justify-between gap-2">
                  {wf.type && <span className="text-xs text-gray-400 font-mono">{wf.type.replace(/_/g, ' ')}</span>}
                  {wf.createdOn && <span className="text-xs text-gray-500">{wf.createdOn}</span>}
                </div>
              </div>
            ))}
            {syncStatus !== 'never' && total === 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 workflows found</p>
              </div>
            )}
            {syncStatus === 'never' && (
              <div className="text-center py-6">
                <p className="text-xs text-gray-500 font-mono">Click Sync to load workflow data</p>
              </div>
            )}
          </div>
        </>
      )}
    </>
  );

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