'use client'

import { useEffect, useState } from 'react'
import { Plus, Pencil, Trash2, Search, Loader2, X, UserCircle } from 'lucide-react'
import { getInitials } from '@/lib/utils'
import toast from 'react-hot-toast'
import Pagination, { PaginationData } from '@/components/Pagination'

const ROLES = [
  { value: 'admin', label: 'Admin' },
  { value: 'manager', label: 'Manager' },
  { value: 'finance', label: 'Finance' },
  { value: 'cashier', label: 'Kasir' },
  { value: 'waiter', label: 'Pelayan' },
  { value: 'chef', label: 'Koki' },
  { value: 'staff', label: 'Staff' },
]

export default function StaffPage() {
  const [staff, setStaff] = useState<any[]>([])
  const [stores, setStores] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [showModal, setShowModal] = useState(false)
  const [editing, setEditing] = useState<any>(null)
  const [form, setForm] = useState({ name: '', email: '', password: '', role: 'staff', phone: '', storeId: '' })
  const [saving, setSaving] = useState(false)
  const [pagination, setPagination] = useState<PaginationData>({ page: 1, limit: 20, total: 0, totalPages: 0 })

  const fetchStaff = async (page = 1) => {
    const params = new URLSearchParams()
    params.set('page', String(page))
    if (search) params.set('search', search)
    const staffRes = await fetch(`/api/staff?${params}`).then(r => r.json())
    setStaff(staffRes.staff || [])
    if (staffRes.pagination) setPagination(staffRes.pagination)
  }

  const fetchData = async () => {
    const [, storesRes] = await Promise.all([
      fetchStaff(1),
      fetch('/api/stores').then(r => r.json()),
    ])
    setStores(storesRes.stores || [])
    setLoading(false)
  }

  useEffect(() => { fetchData() }, [])
  useEffect(() => { fetchStaff(1) }, [search])

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

  const handleDelete = async (id: string) => {
    if (!confirm('Nonaktifkan staff ini?')) return
    await fetch(`/api/staff/${id}`, { method: 'DELETE' })
    toast.success('Staff dinonaktifkan')
    fetchData()
  }

  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-primary-600"></div></div>

  return (
    <div>
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Manajemen Staff</h1>
          <p className="text-gray-600 dark:text-gray-300 mt-1">Kelola karyawan dan hak akses mereka.</p>
        </div>
        <button onClick={() => { setForm({ name: '', email: '', password: '', role: 'staff', phone: '', storeId: '' }); setEditing(null); setShowModal(true) }} className="btn-primary text-sm">
          <Plus className="w-4 h-4 inline mr-1" /> Tambah Staff
        </button>
      </div>

      <div className="relative mb-4">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 dark:text-gray-500" />
        <input type="text" placeholder="Cari staff..." className="input-field pl-10" value={search} onChange={(e) => setSearch(e.target.value)} />
      </div>

      <div className="card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/50">
                <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300">Staff</th>
                <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300">Email</th>
                <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300">Role</th>
                <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300">Cabang</th>
                <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300">Status</th>
                <th className="text-right py-3 px-4 font-medium text-gray-600 dark:text-gray-300">Aksi</th>
              </tr>
            </thead>
            <tbody>
              {staff.map(s => (
                <tr key={s.id} className="border-b border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800">
                  <td className="py-3 px-4">
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 bg-primary-100 dark:bg-primary-900/30 rounded-full flex items-center justify-center text-primary-700 dark:text-primary-300 font-medium text-xs">
                        {getInitials(s.name)}
                      </div>
                      <div>
                        <p className="font-medium text-gray-900 dark:text-white">{s.name}</p>
                        {s.phone && <p className="text-xs text-gray-500 dark:text-gray-400">{s.phone}</p>}
                      </div>
                    </div>
                  </td>
                  <td className="py-3 px-4 text-gray-600 dark:text-gray-300">{s.email}</td>
                  <td className="py-3 px-4"><span className="badge bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 capitalize">{s.role}</span></td>
                  <td className="py-3 px-4 text-gray-600 dark:text-gray-300">{s.store?.name || 'Semua'}</td>
                  <td className="py-3 px-4">
                    <span className={`badge ${s.isActive ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300' : 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300'}`}>
                      {s.isActive ? 'Aktif' : 'Nonaktif'}
                    </span>
                  </td>
                  <td className="py-3 px-4 text-right">
                    <div className="flex items-center justify-end gap-1">
                      <button onClick={() => { setEditing(s); setForm({ name: s.name, email: s.email, password: '', role: s.role, phone: s.phone || '', storeId: s.storeId || '' }); setShowModal(true) }} className="btn-ghost p-1.5"><Pencil className="w-4 h-4" /></button>
                      <button onClick={() => handleDelete(s.id)} className="btn-ghost p-1.5 text-red-500 hover:bg-red-50 dark:hover:bg-red-900/30"><Trash2 className="w-4 h-4" /></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      <Pagination pagination={pagination} onPageChange={(page) => fetchStaff(page)} itemLabel="staff" />
      {staff.length === 0 && <p className="text-center text-gray-500 dark:text-gray-400 py-12">Tidak ada staff ditemukan.</p>}

      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl w-full max-w-md p-6 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold dark:text-white">{editing ? 'Edit Staff' : 'Tambah Staff'}</h3>
              <button onClick={() => setShowModal(false)}><X className="w-5 h-5 text-gray-400 dark:text-gray-500" /></button>
            </div>
            <form onSubmit={handleSave} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 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 dark:text-gray-200 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 dark:text-gray-200 mb-1">Password {editing && '(kosongkan jika tidak diubah)'}</label>
                <input type="password" className="input-field" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} {...(!editing ? { required: true } : {})} />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Role</label>
                <select className="input-field dark:bg-gray-800 dark:border-gray-600 dark:text-white" value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })}>
                  {ROLES.map(r => <option key={r.value} value={r.value}>{r.label}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Telepon</label>
                <input type="text" className="input-field" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Cabang</label>
                <select className="input-field dark:bg-gray-800 dark:border-gray-600 dark:text-white" value={form.storeId} onChange={(e) => setForm({ ...form, storeId: e.target.value })}>
                  <option value="">Semua Cabang</option>
                  {stores.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                </select>
              </div>
              <div className="flex gap-2 justify-end">
                <button type="button" onClick={() => setShowModal(false)} className="btn-secondary">Batal</button>
                <button type="submit" disabled={saving} className="btn-primary">{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Simpan'}</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}
