'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useOrgAdmin } from '@/app/_lib/org-admin-context';

const MATCH_TYPES = ['HASHTAG', 'PREFIX', 'REACTION_EMOJI'];
const ACTIONS = ['FLAG', 'AUTO_APPROVE', 'SKIP', 'REJECT', 'P1'];

export default function OrgRulesPage() {
  const { orgAdmin, loading } = useOrgAdmin();
  const router = useRouter();
  const [rules, setRules] = useState<any[]>([]);
  const [showAdd, setShowAdd] = useState(false);
  const [form, setForm] = useState({ matchType: 'HASHTAG', matchValue: '', action: 'FLAG', priority: 0 });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  async function load() {
    const res = await fetch('/api/org/rules');
    if (res.ok) setRules(await res.json());
  }

  useEffect(() => {
    if (loading) return;
    if (!orgAdmin) { router.replace('/org/login'); return; }
    void load();
  }, [orgAdmin, loading, router]);

  async function handleAdd(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    setSaving(true);
    try {
      const res = await fetch('/api/org/rules', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.message ?? 'Failed');
      }
      setShowAdd(false);
      setForm({ matchType: 'HASHTAG', matchValue: '', action: 'FLAG', priority: 0 });
      void load();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error');
    } finally {
      setSaving(false);
    }
  }

  async function toggleActive(rule: any) {
    await fetch(`/api/org/rules/${rule.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ isActive: !rule.isActive }),
    });
    void load();
  }

  async function deleteRule(id: string) {
    if (!confirm('Delete this rule?')) return;
    await fetch(`/api/org/rules/${id}`, { method: 'DELETE' });
    void load();
  }

  if (loading || !orgAdmin) return <p className="text-gray-500">Loading...</p>;

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">Org-wide Rules</h1>
          <p className="text-sm text-gray-500 mt-1">These rules apply to all chapters and take priority over chapter-specific rules.</p>
        </div>
        <button
          onClick={() => setShowAdd(!showAdd)}
          className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700"
        >
          Add Rule
        </button>
      </div>

      {showAdd && (
        <form onSubmit={(e) => void handleAdd(e)} className="bg-white rounded-xl border p-5 mb-6 flex flex-col gap-4">
          <h2 className="font-semibold">New Org Rule</h2>
          <div className="grid grid-cols-4 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1">Match type</label>
              <select
                value={form.matchType}
                onChange={(e) => setForm({ ...form, matchType: e.target.value })}
                className="w-full border rounded-lg px-3 py-2 text-sm"
              >
                {MATCH_TYPES.map((t) => <option key={t}>{t}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Match value</label>
              <input
                type="text"
                value={form.matchValue}
                onChange={(e) => setForm({ ...form, matchValue: e.target.value })}
                className="w-full border rounded-lg px-3 py-2 text-sm"
                placeholder="e.g. #emergency"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Action</label>
              <select
                value={form.action}
                onChange={(e) => setForm({ ...form, action: e.target.value })}
                className="w-full border rounded-lg px-3 py-2 text-sm"
              >
                {ACTIONS.map((a) => <option key={a}>{a}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Priority</label>
              <input
                type="number"
                value={form.priority}
                onChange={(e) => setForm({ ...form, priority: Number(e.target.value) })}
                className="w-full border rounded-lg px-3 py-2 text-sm"
              />
            </div>
          </div>
          {error && <p className="text-red-600 text-sm">{error}</p>}
          <div className="flex gap-2">
            <button type="submit" disabled={saving} className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700 disabled:opacity-50">
              {saving ? 'Saving...' : 'Save Rule'}
            </button>
            <button type="button" onClick={() => setShowAdd(false)} className="border rounded-lg px-4 py-2 text-sm hover:bg-gray-50">
              Cancel
            </button>
          </div>
        </form>
      )}

      <div className="bg-white rounded-xl border overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 text-left">
            <tr>
              <th className="px-4 py-3 font-medium">Match type</th>
              <th className="px-4 py-3 font-medium">Match value</th>
              <th className="px-4 py-3 font-medium">Action</th>
              <th className="px-4 py-3 font-medium">Priority</th>
              <th className="px-4 py-3 font-medium">Active</th>
              <th className="px-4 py-3 font-medium"></th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {rules.map((r: any) => (
              <tr key={r.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 text-gray-500">{r.matchType}</td>
                <td className="px-4 py-3 font-mono">{r.matchValue}</td>
                <td className="px-4 py-3">
                  <span className="text-xs font-medium px-2 py-1 rounded-full bg-blue-100 text-blue-700">{r.action}</span>
                </td>
                <td className="px-4 py-3 text-gray-500">{r.priority}</td>
                <td className="px-4 py-3">
                  <button
                    onClick={() => void toggleActive(r)}
                    className={`text-xs font-medium px-2 py-1 rounded-full ${r.isActive ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}
                  >
                    {r.isActive ? 'Active' : 'Inactive'}
                  </button>
                </td>
                <td className="px-4 py-3">
                  <button
                    onClick={() => void deleteRule(r.id)}
                    className="text-xs text-red-600 hover:text-red-800"
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {rules.length === 0 && <p className="p-4 text-gray-400">No org rules yet.</p>}
      </div>
    </div>
  );
}
