import { useState } from 'react';
import useSWR, { mutate } from 'swr';
import { api, type RoutingRule } from '../lib/api';

const STRATEGIES = ['passthrough', 'cheapest', 'quality-first', 'cascading'];
const COMPLEXITIES = ['low', 'medium', 'high'];

export default function Rules() {
  const { data: rules } = useSWR('rules', api.listRules);
  const [editing, setEditing] = useState<RoutingRule | null>(null);
  const [isNew, setIsNew] = useState(false);

  const blank: RoutingRule = {
    priority: (rules?.length ?? 0) + 1,
    name: '',
    strategy: 'cheapest',
    enabled: true,
  };

  const save = async () => {
    if (!editing) return;
    if (isNew) {
      await api.createRule(editing);
    } else if (editing.id) {
      await api.updateRule(editing.id, editing);
    }
    setEditing(null);
    setIsNew(false);
    mutate('rules');
  };

  const remove = async (id: string) => {
    if (!confirm('Delete this rule?')) return;
    await api.deleteRule(id);
    mutate('rules');
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-semibold">Routing Rules</h2>
        <button
          onClick={() => { setEditing(blank); setIsNew(true); }}
          className="px-3 py-1.5 bg-dd0c-primary text-white text-sm rounded-md hover:bg-dd0c-primary/80"
        >
          + Add Rule
        </button>
      </div>

      {/* Rules table */}
      <div className="bg-dd0c-surface border border-dd0c-border rounded-lg overflow-hidden">
        <table className="w-full text-sm" role="table">
          <thead>
            <tr className="text-dd0c-muted text-xs uppercase tracking-wide border-b border-dd0c-border">
              <th className="text-left py-2 px-3">Priority</th>
              <th className="text-left py-2 px-3">Name</th>
              <th className="text-left py-2 px-3">Match</th>
              <th className="text-left py-2 px-3">Strategy</th>
              <th className="text-left py-2 px-3">Target</th>
              <th className="text-center py-2 px-3">Enabled</th>
              <th className="text-right py-2 px-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {(rules ?? []).map((rule) => (
              <tr key={rule.id} className="border-b border-dd0c-border/50 hover:bg-dd0c-border/20">
                <td className="py-2 px-3 font-mono">{rule.priority}</td>
                <td className="py-2 px-3">{rule.name}</td>
                <td className="py-2 px-3 text-dd0c-muted text-xs font-mono">
                  {[
                    rule.match_model && `model=${rule.match_model}`,
                    rule.match_feature && `feature=${rule.match_feature}`,
                    rule.match_team && `team=${rule.match_team}`,
                    rule.match_complexity && `complexity=${rule.match_complexity}`,
                  ].filter(Boolean).join(', ') || '*'}
                </td>
                <td className="py-2 px-3">
                  <span className="px-2 py-0.5 rounded text-xs bg-dd0c-primary/20 text-dd0c-primary">
                    {rule.strategy}
                  </span>
                </td>
                <td className="py-2 px-3 font-mono text-dd0c-accent text-xs">
                  {rule.target_model || '—'}
                </td>
                <td className="py-2 px-3 text-center">
                  {rule.enabled ? '✅' : '⏸️'}
                </td>
                <td className="py-2 px-3 text-right space-x-2">
                  <button
                    onClick={() => { setEditing(rule); setIsNew(false); }}
                    className="text-dd0c-muted hover:text-dd0c-text text-xs"
                  >
                    Edit
                  </button>
                  <button
                    onClick={() => rule.id && remove(rule.id)}
                    className="text-dd0c-danger/60 hover:text-dd0c-danger text-xs"
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
            {(rules ?? []).length === 0 && (
              <tr>
                <td colSpan={7} className="py-8 text-center text-dd0c-muted">
                  No routing rules yet. Add one to start saving.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* Edit modal */}
      {editing && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" role="dialog" aria-modal="true">
          <div className="bg-dd0c-surface border border-dd0c-border rounded-lg p-6 w-full max-w-lg space-y-4">
            <h3 className="text-lg font-semibold">{isNew ? 'New Rule' : 'Edit Rule'}</h3>

            <div className="grid grid-cols-2 gap-3">
              <label className="block">
                <span className="text-xs text-dd0c-muted">Name</span>
                <input
                  value={editing.name}
                  onChange={(e) => setEditing({ ...editing, name: e.target.value })}
                  className="mt-1 w-full bg-dd0c-bg border border-dd0c-border rounded px-2 py-1.5 text-sm"
                />
              </label>
              <label className="block">
                <span className="text-xs text-dd0c-muted">Priority</span>
                <input
                  type="number"
                  value={editing.priority}
                  onChange={(e) => setEditing({ ...editing, priority: parseInt(e.target.value) || 0 })}
                  className="mt-1 w-full bg-dd0c-bg border border-dd0c-border rounded px-2 py-1.5 text-sm"
                />
              </label>
              <label className="block">
                <span className="text-xs text-dd0c-muted">Match Model</span>
                <input
                  value={editing.match_model ?? ''}
                  onChange={(e) => setEditing({ ...editing, match_model: e.target.value || undefined })}
                  placeholder="gpt-4o"
                  className="mt-1 w-full bg-dd0c-bg border border-dd0c-border rounded px-2 py-1.5 text-sm"
                />
              </label>
              <label className="block">
                <span className="text-xs text-dd0c-muted">Match Complexity</span>
                <select
                  value={editing.match_complexity ?? ''}
                  onChange={(e) => setEditing({ ...editing, match_complexity: e.target.value || undefined })}
                  className="mt-1 w-full bg-dd0c-bg border border-dd0c-border rounded px-2 py-1.5 text-sm"
                >
                  <option value="">Any</option>
                  {COMPLEXITIES.map((c) => <option key={c} value={c}>{c}</option>)}
                </select>
              </label>
              <label className="block">
                <span className="text-xs text-dd0c-muted">Strategy</span>
                <select
                  value={editing.strategy}
                  onChange={(e) => setEditing({ ...editing, strategy: e.target.value })}
                  className="mt-1 w-full bg-dd0c-bg border border-dd0c-border rounded px-2 py-1.5 text-sm"
                >
                  {STRATEGIES.map((s) => <option key={s} value={s}>{s}</option>)}
                </select>
              </label>
              <label className="block">
                <span className="text-xs text-dd0c-muted">Target Model</span>
                <input
                  value={editing.target_model ?? ''}
                  onChange={(e) => setEditing({ ...editing, target_model: e.target.value || undefined })}
                  placeholder="gpt-4o-mini"
                  className="mt-1 w-full bg-dd0c-bg border border-dd0c-border rounded px-2 py-1.5 text-sm"
                />
              </label>
            </div>

            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={editing.enabled}
                onChange={(e) => setEditing({ ...editing, enabled: e.target.checked })}
              />
              <span className="text-sm">Enabled</span>
            </label>

            <div className="flex justify-end gap-2 pt-2">
              <button
                onClick={() => { setEditing(null); setIsNew(false); }}
                className="px-3 py-1.5 text-sm text-dd0c-muted hover:text-dd0c-text"
              >
                Cancel
              </button>
              <button
                onClick={save}
                className="px-3 py-1.5 bg-dd0c-primary text-white text-sm rounded-md hover:bg-dd0c-primary/80"
              >
                {isNew ? 'Create' : 'Save'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
