"use client";
// src/app/audit-logs/page.tsx
import { useState, useEffect, useCallback, useMemo } from "react";
import { ColumnDef } from "@tanstack/react-table";
import { AppShell } from "@/components/layout/AppShell";
import { DataTable } from "@/components/datatable/DataTable";
import { PageHeader, Select, Input } from "@/components/ui/index";
import { formatDateTime } from "@/lib/utils";
import { Shield } from "lucide-react";
import { useLanguage } from "@/i18n/LanguageContext";
import type { TranslationKey } from "@/i18n/translations";

const AUDIT_ACTION_TO_KEY: Partial<Record<string, TranslationKey>> = {
  CREATE: "auditLog.actionCreate",
  UPDATE: "auditLog.actionUpdate",
  DELETE: "auditLog.actionDelete",
  LOGIN: "auditLog.actionLogin",
  LOGOUT: "auditLog.actionLogout",
  EXPORT: "auditLog.actionExport",
  IMPORT: "auditLog.actionImport",
  CONVERT: "auditLog.actionConvert",
  PERMISSION_CHANGE: "auditLog.actionPermissionChange",
  MERGE: "auditLog.actionMerge",
};

const AUDIT_ENTITY_TO_KEY: Partial<Record<string, TranslationKey>> = {
  Lead: "auditLog.entityLead",
  Contact: "auditLog.entityContact",
  Account: "auditLog.entityAccount",
  Opportunity: "auditLog.entityOpportunity",
  Quote: "auditLog.entityQuote",
  Invoice: "auditLog.entityInvoice",
  Ticket: "auditLog.entityTicket",
  User: "auditLog.entityUser",
  Product: "auditLog.entityProduct",
};

const ACTION_COLORS: Record<string, string> = {
  CREATE: "bg-green-100 text-green-700",
  UPDATE: "bg-blue-100 text-blue-700",
  DELETE: "bg-red-100 text-red-700",
  LOGIN: "bg-gray-100 text-gray-700",
  LOGOUT: "bg-gray-100 text-gray-600",
  EXPORT: "bg-amber-100 text-amber-700",
  IMPORT: "bg-purple-100 text-purple-700",
  PERMISSION_CHANGE: "bg-orange-100 text-orange-700",
  CONVERT: "bg-teal-100 text-teal-700",
  MERGE: "bg-indigo-100 text-indigo-700",
};

