import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useApi } from '../hooks/useApi.js';

export default function RuleAssigner({ category, currentRuleIds, onSave, onClose }) {
  const { data: rules, loading, error } = useApi('/rules');
  const [selected, setSelected] = useState(new Set(currentRuleIds));
  const [saving, setSaving] = useState(false);

  const toggleRule = (ruleId) => {
    const next = new Set(selected);
    if (next.has(ruleId)) {
      next.delete(ruleId);
    } else {
      next.add(ruleId);
    }
    setSelected(next);
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      await onSave([...selected]);
    } finally {
      setSaving(false);
    }
  };

  const ruleList = Array.isArray(rules) ? rules : [];

  return (
    <AnimatePresence>
      <motion.div
        className="fixed inset-0 z-[200] flex items-center justify-center"
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        onClick={onClose}
      >
        {/* Backdrop */}
        <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />

        {/* Modal */}
        <motion.div
          className="relative glass-card-dark w-[90%] max-w-[500px] max-h-[80vh] flex flex-col p-5"
          initial={{ scale: 0.95, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          exit={{ scale: 0.95, opacity: 0 }}
          transition={{ duration: 0.2 }}
          onClick={(e) => e.stopPropagation()}
        >
          <h3 className="font-serif text-lg text-cream mb-4 tracking-wide">
            Assign Rules: {category}
          </h3>

          {loading && (
            <div className="py-8 text-center text-cream-dark text-sm tracking-widest uppercase">
              Loading rules...
            </div>
          )}

          {error && (
            <div className="glass-card p-3 mb-3 border-blockRed/30 bg-blockRed/10">
              <span className="text-blockRed text-sm">{error}</span>
            </div>
          )}

          {/* Rule list */}
          <div className="flex-1 overflow-y-auto mb-4 max-h-[50vh] space-y-1">
            {ruleList.length === 0 && !loading ? (
              <div className="py-8 text-center text-cream-dark text-sm italic">
                No traffic rules found. Connect to UDR to discover rules.
              </div>
            ) : (
              ruleList.map((rule) => (
                <label
                  key={rule._id}
                  className="flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-colors hover:bg-cream/5"
                >
                  <input
                    type="checkbox"
                    checked={selected.has(rule._id)}
                    onChange={() => toggleRule(rule._id)}
                    className="w-4 h-4 accent-manor-green rounded"
                  />
                  <div className="flex flex-col gap-0.5 min-w-0">
                    <span className="text-cream text-sm truncate">
                      {rule.description || rule.name || rule._id}
                    </span>
                    <span className={`text-[0.6rem] uppercase tracking-wider ${
                      rule.enabled ? 'text-blockRed' : 'text-cream-dark'
                    }`}>
                      {rule.enabled ? 'Blocking' : 'Inactive'}
                    </span>
                  </div>
                </label>
              ))
            )}
          </div>

          {/* Actions */}
          <div className="flex gap-3 justify-end">
            <button className="btn-manor btn-manor-ghost" onClick={onClose}>
              Cancel
            </button>
            <button
              className="btn-manor btn-manor-green"
              onClick={handleSave}
              disabled={saving}
            >
              {saving ? 'Saving...' : `Save (${selected.size} rules)`}
            </button>
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}
