"use client";

import { useState, useCallback } from "react";
import Link from "next/link";
import type { Route } from "next";
import { trpc } from "~/lib/trpc/client.js";

// ─── Helpers ────────────────────────────────────────────────────────────────

const ACTION_BADGES: Record<string, { label: string; className: string }> = {
  CREATE: { label: "Create", className: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-400" },
  UPDATE: { label: "Update", className: "bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-400" },
  DELETE: { label: "Delete", className: "bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-400" },
  SHIFT: { label: "Shift", className: "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-400" },
  IMPORT: { label: "Import", className: "bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-400" },
};

function relativeTime(date: Date | string): string {
  const now = new Date();
  const diffMs = now.getTime() - new Date(date).getTime();
  const diffSec = Math.floor(diffMs / 1000);
  const diffMin = Math.floor(diffSec / 60);
  const diffHr = Math.floor(diffMin / 60);
  const diffDays = Math.floor(diffHr / 24);

  if (diffSec < 60) return "just now";
  if (diffMin < 60) return `${diffMin}m ago`;
  if (diffHr < 24) return `${diffHr}h ago`;
  if (diffDays < 7) return `${diffDays}d ago`;
  return new Date(date).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", year: "numeric" });
}

function formatValue(val: unknown): string {
  if (val === null || val === undefined) return "(empty)";
  if (typeof val === "boolean") return val ? "Yes" : "No";
  if (typeof val === "object") return JSON.stringify(val);
  return String(val);
}

type DiffEntry = { old: unknown; new: unknown };
type Changes = {
  before?: Record<string, unknown>;
  after?: Record<string, unknown>;
  diff?: Record<string, DiffEntry>;
};

function parseChanges(changes: unknown): Changes {
  if (!changes || typeof changes !== "object") return {};
  return changes as Changes;
}

// ─── Component ──────────────────────────────────────────────────────────────

interface EntityHistoryProps {
  entityType: string;
  entityId: string;
  limit?: number;
}

type AuditEntry = {
  id: string;
  entityType: string;
  entityId: string;
  action: string;
  changes: unknown;
  createdAt: Date | string;
  source: string | null;
  entityName: string | null;
  summary: string | null;
  user: { id: string; name: string | null; email: string } | null;
};

export function EntityHistory({ entityType, entityId, limit = 10 }: EntityHistoryProps) {
  const [expandedId, setExpandedId] = useState<string | null>(null);

  const { data: entries = [], isLoading } = trpc.auditLog.getByEntity.useQuery(
    { entityType, entityId, limit },
    { staleTime: 30_000 },
  ) as { data: AuditEntry[]; isLoading: boolean };

  const toggleExpand = useCallback((id: string) => {
    setExpandedId((prev) => (prev === id ? null : id));
  }, []);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-6">
        <div className="h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-blue-600" />
      </div>
    );
  }

  if (entries.length === 0) {
    return (
      <div className="py-6 text-center text-sm text-gray-500 dark:text-gray-400">
        No history recorded yet.
      </div>
    );
  }

  return (
    <div className="space-y-1">
      <h3 className="mb-3 text-sm font-semibold text-gray-700 dark:text-gray-300">Change History</h3>

      {/* Timeline */}
      <div className="relative space-y-0">
        {/* Vertical line */}
        <div className="absolute left-3 top-2 bottom-2 w-px bg-gray-200 dark:bg-slate-600" />

        {entries.map((entry) => {
          const changes = parseChanges(entry.changes);
          const isExpanded = expandedId === entry.id;
          const badge = ACTION_BADGES[entry.action] ?? { label: entry.action, className: "bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400" };

          return (
            <div key={entry.id} className="relative pl-8">
              {/* Dot */}
              <div className="absolute left-1.5 top-2.5 h-3 w-3 rounded-full border-2 border-white bg-gray-400 dark:border-slate-800 dark:bg-slate-500" />

              <button
                onClick={() => toggleExpand(entry.id)}
                className="w-full rounded-lg p-2 text-left transition-colors hover:bg-gray-50 dark:hover:bg-slate-700/50"
              >
                <div className="flex items-center gap-2">
                  <span className={`inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium ${badge.className}`}>
                    {badge.label}
                  </span>
                  <span className="text-xs text-gray-500 dark:text-gray-400">
                    {entry.user?.name ?? entry.user?.email ?? "System"}
                  </span>
                  <span
                    className="ml-auto text-[10px] text-gray-400 dark:text-gray-500"
                    title={new Date(entry.createdAt).toLocaleString("de-DE")}
                  >
                    {relativeTime(entry.createdAt)}
                  </span>
                </div>
                {entry.summary && (
                  <p className="mt-0.5 text-xs text-gray-600 dark:text-gray-400">{entry.summary}</p>
                )}
              </button>

              {/* Expanded diff */}
              {isExpanded && changes.diff && Object.keys(changes.diff).length > 0 && (
                <div className="mb-2 ml-2 rounded-lg border border-gray-100 bg-gray-50 p-2 dark:border-slate-700 dark:bg-slate-800/50">
                  {Object.entries(changes.diff).map(([field, { old: oldVal, new: newVal }]) => (
                    <div key={field} className="flex items-start gap-2 text-xs">
                      <span className="min-w-[80px] shrink-0 font-medium text-gray-600 dark:text-gray-400">{field}</span>
                      <span className="rounded bg-red-50 px-1 text-red-600 line-through dark:bg-red-900/20 dark:text-red-400">
                        {formatValue(oldVal)}
                      </span>
                      <span className="text-gray-400">&rarr;</span>
                      <span className="rounded bg-emerald-50 px-1 text-emerald-600 dark:bg-emerald-900/20 dark:text-emerald-400">
                        {formatValue(newVal)}
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Link to full log */}
      <div className="pt-2 text-center">
        <Link
          href={`/admin/activity-log?entityType=${encodeURIComponent(entityType)}&search=${encodeURIComponent(entityId)}` as Route}
          className="text-xs font-medium text-blue-600 hover:underline dark:text-blue-400"
        >
          View all in Activity Log
        </Link>
      </div>
    </div>
  );
}
