import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useToast } from './ToastProvider';

// Existing hardcoded categories — used for datalist autocomplete
const KNOWN_CATEGORIES = [
  'Attendance & Punctuality',
  'Administrative Integrity',
  'Financial Stewardship',
  'Operational Response',
  'Professional Conduct',
  'Work From Home',
  'Safety & Security',
];

const CONTEXT_FIELDS = [
  { key: 'time',        label: 'Incident Time' },
  { key: 'minutes',     label: 'Minutes Late' },
  { key: 'amount',      label: 'Amount / Value' },
  { key: 'location',    label: 'Location / Context' },
  { key: 'description', label: 'Additional Details' },
];

const s = {
  overlay:   { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' },
  modal:     { background: '#111217', border: '1px solid #2a2b3a', borderRadius: '10px', width: '100%', maxWidth: '620px', maxHeight: '90vh', overflowY: 'auto', padding: '32px' },
  title:     { color: '#f8f9fa', fontSize: '20px', fontWeight: 700, marginBottom: '24px', borderBottom: '1px solid #2a2b3a', paddingBottom: '12px' },
  label:     { fontWeight: 600, color: '#e5e7f1', marginBottom: '5px', fontSize: '13px', display: 'block' },
  input:     { width: '100%', padding: '10px', border: '1px solid #333544', borderRadius: '4px', fontSize: '14px', fontFamily: 'inherit', background: '#050608', color: '#f8f9fa', boxSizing: 'border-box' },
  textarea:  { width: '100%', padding: '10px', border: '1px solid #333544', borderRadius: '4px', fontSize: '13px', fontFamily: 'inherit', background: '#050608', color: '#f8f9fa', resize: 'vertical', minHeight: '80px', boxSizing: 'border-box' },
  group:     { marginBottom: '18px' },
  hint:      { fontSize: '11px', color: '#9ca0b8', marginTop: '4px', fontStyle: 'italic' },
  row:       { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' },
  toggle:    { display: 'flex', gap: '8px', marginTop: '6px' },
  toggleBtn: (active) => ({
    padding: '7px 18px', borderRadius: '4px', fontSize: '13px', fontWeight: 600, cursor: 'pointer', border: '1px solid',
    background: active ? '#d4af37' : '#050608',
    color:      active ? '#000'    : '#9ca0b8',
    borderColor: active ? '#d4af37' : '#333544',
  }),
  fieldGrid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginTop: '8px' },
  checkbox:  { display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', color: '#d1d3e0', cursor: 'pointer' },
  btnRow:    { display: 'flex', gap: '12px', justifyContent: 'flex-end', marginTop: '28px', paddingTop: '16px', borderTop: '1px solid #2a2b3a' },
  btnSave:   { padding: '10px 28px', fontSize: '14px', fontWeight: 600, border: 'none', borderRadius: '6px', cursor: 'pointer', background: 'linear-gradient(135deg, #d4af37 0%, #ffdf8a 100%)', color: '#000' },
  btnDanger: { padding: '10px 18px', fontSize: '14px', fontWeight: 600, border: '1px solid #721c24', borderRadius: '6px', cursor: 'pointer', background: '#3c1114', color: '#ffb3b8' },
  btnCancel: { padding: '10px 18px', fontSize: '14px', fontWeight: 600, border: '1px solid #333544', borderRadius: '6px', cursor: 'pointer', background: '#050608', color: '#f8f9fa' },
  section:   { background: '#181924', border: '1px solid #2a2b3a', borderRadius: '6px', padding: '16px', marginBottom: '18px' },
  secTitle:  { color: '#d4af37', fontSize: '13px', fontWeight: 700, marginBottom: '12px', textTransform: 'uppercase', letterSpacing: '0.05em' },
  customBadge: { display: 'inline-block', marginLeft: '8px', padding: '1px 7px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: '#1a2e1a', color: '#4caf50', border: '1px solid #4caf50', verticalAlign: 'middle' },
};

const EMPTY = {
  name: '', category: '', chapter: '', description: '',
  pointType: 'fixed',   // 'fixed' | 'sliding'
  fixedPoints: 1,
  minPoints: 1,
  maxPoints: 5,
  fields: ['description'],
};

export default function ViolationTypeModal({ onClose, onSaved, editing = null }) {
  const [form,    setForm]    = useState(EMPTY);
  const [saving,  setSaving]  = useState(false);
  const [deleting, setDeleting] = useState(false);
  const toast = useToast();

  // Populate form when editing an existing type
  useEffect(() => {
    if (editing) {
      const isSliding = editing.min_points !== editing.max_points;
      setForm({
        name:        editing.name,
        category:    editing.category,
        chapter:     editing.chapter     || '',
        description: editing.description || '',
        pointType:   isSliding ? 'sliding' : 'fixed',
        fixedPoints: isSliding ? editing.min_points : editing.min_points,
        minPoints:   editing.min_points,
        maxPoints:   editing.max_points,
        fields:      editing.fields || ['description'],
      });
    }
  }, [editing]);

  const set = (key, val) => setForm(prev => ({ ...prev, [key]: val }));

  const toggleField = key => {
    setForm(prev => ({
      ...prev,
      fields: prev.fields.includes(key)
        ? prev.fields.filter(f => f !== key)
        : [...prev.fields, key],
    }));
  };

  const handleSave = async () => {
    if (!form.name.trim()) { toast.warning('Violation name is required.'); return; }
    if (!form.category.trim()) { toast.warning('Category is required.'); return; }

    const minPts = form.pointType === 'fixed' ? parseInt(form.fixedPoints) || 1 : parseInt(form.minPoints) || 1;
    const maxPts = form.pointType === 'fixed' ? minPts                           : parseInt(form.maxPoints) || 1;

    if (maxPts < minPts) { toast.warning('Max points must be >= min points.'); return; }
    if (form.fields.length === 0) { toast.warning('Select at least one context field.'); return; }

    const payload = {
      name:        form.name.trim(),
      category:    form.category.trim(),
      chapter:     form.chapter.trim()     || null,
      description: form.description.trim() || null,
      min_points:  minPts,
      max_points:  maxPts,
      fields:      form.fields,
    };

    setSaving(true);
    try {
      let saved;
      if (editing) {
        const res = await axios.put(`/api/violation-types/${editing.id}`, payload);
        saved = res.data;
        toast.success(`"${saved.name}" updated.`);
      } else {
        const res = await axios.post('/api/violation-types', payload);
        saved = res.data;
        toast.success(`"${saved.name}" added to violation types.`);
      }
      onSaved(saved);
    } catch (err) {
      toast.error(err.response?.data?.error || err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!editing) return;
    if (!window.confirm(`Delete "${editing.name}"? This cannot be undone and will fail if any violations reference this type.`)) return;
    setDeleting(true);
    try {
      await axios.delete(`/api/violation-types/${editing.id}`);
      toast.success(`"${editing.name}" deleted.`);
      onSaved(null); // null signals a deletion to the parent
    } catch (err) {
      toast.error(err.response?.data?.error || err.message);
    } finally {
      setDeleting(false);
    }
  };

  return (
    <div style={s.overlay} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={s.modal}>
        <div style={s.title}>
          {editing ? 'Edit Violation Type' : 'Add Violation Type'}
          {editing && <span style={s.customBadge}>CUSTOM</span>}
        </div>

        {/* Basic Info */}
        <div style={s.section}>
          <div style={s.secTitle}>Violation Definition</div>

          <div style={s.group}>
            <label style={s.label}>Violation Name *</label>
            <input
              style={s.input}
              type="text"
              value={form.name}
              onChange={e => set('name', e.target.value)}
              placeholder="e.g. Unauthorized System Access"
            />
          </div>

          <div style={s.group}>
            <label style={s.label}>Category *</label>
            <input
              style={s.input}
              type="text"
              list="vt-categories"
              value={form.category}
              onChange={e => set('category', e.target.value)}
              placeholder="Select existing or type new category"
            />
            <datalist id="vt-categories">
              {KNOWN_CATEGORIES.map(c => <option key={c} value={c} />)}
            </datalist>
            <div style={s.hint}>Choose an existing category or type a new one to create a new group in the dropdown.</div>
          </div>

          <div style={s.group}>
            <label style={s.label}>Handbook Reference / Chapter</label>
            <input
              style={s.input}
              type="text"
              value={form.chapter}
              onChange={e => set('chapter', e.target.value)}
              placeholder="e.g. Chapter 4, Section 6"
            />
          </div>

          <div style={s.group}>
            <label style={s.label}>Description / Reference Text</label>
            <textarea
              style={s.textarea}
              value={form.description}
              onChange={e => set('description', e.target.value)}
              placeholder="Paste the relevant handbook language or describe the infraction in plain terms..."
            />
            <div style={s.hint}>Shown in the context box on the violation form and printed on the PDF.</div>
          </div>
        </div>

        {/* Point Assignment */}
        <div style={s.section}>
          <div style={s.secTitle}>Point Assignment</div>

          <label style={s.label}>Point Type</label>
          <div style={s.toggle}>
            <button type="button" style={s.toggleBtn(form.pointType === 'fixed')}   onClick={() => set('pointType', 'fixed')}>Fixed</button>
            <button type="button" style={s.toggleBtn(form.pointType === 'sliding')} onClick={() => set('pointType', 'sliding')}>Sliding Range</button>
          </div>
          <div style={{ ...s.hint, marginTop: '6px' }}>
            Fixed = exact value every time. Sliding = supervisor adjusts within a min/max range.
          </div>

          {form.pointType === 'fixed' ? (
            <div style={{ ...s.group, marginTop: '14px' }}>
              <label style={s.label}>Points (Fixed)</label>
              <input
                style={{ ...s.input, width: '120px' }}
                type="number" min="1" max="30"
                value={form.fixedPoints}
                onChange={e => set('fixedPoints', e.target.value)}
              />
            </div>
          ) : (
            <div style={{ ...s.row, marginTop: '14px' }}>
              <div style={s.group}>
                <label style={s.label}>Min Points</label>
                <input
                  style={s.input}
                  type="number" min="1" max="30"
                  value={form.minPoints}
                  onChange={e => set('minPoints', e.target.value)}
                />
              </div>
              <div style={s.group}>
                <label style={s.label}>Max Points</label>
                <input
                  style={s.input}
                  type="number" min="1" max="30"
                  value={form.maxPoints}
                  onChange={e => set('maxPoints', e.target.value)}
                />
              </div>
            </div>
          )}
        </div>

        {/* Context Fields */}
        <div style={s.section}>
          <div style={s.secTitle}>Context Fields</div>
          <div style={s.hint}>Select which additional fields appear on the violation form for this type.</div>
          <div style={s.fieldGrid}>
            {CONTEXT_FIELDS.map(({ key, label }) => (
              <label key={key} style={s.checkbox}>
                <input
                  type="checkbox"
                  checked={form.fields.includes(key)}
                  onChange={() => toggleField(key)}
                />
                {label}
              </label>
            ))}
          </div>
        </div>

        <div style={s.btnRow}>
          {editing && (
            <button type="button" style={s.btnDanger} onClick={handleDelete} disabled={deleting}>
              {deleting ? 'Deleting…' : 'Delete Type'}
            </button>
          )}
          <button type="button" style={s.btnCancel} onClick={onClose}>Cancel</button>
          <button type="button" style={s.btnSave}   onClick={handleSave} disabled={saving}>
            {saving ? 'Saving…' : editing ? 'Save Changes' : 'Add Violation Type'}
          </button>
        </div>
      </div>
    </div>
  );
}
