"use client"

import { useState, Fragment } from "react"
import { useLocale, useTranslations } from "next-intl"

import { Badge } from "@/shared/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { Button } from "@/shared/components/ui/button"
import { EmptyTableRow } from "@/shared/components/ui/empty-table-row"
import { Pagination } from "@/shared/components/ui/pagination"
import { StatusBadge } from "@/shared/components/ui/status-badge"
import { formatDate } from "@/shared/lib/utils"
import type { DataChangeLog } from "../types"
import {
  DATA_CHANGE_ACTION_VARIANT,
  DATA_CHANGE_ACTION_CLASS_NAME,
} from "../types"
import { AuditLogDetailDialog } from "./audit-log-detail-dialog"

interface DataChangeLogTableProps {
  items: DataChangeLog[]
  page: number
  pageSize: number
  total: number
  totalPages: number
  onPageChange: (page: number) => void
}

export function DataChangeLogTable({
  items,
  page,
  pageSize,
  total,
  totalPages,
  onPageChange,
}: DataChangeLogTableProps) {
  const t = useTranslations("audit")
  const locale = useLocale()
  const [expandedId, setExpandedId] = useState<string | null>(null)

  return (
    <div className="space-y-4">
      <div className="rounded-md border">
        <Table aria-label={t("dataChanges.title")}>
          <TableHeader className="bg-muted/40">
            <TableRow>
              <TableHead>{t("table.tableName")}</TableHead>
              <TableHead>{t("table.recordId")}</TableHead>
              <TableHead>{t("table.action")}</TableHead>
              <TableHead>{t("table.changedBy")}</TableHead>
              <TableHead>{t("table.ipAddress")}</TableHead>
              <TableHead>{t("table.time")}</TableHead>
              <TableHead className="w-24" />
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.length === 0 ? (
              <EmptyTableRow colSpan={7} message={t("empty.dataChange")} />
            ) : (
              items.map((log) => (
                <Fragment key={log.id}>
                  <TableRow>
                    <TableCell>
                      <Badge variant="outline" className="font-mono text-xs">
                        {log.tableName}
                      </Badge>
                    </TableCell>
                    <TableCell className="font-mono text-xs">{log.recordId}</TableCell>
                    <TableCell>
                      <StatusBadge
                        status={log.action}
                        variantMap={DATA_CHANGE_ACTION_VARIANT}
                        classNameMap={DATA_CHANGE_ACTION_CLASS_NAME}
                      />
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col">
                        <span className="font-medium">{log.changedByName}</span>
                        <span className="text-xs text-muted-foreground">{log.changedBy}</span>
                      </div>
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground font-mono">
                      {log.ipAddress ?? "-"}
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      {formatDate(log.createdAt, locale)}
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          aria-expanded={expandedId === log.id}
                          aria-label={expandedId === log.id ? t("table.hide") : t("table.view")}
                          onClick={() => setExpandedId(expandedId === log.id ? null : log.id)}
                        >
                          {expandedId === log.id ? t("table.hide") : t("table.view")}
                        </Button>
                        <AuditLogDetailDialog type="dataChange" item={log} />
                      </div>
                    </TableCell>
                  </TableRow>
                  {expandedId === log.id && (
                    <TableRow>
                      <TableCell colSpan={7} className="bg-muted/30">
                        <div className="grid gap-4 md:grid-cols-2">
                          <div>
                            <div className="mb-1 text-xs font-semibold text-muted-foreground">
                              {t("table.oldValue")}
                            </div>
                            <pre className="max-h-60 overflow-auto rounded border bg-background p-2 text-xs">
                              {log.oldValue ?? "—"}
                            </pre>
                          </div>
                          <div>
                            <div className="mb-1 text-xs font-semibold text-muted-foreground">
                              {t("table.newValue")}
                            </div>
                            <pre className="max-h-60 overflow-auto rounded border bg-background p-2 text-xs">
                              {log.newValue ?? "—"}
                            </pre>
                          </div>
                        </div>
                      </TableCell>
                    </TableRow>
                  )}
                </Fragment>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <Pagination
        page={page}
        pageSize={pageSize}
        total={total}
        totalPages={totalPages}
        onPageChange={onPageChange}
      />
    </div>
  )
}