export default function AuditLogsPage() {
  const { t } = useLanguage();
  const ACTION_OPTIONS = useMemo(
    () => [
      { value: "", label: t("auditLog.actionAll") },
      { value: "CREATE", label: t("auditLog.actionCreate") },
      { value: "UPDATE", label: t("auditLog.actionUpdate") },
      { value: "DELETE", label: t("auditLog.actionDelete") },
      { value: "LOGIN", label: t("auditLog.actionLogin") },
      { value: "LOGOUT", label: t("auditLog.actionLogout") },
      { value: "EXPORT", label: t("auditLog.actionExport") },
      { value: "IMPORT", label: t("auditLog.actionImport") },
      { value: "CONVERT", label: t("auditLog.actionConvert") },
      { value: "PERMISSION_CHANGE", label: t("auditLog.actionPermissionChange") },
      { value: "MERGE", label: t("auditLog.actionMerge") },
    ],
    [t]
  );
  const ENTITY_OPTIONS = useMemo(
    () => [
      { value: "", label: t("auditLog.entityAll") },
      { value: "Lead", label: t("auditLog.entityLead") },
      { value: "Contact", label: t("auditLog.entityContact") },
      { value: "Account", label: t("auditLog.entityAccount") },
      { value: "Opportunity", label: t("auditLog.entityOpportunity") },
      { value: "Quote", label: t("auditLog.entityQuote") },
      { value: "Invoice", label: t("auditLog.entityInvoice") },
      { value: "Ticket", label: t("auditLog.entityTicket") },
      { value: "User", label: t("auditLog.entityUser") },
      { value: "Product", label: t("auditLog.entityProduct") },
    ],
    [t]
  );

  const [logs, setLogs] = useState<any[]>([]);
  const [meta, setMeta] = useState({ total: 0, page: 1, pageSize: 20, pageCount: 1 });
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [actionFilter, setActionFilter] = useState("");
  const [entityFilter, setEntityFilter] = useState("");
  const [dateFrom, setDateFrom] = useState("");
  const [dateTo, setDateTo] = useState("");

  const fetchLogs = useCallback(async () => {
    setIsLoading(true);
    try {
      const params = new URLSearchParams({
        page: String(page),
        pageSize: String(pageSize),
        ...(search && { search }),
        ...(actionFilter && { action: actionFilter }),
        ...(entityFilter && { entity: entityFilter }),
        ...(dateFrom && { dateFrom }),
        ...(dateTo && { dateTo }),
      });
      const res = await fetch(`/api/audit-logs?${params}`);
      if (!res.ok) throw new Error("Failed");
      const data = await res.json();
      setLogs(data.data.items);
      setMeta(data.data.meta);
    } catch {
      setError(t("auditLog.loadError"));
    } finally {
      setIsLoading(false);
    }
  }, [page, pageSize, search, actionFilter, entityFilter, dateFrom, dateTo, t]);

  useEffect(() => {
    fetchLogs();
  }, [fetchLogs]);
  useEffect(() => {
    setPage(1);
  }, [search, actionFilter, entityFilter, dateFrom, dateTo]);

  const columns: ColumnDef<any, any>[] = useMemo(
    () => [
      {
        id: "action",
        header: t("auditLog.action"),
        enableSorting: false,
        cell: ({ row }) => {
          const a = row.original;
          const actionKey = AUDIT_ACTION_TO_KEY[a.action];
          return (
            <div className="flex items-center gap-2">
              <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${ACTION_COLORS[a.action] ?? "bg-gray-100 text-gray-600"}`}>
                {actionKey ? t(actionKey) : a.action}
              </span>
            </div>
          );
        },
      },
      {
        id: "entity",
        header: t("auditLog.entity"),
        enableSorting: false,
        cell: ({ row }) => {
          const a = row.original;
          const entityKey = AUDIT_ENTITY_TO_KEY[a.entity];
          return (
            <div>
              <p className="text-sm font-medium">
                {entityKey ? t(entityKey) : a.entity}
              </p>
              {a.entityId && <p className="text-xs text-muted-foreground font-mono">{a.entityId.slice(0, 12)}…</p>}
            </div>
          );
        },
      },
      {
        id: "user",
        header: t("auditLog.performedBy"),
        enableSorting: false,
        cell: ({ row }) => (
          <div>
            <p className="text-sm">{row.original.user?.name ?? t("auditLog.system")}</p>
            {row.original.user?.email && <p className="text-xs text-muted-foreground">{row.original.user.email}</p>}
          </div>
        ),
      },
      {
        id: "ip",
        header: t("auditLog.ipAddress"),
        enableSorting: false,
        cell: ({ row }) => <span className="text-xs font-mono text-muted-foreground">{row.original.ipAddress ?? "—"}</span>,
      },
      {
        id: "changes",
        header: t("auditLog.changesSummary"),
        enableSorting: false,
        cell: ({ row }) => {
          const a = row.original;
          if (!a.newValues) return <span className="text-muted-foreground text-xs">—</span>;
          try {
            const vals = JSON.parse(a.newValues);
            const keys = Object.keys(vals).slice(0, 3);
            return (
              <div className="text-xs text-muted-foreground">
                {keys.map((k) => (
                  <span key={k} className="inline-block bg-muted px-1.5 py-0.5 rounded mr-1 mb-0.5">
                    {k}
                  </span>
                ))}
                {Object.keys(vals).length > 3 && (
                  <span className="text-muted-foreground">{t("auditLog.moreChanges", { n: Object.keys(vals).length - 3 })}</span>
                )}
              </div>
            );
          } catch {
            return <span className="text-xs text-muted-foreground">—</span>;
          }
        },
      },
      {
        accessorKey: "createdAt",
        header: t("auditLog.timestampCol"),
        cell: ({ getValue }) => <span className="text-xs text-muted-foreground">{formatDateTime(getValue() as string)}</span>,
      },
    ],
    [t]
  );

  return (
    <AppShell breadcrumbs={[{ label: t("nav.auditLogs") }]}>
      <PageHeader title={t("auditLog.title")} description={t("auditLog.listSubtitle")}>
        <div className="flex items-center gap-2 text-sm text-muted-foreground bg-amber-50 border border-amber-200 px-3 py-1.5 rounded-lg">
          <Shield className="w-4 h-4 text-amber-600" />
          <span>{t("auditLog.readOnlyHint")}</span>
        </div>
      </PageHeader>

      <div className="flex flex-wrap gap-3 mb-4">
        <div className="w-44">
          <Select options={ACTION_OPTIONS} value={actionFilter} onChange={(e) => setActionFilter(e.target.value)} />
        </div>
        <div className="w-44">
          <Select options={ENTITY_OPTIONS} value={entityFilter} onChange={(e) => setEntityFilter(e.target.value)} />
        </div>
        <Input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)} className="w-40 sm:w-44" />
        <Input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)} className="w-40 sm:w-44" />
        {(actionFilter || entityFilter || dateFrom || dateTo) && (
          <button
            onClick={() => {
              setActionFilter("");
              setEntityFilter("");
              setDateFrom("");
              setDateTo("");
            }}
            className="h-9 px-3 text-sm text-muted-foreground hover:text-foreground rounded-lg border border-border hover:bg-accent transition-colors"
          >
            {t("common.clear")}
          </button>
        )}
      </div>

      <DataTable
        data={logs}
        columns={columns}
        isLoading={isLoading}
        error={error}
        pageCount={meta.pageCount}
        page={meta.page}
        pageSize={meta.pageSize}
        total={meta.total}
        onPageChange={setPage}
        onPageSizeChange={(s) => {
          setPageSize(s);
          setPage(1);
        }}
        searchValue={search}
        onSearchChange={setSearch}
        searchPlaceholder={t("auditLog.searchPlaceholder")}
        emptyTitle={t("auditLog.emptyListTitle")}
        emptyDescription={t("auditLog.emptyListDescription")}
      />
    </AppShell>
  );
}
