import React, { useState } from 'react';
import { XCircle, RefreshCw, 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 EditCVEModal({ cve, onClose, onSuccess }) {
  const toast = useToast();
  const [form, setForm] = useState({
    cve_id: cve.cve_id,
    vendor: cve.vendor,
    severity: cve.severity,
    description: cve.description || '',
    published_date: cve.published_date || '',
    status: cve.status || 'Open',
  });
  const [nvdLoading, setNvdLoading] = useState(false);
  const [nvdError, setNvdError] = useState(null);
  const [nvdAutoFilled, setNvdAutoFilled] = useState(false);

  const lookupNVD = async () => {
    const trimmed = form.cve_id.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: data.description || prev.description,
        severity: data.severity || prev.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();

    const body = {};
    if (form.cve_id !== cve.cve_id) body.cve_id = form.cve_id;
    if (form.vendor !== cve.vendor) body.vendor = form.vendor;
    if (form.severity !== cve.severity) body.severity = form.severity;
    if (form.description !== (cve.description || '')) body.description = form.description;
    if (form.published_date !== (cve.published_date || '')) body.published_date = form.published_date;
    if (form.status !== (cve.status || 'Open')) body.status = form.status;

    if (Object.keys(body).length === 0) {
      toast.info('No changes detected.');
      return;
    }

    try {
      const response = await fetch(`${API_BASE}/cves/${cve.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(body),
      });
      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || 'Failed to update CVE');
      }
      toast.success('CVE updated successfully');
      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">Edit 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-warning/30 rounded">
            <p className="text-sm text-white">
              <strong className="text-intel-warning">Note:</strong> Changing CVE ID or Vendor will move associated documents to the new path.
            </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
                  value={form.cve_id}
                  onChange={(e) => { setForm({ ...form, cve_id: e.target.value.toUpperCase() }); setNvdAutoFilled(false); setNvdError(null); }}
                  className="intel-input w-full"
                />
                {nvdLoading && <Loader className="absolute right-3 top-2.5 w-5 h-5 text-intel-accent animate-spin" />}
              </div>
              {nvdAutoFilled && (
                <p className="text-xs text-intel-success mt-1 flex items-center gap-1">
                  <CheckCircle className="w-3 h-3" /> Updated 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
                value={form.vendor}
                onChange={(e) => setForm({ ...form, vendor: e.target.value })}
                className="intel-input w-full"
              />
            </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
                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>
              <label className="block text-xs font-medium text-gray-300 mb-2 uppercase tracking-wider">Status *</label>
              <select value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })} className="intel-input w-full">
                <option value="Open">Open</option>
                <option value="Addressed">Addressed</option>
                <option value="In Progress">In Progress</option>
                <option value="Resolved">Resolved</option>
              </select>
            </div>

            <div className="flex gap-3 pt-4">
              <button
                type="button"
                onClick={lookupNVD}
                disabled={nvdLoading}
                className="intel-button intel-button-success flex items-center gap-2 disabled:opacity-50"
              >
                <RefreshCw className={`w-4 h-4 ${nvdLoading ? 'animate-spin' : ''}`} />
                NVD Update
              </button>
              <button type="submit" className="flex-1 intel-button intel-button-primary">Save Changes</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>
  );
}
