'use client'

import { useEffect, useState } from 'react'
import { Plus, Pencil, Loader2, X, Power } from 'lucide-react'
import toast from 'react-hot-toast'
import { ALL_ROLES, ROLE_LABELS, ROLE_COLORS } from '@/lib/superadmin-permissions'
import type { SuperAdminRole } from '@/lib/superadmin-permissions'

interface Staff {
  id: string
  name: string
  email: string
  role: string
  isActive: boolean
  createdAt: string
}

const defaultForm = {
  name: '',
  email: '',
  password: '',
  role: 'viewer' as string,
}

export default function StaffManagementPage() {
  const [staffList, setStaffList] = useState<Staff[]>([])
  const [loading, setLoading] = useState(true)
  const [showModal, setShowModal] = useState(false)
  const [editing, setEditing] = useState<Staff | null>(null)
  const [form, setForm] = useState(defaultForm)
  const [saving, setSaving] = useState(false)
  const [togglingId, setTogglingId] = useState<string | null>(null)

  const fetchStaff = async () => {
    try {
      const res = await fetch('/api/superadmin/staff')
      const data = await res.json()
      setStaffList(data.staff || [])
    } catch {
      toast.error('Gagal memuat data staff')
    } finally {
      setLoading(false)
    }
  }

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

  const openCreate = () => {
    setEditing(null)
    setForm(defaultForm)
    setShowModal(true)
  }

  const openEdit = (staff: Staff) => {
    setEditing(staff)
    setForm({
      name: staff.name,
      email: staff.email,
      password: '',
      role: staff.role,
    })
    setShowModal(true)
  }

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault()
    setSaving(true)
    try {
      if (editing) {
        const body: any = { name: form.name, email: form.email, role: form.role }
        if (form.password) body.password = form.password
        const res = await fetch(`/api/superadmin/staff/${editing.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
        })
        if (!res.ok) {
          const data = await res.json()
          throw new Error(data.error)
        }
        toast.success('Staff berhasil diupdate')
      } else {
        const res = await fetch('/api/superadmin/staff', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(form),
        })
        if (!res.ok) {
          const data = await res.json()
          throw new Error(data.error)
        }
        toast.success('Staff berhasil ditambahkan')
      }
      setShowModal(false)
      setEditing(null)
      setForm(defaultForm)
      fetchStaff()
    } catch (err: any) {
      toast.error(err.message || 'Gagal menyimpan')
    } finally {
      setSaving(false)
    }
  }

  const handleToggleActive = async (staff: Staff) => {
    const action = staff.isActive ? 'Nonaktifkan' : 'Aktifkan'
    if (!confirm(`${action} staff "${staff.name}"?`)) return

    setTogglingId(staff.id)
    try {
      if (staff.isActive) {
        // Deactivate via DELETE
        const res = await fetch(`/api/superadmin/staff/${staff.id}`, { method: 'DELETE' })
        if (!res.ok) {
          const data = await res.json()
          throw new Error(data.error)
        }
        toast.success('Staff dinonaktifkan')
      } else {
        // Reactivate via PUT
        const res = await fetch(`/api/superadmin/staff/${staff.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ isActive: true }),
        })
        if (!res.ok) {
          const data = await res.json()
          throw new Error(data.error)
        }
        toast.success('Staff diaktifkan')
      }
      fetchStaff()
    } catch (err: any) {
      toast.error(err.message || 'Gagal mengubah status')
    } finally {
      setTogglingId(null)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
      </div>
    )
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Kelola Staff</h1>
          <p className="text-gray-600 mt-1">Kelola akun staff superadmin dan hak akses mereka.</p>
        </div>
        <button onClick={openCreate} className="btn-primary text-sm flex items-center gap-1">
          <Plus className="w-4 h-4" /> Tambah Staff
        </button>
      </div>

      <div className="card">
        {staffList.length === 0 ? (
          <p className="text-gray-500 text-center py-8">Belum ada staff</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-gray-50">
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Nama</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Email</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Role</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Status</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Dibuat</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Aksi</th>
                </tr>
              </thead>
              <tbody>
                {staffList.map((staff) => {
                  const roleColor = ROLE_COLORS[staff.role as SuperAdminRole] || 'bg-gray-100 text-gray-800'
                  const roleLabel = ROLE_LABELS[staff.role as SuperAdminRole] || staff.role
                  return (
                    <tr key={staff.id} className="border-b border-gray-100 hover:bg-gray-50">
                      <td className="py-3 px-3 font-medium text-gray-900">{staff.name}</td>
                      <td className="py-3 px-3 text-gray-600">{staff.email}</td>
                      <td className="py-3 px-3">
                        <span className={`badge text-xs ${roleColor}`}>{roleLabel}</span>
                      </td>
                      <td className="py-3 px-3">
                        <span className={`badge ${staff.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                          {staff.isActive ? 'Aktif' : 'Nonaktif'}
                        </span>
                      </td>
                      <td className="py-3 px-3 text-gray-500">
                        {new Date(staff.createdAt).toLocaleDateString('id-ID', { day: 'numeric', month: 'short', year: 'numeric' })}
                      </td>
                      <td className="py-3 px-3">
                        <div className="flex items-center gap-1">
                          <button onClick={() => openEdit(staff)} className="btn-ghost text-xs p-1.5" title="Edit">
                            <Pencil className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => handleToggleActive(staff)}
                            disabled={togglingId === staff.id}
                            className={`btn-ghost text-xs p-1.5 ${staff.isActive ? 'text-red-500 hover:bg-red-50' : 'text-green-600 hover:bg-green-50'}`}
                            title={staff.isActive ? 'Nonaktifkan' : 'Aktifkan'}
                          >
                            {togglingId === staff.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Power className="w-4 h-4" />}
                          </button>
                        </div>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Create/Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white rounded-xl w-full max-w-md p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold">{editing ? 'Edit Staff' : 'Tambah Staff'}</h3>
              <button onClick={() => setShowModal(false)}>
                <X className="w-5 h-5 text-gray-400" />
              </button>
            </div>
            <form onSubmit={handleSave} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Nama</label>
                <input
                  type="text"
                  className="input-field"
                  value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })}
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                <input
                  type="email"
                  className="input-field"
                  value={form.email}
                  onChange={(e) => setForm({ ...form, email: e.target.value })}
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Password {editing && <span className="text-gray-400 font-normal">(kosongkan jika tidak diubah)</span>}
                </label>
                <input
                  type="password"
                  className="input-field"
                  value={form.password}
                  onChange={(e) => setForm({ ...form, password: e.target.value })}
                  minLength={editing ? 0 : 8}
                  required={!editing}
                  placeholder={editing ? '••••••••' : 'Minimal 8 karakter'}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Role</label>
                <select
                  className="input-field"
                  value={form.role}
                  onChange={(e) => setForm({ ...form, role: e.target.value })}
                  required
                >
                  {ALL_ROLES.map((role) => (
                    <option key={role} value={role}>
                      {ROLE_LABELS[role]}
                    </option>
                  ))}
                </select>
              </div>
              <div className="flex gap-2 justify-end pt-2">
                <button type="button" onClick={() => setShowModal(false)} className="btn-secondary">
                  Batal
                </button>
                <button type="submit" disabled={saving} className="btn-primary flex items-center gap-2">
                  {saving && <Loader2 className="w-4 h-4 animate-spin" />}
                  {saving ? 'Menyimpan...' : 'Simpan'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}
