'use client'

import { useEffect, useState } from 'react'
import { Plus, Power, Key } from 'lucide-react'

interface Admin {
  id: string
  email: string
  name: string
  is_active: boolean
  last_login_at: string | null
  created_at: string
}

export default function AdminsPage() {
  const [admins, setAdmins] = useState<Admin[]>([])
  const [loading, setLoading] = useState(true)
  const [showAdd, setShowAdd] = useState(false)
  const [newEmail, setNewEmail] = useState('')
  const [newName, setNewName] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [error, setError] = useState('')
  const [busy, setBusy] = useState(false)
  const [toast, setToast] = useState<string | null>(null)
  const [resetId, setResetId] = useState<string | null>(null)
  const [resetPassword, setResetPassword] = useState('')

  function flashToast(msg: string) {
    setToast(msg)
    setTimeout(() => setToast(null), 3000)
  }

  async function load() {
    setLoading(true)
    const res = await fetch('/api/admin/admins')
    if (res.ok) {
      const d = await res.json()
      setAdmins(d.admins || [])
    }
    setLoading(false)
  }

  useEffect(() => { load() }, [])

  async function createAdmin(e: React.FormEvent) {
    e.preventDefault()
    setError('')
    setBusy(true)
    const res = await fetch('/api/admin/admins', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: newEmail, name: newName, password: newPassword }),
    })
    setBusy(false)
    if (res.ok) {
      setShowAdd(false)
      setNewEmail(''); setNewName(''); setNewPassword('')
      flashToast('Admin created')
      load()
    } else {
      const d = await res.json().catch(() => ({}))
      setError(d.error || 'Create failed')
    }
  }

  async function toggleActive(a: Admin) {
    if (!confirm(`${a.is_active ? 'Deactivate' : 'Activate'} ${a.email}?`)) return
    setBusy(true)
    const res = await fetch(`/api/admin/admins/${a.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ is_active: !a.is_active }),
    })
    setBusy(false)
    if (res.ok) {
      flashToast(a.is_active ? 'Deactivated' : 'Activated')
      load()
    } else {
      flashToast('Update failed')
    }
  }

  async function submitResetPassword(e: React.FormEvent) {
    e.preventDefault()
    if (!resetId) return
    setBusy(true)
    const res = await fetch(`/api/admin/admins/${resetId}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ password: resetPassword }),
    })
    setBusy(false)
    if (res.ok) {
      flashToast('Password reset')
      setResetId(null)
      setResetPassword('')
    } else {
      const d = await res.json().catch(() => ({}))
      flashToast(d.error || 'Reset failed')
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold text-white">Admins</h1>
          <p className="text-sm text-white/50 mt-1">{admins.length} total</p>
        </div>
        <button
          onClick={() => setShowAdd(s => !s)}
          className="bg-gradient-to-r from-indigo-500 to-purple-600 hover:from-indigo-600 hover:to-purple-700 text-white text-sm font-medium px-4 py-2 rounded-lg shadow-lg shadow-indigo-500/20 flex items-center gap-2"
        >
          <Plus className="w-4 h-4" /> Add admin
        </button>
      </div>

      {showAdd && (
        <form onSubmit={createAdmin} className="bg-white/[0.04] border border-white/[0.08] rounded-2xl p-5 space-y-3">
          <div className="grid md:grid-cols-3 gap-3">
            <input
              type="email"
              value={newEmail}
              onChange={e => setNewEmail(e.target.value)}
              required
              placeholder="email@breakpilot.ai"
              className="bg-black/30 border border-white/10 rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
            />
            <input
              type="text"
              value={newName}
              onChange={e => setNewName(e.target.value)}
              required
              placeholder="Name"
              className="bg-black/30 border border-white/10 rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
            />
            <input
              type="password"
              value={newPassword}
              onChange={e => setNewPassword(e.target.value)}
              required
              minLength={12}
              placeholder="Password (min 12 chars)"
              className="bg-black/30 border border-white/10 rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
            />
          </div>
          {error && (
            <div className="text-sm text-rose-300 bg-rose-500/10 border border-rose-500/20 rounded-lg px-3 py-2">{error}</div>
          )}
          <div className="flex justify-end gap-2">
            <button type="button" onClick={() => { setShowAdd(false); setError('') }} className="text-sm text-white/60 hover:text-white px-4 py-2">Cancel</button>
            <button type="submit" disabled={busy} className="bg-indigo-500 hover:bg-indigo-600 text-white text-sm font-medium px-4 py-2 rounded-lg disabled:opacity-50">
              {busy ? 'Creating…' : 'Create'}
            </button>
          </div>
        </form>
      )}

      {loading ? (
        <div className="flex items-center justify-center h-32"><div className="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" /></div>
      ) : (
        <div className="bg-white/[0.04] border border-white/[0.06] rounded-2xl overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-xs uppercase tracking-wider text-white/40 border-b border-white/[0.06]">
                <th className="py-3 px-4 font-medium">Admin</th>
                <th className="py-3 px-4 font-medium">Status</th>
                <th className="py-3 px-4 font-medium">Last login</th>
                <th className="py-3 px-4 font-medium">Created</th>
                <th className="py-3 px-4 font-medium text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {admins.map(a => (
                <tr key={a.id} className="border-b border-white/[0.04]">
                  <td className="py-3 px-4">
                    <div className="text-white/90 font-medium">{a.name}</div>
                    <div className="text-xs text-white/40">{a.email}</div>
                  </td>
                  <td className="py-3 px-4">
                    <span className={`text-[10px] px-2 py-0.5 rounded-full border uppercase font-semibold ${
                      a.is_active
                        ? 'bg-green-500/15 text-green-300 border-green-500/30'
                        : 'bg-rose-500/15 text-rose-300 border-rose-500/30'
                    }`}>
                      {a.is_active ? 'Active' : 'Disabled'}
                    </span>
                  </td>
                  <td className="py-3 px-4 text-white/60 text-xs">
                    {a.last_login_at ? new Date(a.last_login_at).toLocaleString() : '—'}
                  </td>
                  <td className="py-3 px-4 text-white/60 text-xs">
                    {new Date(a.created_at).toLocaleDateString()}
                  </td>
                  <td className="py-3 px-4">
                    <div className="flex items-center justify-end gap-1">
                      <button
                        onClick={() => { setResetId(a.id); setResetPassword('') }}
                        className="w-8 h-8 rounded-lg flex items-center justify-center text-white/50 hover:bg-amber-500/15 hover:text-amber-300"
                        title="Reset password"
                      >
                        <Key className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => toggleActive(a)}
                        className="w-8 h-8 rounded-lg flex items-center justify-center text-white/50 hover:bg-rose-500/15 hover:text-rose-300"
                        title={a.is_active ? 'Deactivate' : 'Activate'}
                      >
                        <Power className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Reset password modal */}
      {resetId && (
        <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4" onClick={() => setResetId(null)}>
          <form
            onSubmit={submitResetPassword}
            onClick={e => e.stopPropagation()}
            className="bg-[#0a0a1a] border border-white/[0.1] rounded-2xl p-6 w-full max-w-sm space-y-4"
          >
            <h3 className="text-lg font-semibold text-white">Reset Password</h3>
            <p className="text-sm text-white/60">
              The admin's active sessions will be revoked.
            </p>
            <input
              type="password"
              value={resetPassword}
              onChange={e => setResetPassword(e.target.value)}
              required
              minLength={12}
              autoFocus
              placeholder="New password (min 12 chars)"
              className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
            />
            <div className="flex justify-end gap-2">
              <button type="button" onClick={() => setResetId(null)} className="text-sm text-white/60 hover:text-white px-4 py-2">Cancel</button>
              <button type="submit" disabled={busy} className="bg-indigo-500 hover:bg-indigo-600 text-white text-sm font-medium px-4 py-2 rounded-lg disabled:opacity-50">
                {busy ? 'Saving…' : 'Reset'}
              </button>
            </div>
          </form>
        </div>
      )}

      {toast && (
        <div className="fixed bottom-6 right-6 bg-indigo-500/20 border border-indigo-500/40 text-indigo-200 text-sm px-4 py-2 rounded-lg backdrop-blur-sm">
          {toast}
        </div>
      )}
    </div>
  )
}
