'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import Modal from '@/components/Modal';
import PasswordInput from '@/components/PasswordInput';
import { Trash2 } from 'lucide-react';

type Session = { id: number; userAgent: string | null; ipAddress: string; createdAt: string; expiresAt: string };
type AllowlistEntry = { id: number; cidr: string; label: string | null; createdAt: string };

export default function SecuritySettingsPage() {
  const { accessToken, appSecretProof, user, logout, hasPermission } = useAuth();
  const { show } = useToast();
  const [sessions, setSessions] = useState<Session[]>([]);
  const [showReset, setShowReset] = useState(false);
  const [password, setPassword] = useState('');
  const [resetting, setResetting] = useState(false);
  const [resetError, setResetError] = useState<string | null>(null);

  const [allowlist, setAllowlist] = useState<AllowlistEntry[]>([]);
  const [newCidr, setNewCidr] = useState('');
  const [newLabel, setNewLabel] = useState('');
  const [addingIp, setAddingIp] = useState(false);

  useEffect(() => {
    if (!accessToken || !appSecretProof) return;
    adminApiFetch('/admin/security/sessions', accessToken, appSecretProof).then((d) => setSessions(d.sessions || []));
  }, [accessToken, appSecretProof]);

  useEffect(() => {
    if (!accessToken || !appSecretProof || !hasPermission('can_manage_security')) return;
    adminApiFetch('/admin/security/ip-allowlist', accessToken, appSecretProof)
      .then((d) => setAllowlist(d.entries || []))
      .catch(() => { /* silently hide the card for roles without access */ });
  }, [accessToken, appSecretProof, hasPermission]);

  async function revoke(id: number) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/security/sessions/${id}`, accessToken, appSecretProof, { method: 'DELETE' });
      setSessions((s) => s.filter((row) => row.id !== id));
      show('success', 'Session revoked.');
    } catch { show('error', 'Could not revoke that session.'); }
  }

  async function submitReset(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof) return;
    setResetting(true);
    setResetError(null);
    try {
      await adminApiFetch('/admin/security/2fa/reset', accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ password }),
      });
      show('info', '2FA reset — you will be signed out to re-enroll.');
      setTimeout(() => logout(), 1200);
    } catch {
      setResetError('Incorrect password.');
    } finally {
      setResetting(false);
    }
  }

  async function addIp(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !newCidr.trim()) return;
    setAddingIp(true);
    try {
      const d = await adminApiFetch('/admin/security/ip-allowlist', accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ cidr: newCidr, label: newLabel || undefined }),
      });
      setAllowlist((a) => [d.entry, ...a]);
      setNewCidr(''); setNewLabel('');
      show('success', `${newCidr} added to the allowlist.`);
    } catch { show('error', 'Could not add that entry — check the format (e.g. 41.220.10.0/24).'); }
    finally { setAddingIp(false); }
  }

  async function removeIp(id: number, cidr: string) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/security/ip-allowlist/${id}`, accessToken, appSecretProof, { method: 'DELETE' });
      setAllowlist((a) => a.filter((e) => e.id !== id));
      show('success', `${cidr} removed.`);
    } catch { show('error', 'Could not remove that entry.'); }
  }

  return (
    <div className="space-y-6 max-w-2xl">
      <div>
        <h1 className="text-lg font-bold mb-1">Security</h1>
        <p className="text-xs text-gray-500">Signed in as {user?.email} ({user?.role})</p>
      </div>

      <div className="bg-white border border-brand-border rounded-xl p-4">
        <h2 className="text-sm font-semibold mb-2">Two-Factor Authentication</h2>
        <p className="text-xs text-gray-500 mb-3">2FA is mandatory for every admin account and is enforced on the API, not just this screen.</p>
        <button onClick={() => setShowReset(true)} className="text-xs bg-brand-charcoal text-white px-3 py-1.5 rounded-lg transition-transform hover:scale-[1.03]">
          Re-enroll authenticator app
        </button>
      </div>

      <div className="bg-white border border-brand-border rounded-xl p-4">
        <h2 className="text-sm font-semibold mb-2">Active Sessions</h2>
        <div className="space-y-2">
          {sessions.map((s) => (
            <div key={s.id} className="flex items-center justify-between text-xs border-t border-brand-border pt-2 first:border-t-0 first:pt-0">
              <div>
                <p className="font-medium">{s.ipAddress}</p>
                <p className="text-gray-400">{s.userAgent?.slice(0, 60) ?? 'Unknown device'} · since {new Date(s.createdAt).toLocaleDateString()}</p>
              </div>
              <button onClick={() => revoke(s.id)} className="text-brand-red transition-colors hover:text-red-800">Revoke</button>
            </div>
          ))}
          {sessions.length === 0 && <p className="text-xs text-gray-400">No other active sessions.</p>}
        </div>
      </div>

      {hasPermission('can_manage_security') && (
        <div className="bg-white border border-brand-border rounded-xl p-4">
          <h2 className="text-sm font-semibold mb-1">IP Allowlist</h2>
          <p className="text-xs text-gray-500 mb-3">
            This list is a record only — actually blocking traffic outside these ranges is enforced at Cloudflare (see README), not by this app.
          </p>
          <form onSubmit={addIp} className="flex gap-2 mb-3">
            <input placeholder="41.220.10.0/24 or a single IP" value={newCidr} onChange={(e) => setNewCidr(e.target.value)}
              className="flex-1 border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            <input placeholder="Label (optional)" value={newLabel} onChange={(e) => setNewLabel(e.target.value)}
              className="w-32 border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            <button disabled={addingIp} className="bg-brand-charcoal text-white text-xs px-3 py-1.5 rounded-lg disabled:opacity-60">
              {addingIp ? 'Adding…' : 'Add'}
            </button>
          </form>
          <div className="space-y-1.5">
            {allowlist.map((e) => (
              <div key={e.id} className="flex items-center justify-between text-xs border-t border-brand-border pt-1.5 first:border-t-0 first:pt-0">
                <span><span className="font-mono">{e.cidr}</span>{e.label && <span className="text-gray-400"> — {e.label}</span>}</span>
                <button onClick={() => removeIp(e.id, e.cidr)} className="text-brand-red transition-colors hover:text-red-800"><Trash2 size={12} /></button>
              </div>
            ))}
            {allowlist.length === 0 && <p className="text-xs text-gray-400">No entries yet.</p>}
          </div>
        </div>
      )}

      {showReset && (
        <Modal title="Re-enroll Authenticator App" onClose={() => setShowReset(false)}>
          <form onSubmit={submitReset} className="space-y-3">
            <p className="text-xs text-gray-600">
              This disables your current 2FA and signs you out of every device. You&apos;ll
              log in again and scan a fresh QR code, same as your very first login.
            </p>
            <div>
              <label className="text-xs font-medium text-gray-600">Confirm your password</label>
              <div className="mt-1">
                <PasswordInput required autoFocus value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" />
              </div>
            </div>
            {resetError && <p className="text-xs text-brand-red">{resetError}</p>}
            <button disabled={resetting} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
              {resetting ? 'Resetting…' : 'Reset 2FA & Sign Out'}
            </button>
          </form>
        </Modal>
      )}
    </div>
  );
}
