'use client'

import { useEffect, useState } from "react"
import { PageHeader } from "@/components/ui/page-header"
import { KpiCard } from "@/components/ui/kpi-card"
import { SectionCard } from "@/components/ui/section-card"
import { DataTable, type Column } from "@/components/ui/data-table"
import { StatusBadge, type StatusTone } from "@/components/ui/status-badge"
import { ScrollText, Shield, UserCog, Activity } from "lucide-react"
import { formatDateTime } from "@/lib/format"
import { useAuditLogs } from "@/hooks/useAuditLogs"
import { FilterToolbar } from "@/components/ui/filter-toolbar"
import i18n from "@/lib/i18n";

type AuditRow = {
  id: string
  actor: string
  actor_role: string | null
  action: string
  resource: string | null
  severity: string
  ip_address: string | null
  user_agent: string | null
  result: string
  created_at: string
}

const sevTone: Record<string, StatusTone> = { info: "info", warning: "warning", critical: "danger" }
const sevLabel: Record<string, string> = { info: i18n.t('app.admin.audit-logs.page.text_1'), warning: i18n.t('app.admin.audit-logs.page.text_2'), critical: i18n.t('app.admin.audit-logs.page.text_3') }
const resultTone: Record<string, StatusTone> = { success: "success", denied: "danger", failed: "danger" }
const resultLabel: Record<string, string> = { success: i18n.t('app.admin.audit-logs.page.text_4'), denied: i18n.t('app.admin.audit-logs.page.text_5'), failed: i18n.t('app.admin.audit-logs.page.text_6') }

