'use client'

import { useEffect, useState } from 'react'
import { ClipboardList, Filter, ChevronDown, ChevronUp } from 'lucide-react'
import Pagination, { PaginationData } from '@/components/Pagination'

const ACTION_LABELS: Record<string, { label: string; color: string }> = {
  CREATE: { label: 'Tambah', color: 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300' },
  UPDATE: { label: 'Ubah', color: 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300' },
  DELETE: { label: 'Hapus', color: 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300' },
  SETTINGS_CHANGE: { label: 'Pengaturan', color: 'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300' },
  LOGIN: { label: 'Login', color: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300' },
}

const ENTITY_OPTIONS = ['Menu', 'Order', 'Category', 'Settings', 'Staff', 'Store']

const ROLE_LABELS: Record<string, string> = {
  owner: 'Owner',
  admin: 'Admin',
  manager: 'Manager',
  staff: 'Staff',
  cashier: 'Kasir',
  waiter: 'Waiter',
  chef: 'Chef',
}

function timeAgo(dateStr: string): string {
  const now = new Date()
  const date = new Date(dateStr)
  const diff = Math.floor((now.getTime() - date.getTime()) / 1000)

  if (diff < 60) return 'Baru saja'
  if (diff < 3600) return `${Math.floor(diff / 60)} menit lalu`
  if (diff < 86400) return `${Math.floor(diff / 3600)} jam lalu`
  if (diff < 604800) return `${Math.floor(diff / 86400)} hari lalu`

  return date.toLocaleDateString('id-ID', { day: 'numeric', month: 'short', year: 'numeric' })
}

export default function AuditLogPage() {
  const [logs, setLogs] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [pagination, setPagination] = useState<PaginationData>({ page: 1, limit: 25, total: 0, totalPages: 0 })
  const [entity, setEntity] = useState('')
  const [action, setAction] = useState('')
  const [startDate, setStartDate] = useState('')
  const [endDate, setEndDate] = useState('')
  const [expandedId, setExpandedId] = useState<string | null>(null)

  const fetchLogs = async (page = 1) => {
    setLoading(true)
    try {
      const params = new URLSearchParams()
      params.set('page', String(page))
      params.set('limit', '25')
      if (entity) params.set('entity', entity)
      if (action) params.set('action', action)
      if (startDate) params.set('startDate', startDate)
      if (endDate) params.set('endDate', endDate)

      const res = await fetch(`/api/audit-logs?${params}`)
      const data = await res.json()
      setLogs(data.logs || [])
      if (data.pagination) setPagination(data.pagination)
    } catch {
      setLogs([])
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { fetchLogs(1) }, [entity, action, startDate, endDate])

  const handleReset = () => {
    setEntity('')
    setAction('')
    setStartDate('')
    setEndDate('')
  }

  return (
    <div>
      <div className="mb-6">
        <div className="flex items-center gap-3">
          <ClipboardList className="w-7 h-7 text-primary-600" />
          <div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Audit Log</h1>
            <p className="text-gray-600 dark:text-gray-300 mt-0.5">Catatan aktivitas pengguna di sistem</p>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="card mb-6">
        <div className="flex items-center gap-2 mb-3">
          <Filter className="w-4 h-4 text-gray-500" />
          <span className="text-sm font-medium text-gray-700 dark:text-gray-200">Filter</span>
        </div>
        <div className="flex flex-wrap gap-3">
          <select
            className="input-field text-sm w-auto min-w-[140px] dark:bg-gray-800 dark:border-gray-600 dark:text-white"
            value={entity}
            onChange={(e) => setEntity(e.target.value)}
          >
            <option value="">Semua Entitas</option>
            {ENTITY_OPTIONS.map(e => <option key={e} value={e}>{e}</option>)}
          </select>
          <select
            className="input-field text-sm w-auto min-w-[140px] dark:bg-gray-800 dark:border-gray-600 dark:text-white"
            value={action}
            onChange={(e) => setAction(e.target.value)}
          >
            <option value="">Semua Aksi</option>
            {Object.entries(ACTION_LABELS).map(([key, val]) => (
              <option key={key} value={key}>{val.label}</option>
            ))}
          </select>
          <input
            type="date"
            className="input-field text-sm w-auto dark:bg-gray-800 dark:border-gray-600 dark:text-white"
            value={startDate}
            onChange={(e) => setStartDate(e.target.value)}
            placeholder="Dari tanggal"
          />
          <input
            type="date"
            className="input-field text-sm w-auto dark:bg-gray-800 dark:border-gray-600 dark:text-white"
            value={endDate}
            onChange={(e) => setEndDate(e.target.value)}
            placeholder="Sampai tanggal"
          />
          {(entity || action || startDate || endDate) && (
            <button onClick={handleReset} className="btn-secondary text-sm">Reset</button>
          )}
        </div>
      </div>

      {/* Table */}
      <div className="card overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center py-16">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
          </div>
        ) : logs.length === 0 ? (
          <div className="text-center py-16">
            <ClipboardList className="w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-3" />
            <p className="text-gray-500 dark:text-gray-400">Belum ada aktivitas tercatat</p>
          </div>
        ) : (
          <>
            <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 w-40">Waktu</th>
                    <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300 w-40">Pengguna</th>
                    <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300 w-28">Aksi</th>
                    <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300 w-28">Entitas</th>
                    <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300">Deskripsi</th>
                    <th className="w-10"></th>
                  </tr>
                </thead>
                <tbody>
                  {logs.map((log: any) => {
                    const actionInfo = ACTION_LABELS[log.action] || { label: log.action, color: 'bg-gray-100 text-gray-600' }
                    const isExpanded = expandedId === log.id
                    let metaObj: any = null
                    if (log.meta) {
                      try { metaObj = JSON.parse(log.meta) } catch {}
                    }

                    return (
                      <tr key={log.id} className="border-b border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800/50 cursor-pointer" onClick={() => setExpandedId(isExpanded ? null : log.id)}>
                        <td className="py-3 px-4">
                          <span className="text-gray-900 dark:text-white text-xs">{timeAgo(log.createdAt)}</span>
                          <br />
                          <span className="text-xs text-gray-400 dark:text-gray-500">{new Date(log.createdAt).toLocaleString('id-ID', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })}</span>
                        </td>
                        <td className="py-3 px-4">
                          <span className="text-gray-900 dark:text-white">{log.userName || '-'}</span>
                          {log.userRole && (
                            <span className="ml-1.5 text-xs text-gray-500 dark:text-gray-400">({ROLE_LABELS[log.userRole] || log.userRole})</span>
                          )}
                        </td>
                        <td className="py-3 px-4">
                          <span className={`inline-block px-2 py-0.5 rounded-full text-xs font-medium ${actionInfo.color}`}>
                            {actionInfo.label}
                          </span>
                        </td>
                        <td className="py-3 px-4">
                          <span className="text-gray-700 dark:text-gray-300">{log.entity}</span>
                        </td>
                        <td className="py-3 px-4">
                          <span className="text-gray-600 dark:text-gray-300">{log.description}</span>
                          {isExpanded && metaObj && (
                            <div className="mt-2 p-2 bg-gray-50 dark:bg-gray-900 rounded text-xs font-mono text-gray-600 dark:text-gray-400 max-h-40 overflow-auto whitespace-pre-wrap" onClick={(e) => e.stopPropagation()}>
                              {JSON.stringify(metaObj, null, 2)}
                            </div>
                          )}
                        </td>
                        <td className="py-3 px-4 text-gray-400">
                          {metaObj && (isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />)}
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
            <Pagination pagination={pagination} onPageChange={(page) => fetchLogs(page)} itemLabel="log" />
          </>
        )}
      </div>
    </div>
  )
}
