import React, { useState } from 'react';
import { XCircle, Loader, CheckCircle, AlertCircle } from 'lucide-react';
import { useToast } from '../../contexts/ToastContext';

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

export default function AddCVEModal({ onClose, onSuccess }) {
  const toast = useToast();
  const [form, setForm] = useState({
    cve_id: '',
    vendor: '',
    severity: 'Medium',
    description: '',
    published_date: new Date().toISOString().split('T')[0],
  });
  const [nvdLoading, setNvdLoading] = useState(false);
  const [nvdError, setNvdError] = useState(null);
  const [nvdAutoFilled, setNvdAutoFilled] = useState(false);

  const lookupNVD = async (cveId) => {
    const trimmed = cveId.trim();
    if (!/^CVE-\d{4}-\d{4,}$/.test(trimmed)) return;

    setNvdLoading(true);
    setNvdError(null);
    setNvdAutoFilled(false);

    try {
      const response = await fetch(`${API_BASE}/nvd/lookup/${encodeURIComponent(trimmed)}`, { credentials: 'include' });
      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || 'NVD lookup failed');
      }
      const data = await response.json();
      setForm(prev => ({
        ...prev,
        description: prev.description || data.description,
        severity: data.severity,
        published_date: data.published_date || prev.published_date,
      }));
      setNvdAutoFilled(true);
    } catch (err) {
      setNvdError(err.message);
    } finally {
      setNvdLoading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await fetch(`${API_BASE}/cves`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(form),
      });
      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || 'Failed to add CVE');
      }
      toast.success(`CVE ${form.cve_id} added for vendor: ${form.vendor}`);
      onSuccess();
      onClose();
    } catch (err) {
      toast.error(err.message);
    }
  };

  return (
    <div className="fixed inset-0 modal-overlay flex items-center justify-center z-50 p-4">
      <div className="intel-card rounded-lg shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto border-intel-accent">
        <div className="p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-2xl font-bold text-intel-accent font-mono">Add CVE Entry</h2>
            <button onClick={onClose} className="text-gray-400 hover:text-intel-accent transition-colors" aria-label="Close">
              <XCircle className="w-6 h-6" />
            </button>
          </div>

          <div className="mb-4 p-3 bg-intel-medium border border-intel-accent/30 rounded">
            <p className="text-sm text-white">
              <strong className="text-intel-accent">Tip:</strong> You can add the same CVE-ID multiple times with different vendors.
              Each vendor will have its own documents folder.
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-xs font-medium text-gray-300 mb-2 uppercase tracking-wider">CVE ID *</label>
              <div className="relative">
                <input
                  type="text"
                  required
                  placeholder="CVE-2024-1234"
                  value={form.cve_id}
                  onChange={(e) => { setForm({ ...form, cve_id: e.target.value.toUpperCase() }); setNvdAutoFilled(false); setNvdError(null); }}
                  onBlur={(e) => lookupNVD(e.target.value)}
                  className="intel-input w-full"
                />
                {nvdLoading && <Loader className="absolute right-3 top-2.5 w-5 h-5 text-intel-accent animate-spin" />}
              </div>
              <p className="text-xs text-gray-500 mt-1">Can be the same as existing CVE if adding another vendor</p>
              {nvdAutoFilled && (
                <p className="text-xs text-intel-success mt-1 flex items-center gap-1">
                  <CheckCircle className="w-3 h-3" /> Auto-filled from NVD
                </p>
              )}
              {nvdError && (
                <p className="text-xs text-intel-warning mt-1 flex items-center gap-1">
                  <AlertCircle className="w-3 h-3" /> {nvdError}
                </p>
              )}
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-300 mb-2 uppercase tracking-wider">Vendor *</label>
              <input
                type="text"
                required
                placeholder="Microsoft, Cisco, Oracle, etc."
                value={form.vendor}
                onChange={(e) => setForm({ ...form, vendor: e.target.value })}
                className="intel-input w-full"
              />
              <p className="text-xs text-gray-500 mt-1">Must be unique for this CVE-ID</p>
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-300 mb-2 uppercase tracking-wider">Severity *</label>
              <select value={form.severity} onChange={(e) => setForm({ ...form, severity: e.target.value })} className="intel-input w-full">
                <option value="Critical">Critical</option>
                <option value="High">High</option>
                <option value="Medium">Medium</option>
                <option value="Low">Low</option>
              </select>
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-300 mb-2 uppercase tracking-wider">Description *</label>
              <textarea
                required
                placeholder="Brief description of the vulnerability"
                value={form.description}
                onChange={(e) => setForm({ ...form, description: e.target.value })}
                rows={3}
                className="intel-input w-full"
              />
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-300 mb-2 uppercase tracking-wider">Published Date *</label>
              <input
                type="date"
                required
                value={form.published_date}
                onChange={(e) => setForm({ ...form, published_date: e.target.value })}
                className="intel-input w-full"
              />
            </div>

            <div className="flex gap-3 pt-4">
              <button type="submit" className="flex-1 intel-button intel-button-primary">Add CVE Entry</button>
              <button type="button" onClick={onClose} className="px-4 py-2 bg-intel-dark text-gray-400 rounded border border-gray-600 hover:bg-intel-medium transition-colors font-mono text-sm uppercase tracking-wider">
                Cancel
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
