import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { XCircle, AlertCircle } from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import { useToast } from '../../contexts/ToastContext';
import { useDebounce } from '../../hooks/useDebounce';
import StatsBar from '../StatsBar';
import QuickCVELookup from '../QuickCVELookup';
import CVEFilters from '../CVEFilters';
import CVECard from '../CVECard';
import OpenTicketsPanel from '../OpenTicketsPanel';
import IvantiWorkflowPanel from '../IvantiWorkflowPanel';
import CalendarWidget from '../CalendarWidget';
import RecentActivityFeed from '../RecentActivityFeed';
import SidebarTabs from '../SidebarTabs';
import ArcherPage from './ArcherPage';
import ConfirmModal from '../ConfirmModal';
import AddCVEModal from '../modals/AddCVEModal';
import EditCVEModal from '../modals/EditCVEModal';
import JiraTicketModal from '../modals/JiraTicketModal';
import ArcherTicketModal from '../modals/ArcherTicketModal';

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

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

export default function HomePage({ onNavigate, showAddCVE, setShowAddCVE }) {
  const { isAuthenticated, canDelete } = useAuth();
  const toast = useToast();

  // --- CVE data state ---
  const [cves, setCves] = useState([]);
  const [vendors, setVendors] = useState(['All Vendors']);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // --- Filter state ---
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedVendor, setSelectedVendor] = useState('All Vendors');
  const [selectedSeverity, setSelectedSeverity] = useState('All Severities');
  const debouncedSearch = useDebounce(searchQuery, 300);

  // --- Pagination ---
  const [visibleCount, setVisibleCount] = useState(5);

  // --- Tickets ---
  const [jiraTickets, setJiraTickets] = useState([]);
  const [archerTickets, setArcherTickets] = useState([]);

  // --- Modal state ---
  const [editingCVE, setEditingCVE] = useState(null);
  const [jiraModal, setJiraModal] = useState(null); // { ticket?, context? }
  const [archerModal, setArcherModal] = useState(null); // { ticket?, context? }
  const [pendingConfirm, setPendingConfirm] = useState(null);

  // --- Fetchers ---
  const fetchCVEs = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams();
      if (debouncedSearch) params.append('search', debouncedSearch);
      if (selectedVendor !== 'All Vendors') params.append('vendor', selectedVendor);
      if (selectedSeverity !== 'All Severities') params.append('severity', selectedSeverity);

      const response = await fetch(`${API_BASE}/cves?${params}`, { credentials: 'include' });
      if (!response.ok) throw new Error('Failed to fetch CVEs');
      const data = await response.json();
      setCves(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [debouncedSearch, selectedVendor, selectedSeverity]);

  const fetchVendors = useCallback(async () => {
    try {
      const response = await fetch(`${API_BASE}/vendors`, { credentials: 'include' });
      if (!response.ok) throw new Error('Failed to fetch vendors');
      const data = await response.json();
      setVendors(['All Vendors', ...data]);
    } catch (err) {
      console.error('Error fetching vendors:', err);
    }
  }, []);

  const fetchJiraTickets = useCallback(async () => {
    try {
      const response = await fetch(`${API_BASE}/jira-tickets`, { credentials: 'include' });
      if (!response.ok) throw new Error('Failed to fetch JIRA tickets');
      const data = await response.json();
      setJiraTickets(data);
    } catch (err) {
      console.error('Error fetching JIRA tickets:', err);
    }
  }, []);

  const fetchArcherTickets = useCallback(async () => {
    try {
      const response = await fetch(`${API_BASE}/archer-tickets`, { credentials: 'include' });
      if (!response.ok) throw new Error('Failed to fetch Archer tickets');
      const data = await response.json();
      setArcherTickets(data);
    } catch (err) {
      console.error('Error fetching Archer tickets:', err);
    }
  }, []);

  // --- Effects ---
  useEffect(() => {
    if (isAuthenticated) {
      fetchCVEs();
      fetchVendors();
      fetchJiraTickets();
      fetchArcherTickets();
    }
  }, [isAuthenticated, fetchCVEs, fetchVendors, fetchJiraTickets, fetchArcherTickets]);

  // Reset visible count when filters change
  useEffect(() => { setVisibleCount(5); }, [debouncedSearch, selectedVendor, selectedSeverity]);

  // --- Memoized data ---
  const groupedCVEs = useMemo(() =>
    cves.reduce((acc, cve) => {
      if (!acc[cve.cve_id]) acc[cve.cve_id] = [];
      acc[cve.cve_id].push(cve);
      return acc;
    }, {}),
    [cves]
  );

  const openTicketCount = useMemo(
    () => jiraTickets.filter(t => !isClosedStatus(t.status)).length,
    [jiraTickets]
  );

  const criticalCount = useMemo(
    () => cves.filter(c => c.severity === 'Critical').length,
    [cves]
  );

  // --- Handlers ---
  const handleDeleteEntry = (cve) => {
    setPendingConfirm({
      title: 'Delete Vendor Entry',
      message: `Are you sure you want to delete the "${cve.vendor}" entry for ${cve.cve_id}? This will also delete all associated documents.`,
      confirmText: 'Delete',
      onConfirm: async () => {
        setPendingConfirm(null);
        try {
          const response = await fetch(`${API_BASE}/cves/${cve.id}`, { method: 'DELETE', credentials: 'include' });
          if (!response.ok) {
            const ct = response.headers.get('content-type');
            if (ct && ct.includes('application/json')) {
              const data = await response.json();
              throw new Error(data.error || 'Failed to delete CVE entry');
            } else {
              throw new Error(`Server returned ${response.status} ${response.statusText}`);
            }
          }
          toast.success(`Deleted ${cve.vendor} entry for ${cve.cve_id}`);
          fetchCVEs();
          fetchVendors();
        } catch (err) {
          toast.error(err.message);
        }
      },
    });
  };

  const handleDeleteAll = (cveId, vendorCount) => {
    setPendingConfirm({
      title: 'Delete Entire CVE',
      message: `Are you sure you want to delete ALL ${vendorCount} vendor entries for ${cveId}? This will permanently remove all associated documents and files.`,
      confirmText: 'Delete All',
      onConfirm: async () => {
        setPendingConfirm(null);
        try {
          const response = await fetch(`${API_BASE}/cves/by-cve-id/${encodeURIComponent(cveId)}`, { method: 'DELETE', credentials: 'include' });
          if (!response.ok) {
            const ct = response.headers.get('content-type');
            if (ct && ct.includes('application/json')) {
              const data = await response.json();
              throw new Error(data.error || 'Failed to delete CVE');
            } else {
              throw new Error(`Server returned ${response.status} ${response.statusText}`);
            }
          }
          toast.success(`Deleted all entries for ${cveId}`);
          fetchCVEs();
          fetchVendors();
        } catch (err) {
          toast.error(err.message);
        }
      },
    });
  };

  const handleDeleteTicket = (ticket) => {
    setPendingConfirm({
      title: 'Delete Ticket',
      message: `Delete ticket ${ticket.ticket_key}?`,
      confirmText: 'Delete',
      onConfirm: async () => {
        setPendingConfirm(null);
        try {
          const response = await fetch(`${API_BASE}/jira-tickets/${ticket.id}`, { method: 'DELETE', credentials: 'include' });
          if (!response.ok) throw new Error('Failed to delete ticket');
          toast.success('Ticket deleted');
          fetchJiraTickets();
        } catch (err) {
          toast.error(err.message);
        }
      },
    });
  };

  const handleDeleteArcherTicket = (ticket) => {
    setPendingConfirm({
      title: 'Delete Archer Ticket',
      message: `Delete Archer ticket ${ticket.exc_number}?`,
      confirmText: 'Delete',
      onConfirm: async () => {
        setPendingConfirm(null);
        try {
          const response = await fetch(`${API_BASE}/archer-tickets/${ticket.id}`, { method: 'DELETE', credentials: 'include' });
          if (!response.ok) throw new Error('Failed to delete Archer ticket');
          toast.success('Archer ticket deleted');
          fetchArcherTickets();
        } catch (err) {
          toast.error(err.message);
        }
      },
    });
  };

  const handleFilterSeverity = (severity) => {
    setSelectedSeverity(severity);
  };

  const totalCVEs = Object.keys(groupedCVEs).length;

  return (
    <>
      {/* Stats Bar */}
      <StatsBar
        totalCVEs={totalCVEs}
        vendorEntries={cves.length}
        openTickets={openTicketCount}
        criticalCount={criticalCount}
        onFilterSeverity={handleFilterSeverity}
        activeSeverity={selectedSeverity}
      />

      {/* Two Column Layout */}
      <div className="grid grid-cols-12 gap-6 mt-6">
        {/* CENTER PANEL */}
        <div className="col-span-12 lg:col-span-9 space-y-4">
          <QuickCVELookup />

          <CVEFilters
            searchQuery={searchQuery}
            onSearchChange={setSearchQuery}
            selectedVendor={selectedVendor}
            onVendorChange={setSelectedVendor}
            vendors={vendors}
            selectedSeverity={selectedSeverity}
            onSeverityChange={setSelectedSeverity}
          />

          {/* Results Summary */}
          <div className="flex justify-between items-center">
            <p className="text-gray-400 font-mono text-sm">
              <span className="text-intel-accent font-bold">{totalCVEs}</span> CVE{totalCVEs !== 1 ? 's' : ''}
              <span className="text-gray-500 mx-2">•</span>
              <span className="text-gray-300">{cves.length}</span> vendor entr{cves.length !== 1 ? 'ies' : 'y'}
            </p>
          </div>

          {/* CVE List */}
          {loading ? (
            <div className="intel-card rounded-lg p-12 text-center">
              <div className="loading-spinner w-12 h-12 mx-auto mb-4"></div>
              <p className="text-gray-400 font-mono text-sm uppercase tracking-wider">Scanning Vulnerabilities...</p>
            </div>
          ) : error ? (
            <div className="intel-card rounded-lg p-12 text-center border-intel-danger">
              <XCircle className="w-12 h-12 text-intel-danger mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-200 mb-2 font-mono">Error Loading CVEs</h3>
              <p className="text-gray-400 mb-4">{error}</p>
              <button onClick={fetchCVEs} className="intel-button intel-button-primary">Retry</button>
            </div>
          ) : (
            <div className="space-y-4">
              {Object.entries(groupedCVEs).slice(0, visibleCount).map(([cveId, vendorEntries]) => (
                <CVECard
                  key={cveId}
                  cveId={cveId}
                  vendorEntries={vendorEntries}
                  jiraTickets={jiraTickets}
                  onEditCVE={(cve) => setEditingCVE(cve)}
                  onDeleteEntry={handleDeleteEntry}
                  onDeleteAll={handleDeleteAll}
                  onEditTicket={(ticket) => setJiraModal({ ticket })}
                  onDeleteTicket={handleDeleteTicket}
                  onAddTicket={(cve_id, vendor) => setJiraModal({ context: { cve_id, vendor } })}
                  onRequestConfirm={setPendingConfirm}
                />
              ))}

              {/* Pagination */}
              {totalCVEs > visibleCount && (
                <div className="flex items-center justify-between pt-2">
                  <span className="text-gray-500 font-mono text-xs">
                    Showing {visibleCount} of {totalCVEs} CVEs
                  </span>
                  <div className="flex gap-2">
                    <button
                      onClick={() => setVisibleCount(v => v + 5)}
                      className="intel-button intel-button-primary text-xs px-3 py-1"
                    >
                      Show 5 more
                    </button>
                    <button
                      onClick={() => setVisibleCount(totalCVEs)}
                      className="intel-button text-xs px-3 py-1"
                      style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', color: '#94A3B8' }}
                    >
                      Show all
                    </button>
                  </div>
                </div>
              )}
              {visibleCount > 5 && totalCVEs <= visibleCount && totalCVEs > 5 && (
                <div className="flex justify-end pt-2">
                  <button
                    onClick={() => setVisibleCount(5)}
                    className="intel-button text-xs px-3 py-1"
                    style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', color: '#94A3B8' }}
                  >
                    Collapse
                  </button>
                </div>
              )}
            </div>
          )}

          {totalCVEs === 0 && !loading && (
            <div className="intel-card rounded-lg p-12 text-center">
              <AlertCircle className="w-12 h-12 text-gray-400 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-white mb-2 font-mono">No CVEs Found</h3>
              <p className="text-gray-300">Try adjusting your search criteria or filters</p>
            </div>
          )}
        </div>

        {/* RIGHT PANEL */}
        <div className="col-span-12 lg:col-span-3 space-y-4">
          {/* Calendar */}
          <div className="panel-card panel-card--accent">
            <h2 className="section-heading section-heading--accent" style={{ marginBottom: '1rem' }}>
              Calendar
            </h2>
            <CalendarWidget
              onDateClick={(dateStr) => {
                onNavigate('triage', { calendarFilter: dateStr });
              }}
            />
          </div>

          {/* Recent Activity */}
          <RecentActivityFeed />

          {/* Tabbed panels: Tickets / Archer / Ivanti */}
          <SidebarTabs>
            {{
              tickets: (
                <OpenTicketsPanel
                  tickets={jiraTickets}
                  onAdd={() => setJiraModal({ context: null })}
                  onEdit={(ticket) => setJiraModal({ ticket })}
                  onDelete={handleDeleteTicket}
                  embedded
                />
              ),
              archer: (
                <ArcherPage
                  archerTickets={archerTickets}
                  onEditTicket={(ticket) => setArcherModal({ ticket })}
                  onDeleteTicket={handleDeleteArcherTicket}
                  onFilterByExc={(exc) => onNavigate('triage', { reportingExcFilter: exc })}
                  onAddTicket={() => setArcherModal({ context: null })}
                  canDeleteTicket={canDelete}
                />
              ),
              ivanti: (
                <IvantiWorkflowPanel embedded />
              ),
            }}
          </SidebarTabs>
        </div>
      </div>

      {/* Modals */}
      {showAddCVE && (
        <AddCVEModal
          onClose={() => setShowAddCVE(false)}
          onSuccess={() => { fetchCVEs(); fetchVendors(); }}
        />
      )}

      {editingCVE && (
        <EditCVEModal
          cve={editingCVE}
          onClose={() => setEditingCVE(null)}
          onSuccess={() => { fetchCVEs(); fetchVendors(); }}
        />
      )}

      {jiraModal && (
        <JiraTicketModal
          ticket={jiraModal.ticket || null}
          context={jiraModal.context || null}
          onClose={() => setJiraModal(null)}
          onSuccess={fetchJiraTickets}
        />
      )}

      {archerModal && (
        <ArcherTicketModal
          ticket={archerModal.ticket || null}
          context={archerModal.context || null}
          onClose={() => setArcherModal(null)}
          onSuccess={fetchArcherTickets}
        />
      )}

      {/* Confirmation Modal */}
      <ConfirmModal
        open={!!pendingConfirm}
        title={pendingConfirm?.title}
        message={pendingConfirm?.message}
        confirmText={pendingConfirm?.confirmText}
        variant={pendingConfirm?.variant || 'danger'}
        onConfirm={pendingConfirm?.onConfirm}
        onCancel={() => setPendingConfirm(null)}
      />
    </>
  );
}