export default function AuditLogsPage() {
  const { 
    items, 
    isLoading: loading,
    error, 
    fetchItems, 
    currentPage, 
    pageSize, 
    totalPages, 
    totalCount, 
    setCurrentPage 
  } = useAuditLogs()

  const [rows, setRows] = useState<AuditRow[]>([])
  const [criticalCount, setCriticalCount] = useState(0)
  const [deniedCount, setDeniedCount] = useState(0)
  const [adminCount, setAdminCount] = useState(0)

  const [searchQuery, setSearchQuery] = useState("")
  const [actionFilter, setActionFilter] = useState("")
  const [fromDate, setFromDate] = useState("")
  const [toDate, setToDate] = useState("")

  useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
      fetchItems(currentPage, pageSize, searchQuery, {
        action: actionFilter || undefined,
        from_date: fromDate ? new Date(fromDate).toISOString() : undefined,
        to_date: toDate ? new Date(toDate).toISOString() : undefined,
      })
    }, 500)
    return () => clearTimeout(delayDebounceFn)
  }, [fetchItems, currentPage, pageSize, searchQuery, actionFilter, fromDate, toDate])

  useEffect(() => {
    if (items && items.length > 0) {
      const data = items.map((log: any) => ({
        id: log.id,
        actor: log.actor_user_id || i18n.t('app.admin.audit-logs.page.text_7'),
        actor_role: null,
        action: log.action,
        resource: log.entity_type,
        severity: log.action.includes("block") || log.action.includes("suspend") || log.action.includes("delete") ? "critical" : "info",
        ip_address: null,
        user_agent: null,
        result: "success",
        created_at: log.created_at,
      }))
      setRows(data)
      setCriticalCount(data.filter((r: any) => r.severity === "critical").length)
      setAdminCount(data.length)
    } else if (!loading) {
      setRows([])
      setCriticalCount(0)
      setDeniedCount(0)
      setAdminCount(0)
    }
  }, [items, loading])

  const columns: Column<AuditRow>[] = [
    { key: "time", header: i18n.t('app.admin.audit-logs.page.text_8'), cell: (r) => <span className="font-mono text-[11.5px] text-muted-foreground">{formatDateTime(r.created_at)}</span> },
    { key: "actor", header: i18n.t('app.admin.audit-logs.page.text_9'), cell: (r) => <div><p className="text-[12.5px] font-medium max-w-[80px] truncate" title={r.actor}>{r.actor}</p><p className="text-[10.5px] text-muted-foreground">{r.actor_role ?? "—"}</p></div> },
    { key: "action", header: i18n.t('app.admin.audit-logs.page.text_10'), cell: (r) => <span className="font-mono text-[12px]">{r.action}</span> },
    { key: "resource", header: i18n.t('app.admin.audit-logs.page.text_11'), cell: (r) => <span className="text-[12px] text-muted-foreground">{r.resource ?? "—"}</span> },
    { key: "ip", header: "IP", cell: (r) => <span className="font-mono text-[11.5px] text-muted-foreground">{r.ip_address ?? "—"}</span> },
    { key: "severity", header: i18n.t('app.admin.audit-logs.page.text_12'), cell: (r) => <StatusBadge tone={sevTone[r.severity] ?? "neutral"} size="sm">{sevLabel[r.severity] ?? r.severity}</StatusBadge> },
    { key: "result", header: i18n.t('app.admin.audit-logs.page.text_13'), cell: (r) => <StatusBadge tone={resultTone[r.result] ?? "neutral"} size="sm">{resultLabel[r.result] ?? r.result}</StatusBadge> },
  ]

  return (
    <div className="space-y-6">
      <PageHeader
        title={i18n.t('app.admin.audit-logs.page.text_14')}
        description={i18n.t('app.admin.audit-logs.page.text_15')}
        breadcrumbs={[{ label: i18n.t('app.admin.audit-logs.page.text_16'), href: "#" }, { label: i18n.t('app.admin.audit-logs.page.text_17') }]}
      />

      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <KpiCard label={i18n.t('app.admin.audit-logs.page.text_18')} value={String(totalCount)} icon={ScrollText} tone="gold" accent />
        <KpiCard label={i18n.t('app.admin.audit-logs.page.text_19')} value={String(criticalCount)} icon={Shield} tone="danger" />
        <KpiCard label={i18n.t('app.admin.audit-logs.page.text_20')} value={String(deniedCount)} icon={Activity} tone="warning" />
        <KpiCard label={i18n.t('app.admin.audit-logs.page.text_21')} value={String(adminCount)} icon={UserCog} tone="info" />
      </div>

      <FilterToolbar
        searchValue={searchQuery}
        onSearchChange={setSearchQuery}
        searchPlaceholder={i18n.t('app.admin.audit-logs.page.text_22')}
        showDate={false}
        showFilterIcon={false}
        customFilters={
          <div className="flex gap-2">
            <select
              value={actionFilter}
              onChange={(e) => setActionFilter(e.target.value)}
              className="h-9 px-3 rounded-md border border-border bg-card text-[12.5px] focus:outline-none focus:border-gold-400 text-foreground transition"
            >
              <option value="">{i18n.t('app.admin.audit-logs.page.text_26')}</option>
              <option value="create">{i18n.t('app.admin.audit-logs.page.text_27')}</option>
              <option value="update">{i18n.t('app.admin.audit-logs.page.text_28')}</option>
              <option value="delete">{i18n.t('app.admin.audit-logs.page.text_29')}</option>
              <option value="login">{i18n.t('app.admin.audit-logs.page.text_30')}</option>
              <option value="logout">{i18n.t('app.admin.audit-logs.page.text_31')}</option>
              <option value="deposit">{i18n.t('app.admin.audit-logs.page.text_32')}</option>
              <option value="withdraw">{i18n.t('app.admin.audit-logs.page.text_33')}</option>
            </select>
            <input
              type="date"
              value={fromDate}
              onChange={(e) => setFromDate(e.target.value)}
              className="h-9 px-3 rounded-md border border-border bg-card text-[12.5px] focus:outline-none focus:border-gold-400 text-foreground transition"
              title={i18n.t('app.admin.audit-logs.page.text_23')}
            />
            <input
              type="date"
              value={toDate}
              onChange={(e) => setToDate(e.target.value)}
              className="h-9 px-3 rounded-md border border-border bg-card text-[12.5px] focus:outline-none focus:border-gold-400 text-foreground transition"
              title={i18n.t('app.admin.audit-logs.page.text_24')}
            />
          </div>
        }
      />

      <SectionCard title={i18n.t('app.admin.audit-logs.page.text_25')} padded={false}>
        {rows.length === 0 ? (
          <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.audit-logs.page.text_34')}</div>
        ) : (
          <>
            <DataTable columns={columns} data={rows} rowKey={(r) => r.id} compact />
            {totalPages > 1 && (
              <div className="px-5 py-3 border-t border-border flex items-center justify-between text-[12.5px]">
                <div className="text-muted-foreground">
                  {i18n.t('app.admin.audit-logs.page.text_35')}{totalCount} {i18n.t('app.admin.audit-logs.page.text_36')}</div>
                <div className="flex gap-2">
                  <button
                    disabled={currentPage <= 1}
                    onClick={() => {
                      setCurrentPage(currentPage - 1)
                      fetchItems(currentPage - 1, pageSize)
                    }}
                    className="px-3 py-1 bg-muted hover:bg-muted/80 rounded-md disabled:opacity-50 transition-colors"
                  >
                    {i18n.t('app.admin.audit-logs.page.text_37')}</button>
                  <span className="py-1 px-2 font-medium">{i18n.t('app.admin.audit-logs.page.text_38')}{currentPage} {i18n.t('app.admin.audit-logs.page.text_39')}{totalPages}</span>
                  <button
                    disabled={currentPage >= totalPages}
                    onClick={() => {
                      setCurrentPage(currentPage + 1)
                      fetchItems(currentPage + 1, pageSize)
                    }}
                    className="px-3 py-1 bg-muted hover:bg-muted/80 rounded-md disabled:opacity-50 transition-colors"
                  >
                    {i18n.t('app.admin.audit-logs.page.text_40')}</button>
                </div>
              </div>
            )}
          </>
        )}
      </SectionCard>
    </div>
  )
}
