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

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

/**
 * Shared modal for adding and editing JIRA tickets.
 * Props:
 *   - ticket: existing ticket object (edit mode) or null (add mode)
 *   - context: { cve_id, vendor } when adding from a CVE card
 *   - onClose: close handler
 *   - onSuccess: refresh handler
 */
export default function JiraTicketModal({ ticket, context, onClose, onSuccess }) {
  const toast = useToast();
  const isEdit = !!ticket;

  const [form, setForm] = useState({
    cve_id: ticket?.cve_id || context?.cve_id || '',
    vendor: ticket?.vendor || context?.vendor || '',
    ticket_key: ticket?.ticket_key || '',
    url: ticket?.url || '',
    summary: ticket?.summary || '',
    status: ticket?.status || 'Open',
  });

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (isEdit) {
        const response = await fetch(`${API_BASE}/jira-tickets/${ticket.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify({
            ticket_key: form.ticket_key,
            url: form.url,
            summary: form.summary,
            status: form.status,
          }),
        });
        if (!response.ok) {
          const data = await response.json();
          throw new Error(data.error || 'Failed to update ticket');
        }
        toast.success('JIRA ticket updated');
      } else {
        const response = await fetch(`${API_BASE}/jira-tickets`, {
          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 create ticket');
        }
        toast.success('JIRA ticket added');
      }
      onSuccess();
      onClose();
    } catch (err) {
      toast.error(err.message);
    }
  };

  const showCVEFields = !isEdit && !context;

  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-md w-full border-intel-warning">
        <div className="p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-bold text-intel-warning font-mono">
              {isEdit ? 'Edit JIRA Ticket' : 'Add JIRA Ticket'}
            </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>

          {/* Context info */}
          {(isEdit || context) && (
            <div className="p-3 bg-intel-medium rounded text-sm text-white mb-4 font-mono">
              {isEdit ? `${ticket.cve_id} / ${ticket.vendor}` : `Adding ticket for `}
              {context && !isEdit && (
                <>
                  <strong className="text-intel-warning">{context.cve_id}</strong> / <strong className="text-intel-warning">{context.vendor}</strong>
                </>
              )}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            {showCVEFields && (
              <>
                <div>
                  <label className="block text-xs font-medium text-gray-300 mb-2 uppercase tracking-wider">CVE ID *</label>
                  <input
                    type="text"
                    required
                    placeholder="CVE-2024-1234"
                    value={form.cve_id}
                    onChange={(e) => setForm({ ...form, cve_id: e.target.value.toUpperCase() })}
                    className="intel-input w-full"
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-300 mb-2 uppercase tracking-wider">Vendor *</label>
                  <input
                    type="text"
                    required
                    placeholder="Cisco"
                    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">Ticket Key *</label>
              <input
                type="text"
                required
                placeholder="VULN-1234"
                value={form.ticket_key}
                onChange={(e) => setForm({ ...form, ticket_key: e.target.value.toUpperCase() })}
                className="intel-input w-full"
              />
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-300 mb-2 uppercase tracking-wider">JIRA URL</label>
              <input
                type="url"
                placeholder="https://jira.company.com/browse/VULN-1234"
                value={form.url}
                onChange={(e) => setForm({ ...form, url: 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">Summary</label>
              <input
                type="text"
                placeholder="Brief description"
                value={form.summary}
                onChange={(e) => setForm({ ...form, summary: 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="In Progress">In Progress</option>
                <option value="Closed">Closed</option>
                {form.status && !['Open', 'In Progress', 'Closed'].includes(form.status) && (
                  <option value={form.status}>{form.status}</option>
                )}
              </select>
            </div>

            <div className="flex gap-3 pt-4">
              <button type="submit" className="flex-1 intel-button intel-button-primary">
                {isEdit ? 'Save Changes' : 'Add Ticket'}
              </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>
  );
}
