"use client";

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

// ─── Constants ──────────────────────────────────────────────────────────────

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" },
};

const ENTITY_TYPE_OPTIONS = [
  "Project",
  "Resource",
  "Allocation",
  "Blueprint",
  "Vacation",
  "Role",
  "Estimate",
  "EstimateVersion",
  "ScopeItem",
  "DemandLine",
  "Comment",
];

const ACTION_OPTIONS = ["CREATE", "UPDATE", "DELETE", "SHIFT", "IMPORT"];

const ENTITY_LINKS: Record<string, (id: string) => string> = {
  Project: (id) => `/projects/${id}`,
  Resource: (id) => `/resources/${id}`,
  Allocation: (id) => `/allocations?allocationId=${id}`,
  Blueprint: (_id) => `/admin/blueprints`,
  Vacation: (_id) => `/vacations`,
  Role: (_id) => `/roles`,
  Estimate: (id) => `/estimates/${id}`,
};

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

function relativeTime(date: Date): 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 userInitials(name: string | null | undefined, email: string): string {
  if (name) {
    const parts = name.trim().split(/\s+/);
    if (parts.length >= 2) return (parts[0]![0]! + parts[parts.length - 1]![0]!).toUpperCase();
    return name.slice(0, 2).toUpperCase();
  }
  return email.slice(0, 2).toUpperCase();
}

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

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

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);
}

// ─── Sub-components ─────────────────────────────────────────────────────────

function ActionBadge({ action }: { action: string }) {
  const badge = ACTION_BADGES[action] ?? { label: action, className: "bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400" };
  return (
    <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${badge.className}`}>
      {badge.label}
    </span>
  );
}

function DiffView({ changes }: { changes: Changes }) {
  const diff = changes.diff;
  if (!diff || Object.keys(diff).length === 0) {
    return <p className="text-sm text-gray-500 dark:text-gray-400">No field-level diff available.</p>;
  }

  return (
    <div className="space-y-1">
      {Object.entries(diff).map(([field, { old: oldVal, new: newVal }]) => (
        <div key={field} className="flex items-start gap-2 text-sm">
          <span className="min-w-[120px] shrink-0 font-medium text-gray-700 dark:text-gray-300">{field}</span>
          <span className="rounded bg-red-50 px-1.5 py-0.5 text-red-700 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.5 py-0.5 text-emerald-700 dark:bg-emerald-900/20 dark:text-emerald-400">
            {formatValue(newVal)}
          </span>
        </div>
      ))}
    </div>
  );
}

function ExpandedDiff({ entryId }: { entryId: string }) {
  const { data, isLoading } = trpc.auditLog.getById.useQuery(
    { id: entryId },
    { staleTime: 300_000 },
  );

  if (isLoading) {
    return (
      <div className="border-t border-gray-100 px-4 py-3 dark:border-slate-700">
        <div className="h-4 w-48 shimmer-skeleton rounded" />
      </div>
    );
  }

  const changes = parseChanges((data as any)?.changes);
  return (
    <div className="border-t border-gray-100 px-4 py-3 dark:border-slate-700">
      <DiffView changes={changes} />
    </div>
  );
}

function SummaryCards({ summary }: { summary: { byEntityType: Record<string, number>; total: number } }) {
  const sorted = useMemo(() => {
    return Object.entries(summary.byEntityType)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 5);
  }, [summary.byEntityType]);

  return (
    <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
      <div className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-800">
        <p className="text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">Total (7d)</p>
        <p className="mt-1 text-2xl font-bold text-gray-900 dark:text-white">{summary.total}</p>
      </div>
      {sorted.map(([type, count]) => (
        <div key={type} className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-800">
          <p className="text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">{type}</p>
          <p className="mt-1 text-2xl font-bold text-gray-900 dark:text-white">{count}</p>
        </div>
      ))}
    </div>
  );
}

// ─── Main Component ─────────────────────────────────────────────────────────

export function ActivityLogClient() {
  // Filters
  const [entityType, setEntityType] = useState("");
  const [action, setAction] = useState("");
  const [userId, setUserId] = useState("");
  const [search, setSearch] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");

  // Expanded entry
  const [expandedId, setExpandedId] = useState<string | null>(null);

  // Summary (last 7 days)
  const sevenDaysAgo = useMemo(() => {
    const d = new Date();
    d.setDate(d.getDate() - 7);
    return d;
  }, []);

  const { data: summary } = trpc.auditLog.getActivitySummary.useQuery(
    { startDate: sevenDaysAgo },
    { staleTime: 60_000 },
  );

  // Users for filter dropdown
  type UserListItem = { id: string; name: string | null; email: string };
  const { data: users = [] } = trpc.user.list.useQuery(undefined, { staleTime: 300_000 }) as { data: UserListItem[] };

  // Build query input
  const queryInput = useMemo(() => {
    const input: Record<string, unknown> = { limit: 50 };
    if (entityType) input.entityType = entityType;
    if (action) input.action = action;
    if (userId) input.userId = userId;
    if (search) input.search = search;
    if (startDate) input.startDate = new Date(startDate);
    if (endDate) input.endDate = new Date(endDate + "T23:59:59");
    return input;
  }, [entityType, action, userId, search, startDate, endDate]);

  type AuditListPage = { items: Array<{
    id: string;
    entityType: string;
    entityId: string;
    action: string;
    changes: unknown;
    createdAt: Date;
    source: string | null;
    entityName: string | null;
    summary: string | null;
    user: { id: string; name: string | null; email: string } | null;
  }>; nextCursor?: string };

  const {
    data,
    isLoading,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    // Keep as any to avoid tRPC TS depth limits with useInfiniteQuery
  } = (trpc.auditLog.list.useInfiniteQuery as any)(
    queryInput,
    {
      getNextPageParam: (lastPage: AuditListPage) => lastPage.nextCursor ?? undefined,
      initialCursor: undefined,
      staleTime: 30_000,
    },
  ) as {
    data: { pages: AuditListPage[] } | undefined;
    isLoading: boolean;
    fetchNextPage: () => void;
    hasNextPage: boolean;
    isFetchingNextPage: boolean;
  };

  const allEntries = useMemo(() => {
    if (!data) return [];
    return data.pages.flatMap((page) => page.items);
  }, [data]);

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

  const totalCount = summary?.total ?? 0;

  return (
    <div className="mx-auto max-w-7xl space-y-6 p-4 sm:p-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Activity Log</h1>
        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
          {totalCount.toLocaleString()} changes recorded in the last 7 days
        </p>
      </div>

      {/* Summary Cards */}
      {summary && <SummaryCards summary={summary} />}

      {/* Filter Bar */}
      <div className="flex flex-wrap items-end gap-3 rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-800">
        <div className="min-w-[140px]">
          <label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">Entity Type</label>
          <select
            value={entityType}
            onChange={(e) => setEntityType(e.target.value)}
            className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-gray-200"
          >
            <option value="">All</option>
            {ENTITY_TYPE_OPTIONS.map((t) => (
              <option key={t} value={t}>{t}</option>
            ))}
          </select>
        </div>

        <div className="min-w-[120px]">
          <label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">Action</label>
          <select
            value={action}
            onChange={(e) => setAction(e.target.value)}
            className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-gray-200"
          >
            <option value="">All</option>
            {ACTION_OPTIONS.map((a) => (
              <option key={a} value={a}>{a}</option>
            ))}
          </select>
        </div>

        <div className="min-w-[160px]">
          <label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">User</label>
          <select
            value={userId}
            onChange={(e) => setUserId(e.target.value)}
            className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-gray-200"
          >
            <option value="">All</option>
            {users.map((u) => (
              <option key={u.id} value={u.id}>{u.name ?? u.email}</option>
            ))}
          </select>
        </div>

        <div className="min-w-[130px]">
          <label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">From</label>
          <input
            type="date"
            value={startDate}
            onChange={(e) => setStartDate(e.target.value)}
            className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-gray-200"
          />
        </div>

        <div className="min-w-[130px]">
          <label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">To</label>
          <input
            type="date"
            value={endDate}
            onChange={(e) => setEndDate(e.target.value)}
            className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-gray-200"
          />
        </div>

        <div className="min-w-[200px] flex-1">
          <label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">Search</label>
          <input
            type="text"
            placeholder="Search entity name or summary..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-gray-200"
          />
        </div>

        <button
          onClick={() => {
            setEntityType("");
            setAction("");
            setUserId("");
            setSearch("");
            setStartDate("");
            setEndDate("");
          }}
          className="rounded-lg border border-gray-300 px-3 py-2 text-sm text-gray-600 hover:bg-gray-50 dark:border-slate-600 dark:text-gray-400 dark:hover:bg-slate-700"
        >
          Reset
        </button>
      </div>

      {/* Timeline List */}
      <div className="space-y-2">
        {isLoading && (
          <div className="flex items-center justify-center py-12">
            <div className="h-6 w-6 animate-spin rounded-full border-2 border-gray-300 border-t-blue-600" />
          </div>
        )}

        {!isLoading && allEntries.length === 0 && (
          <div className="rounded-xl border border-dashed border-gray-300 bg-white py-16 text-center dark:border-slate-600 dark:bg-slate-800">
            <svg className="mx-auto h-10 w-10 text-gray-400 dark:text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <p className="mt-3 text-sm font-medium text-gray-600 dark:text-gray-400">No activity found</p>
            <p className="mt-1 text-xs text-gray-500 dark:text-gray-500">Try adjusting your filters or date range.</p>
          </div>
        )}

        {allEntries.map((entry) => {
          const isExpanded = expandedId === entry.id;
          const entityLink = ENTITY_LINKS[entry.entityType]?.(entry.entityId);

          return (
            <div
              key={entry.id}
              className="rounded-xl border border-gray-200 bg-white shadow-sm transition-shadow hover:shadow-md dark:border-slate-700 dark:bg-slate-800"
            >
              <button
                onClick={() => toggleExpand(entry.id)}
                className="flex w-full items-start gap-3 p-4 text-left"
              >
                {/* User Avatar */}
                <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-gray-200 text-xs font-semibold text-gray-700 dark:bg-slate-600 dark:text-gray-200">
                  {entry.user ? userInitials(entry.user.name, entry.user.email) : "SY"}
                </div>

                {/* Content */}
                <div className="min-w-0 flex-1">
                  <div className="flex flex-wrap items-center gap-2">
                    <span className="text-sm font-medium text-gray-900 dark:text-white">
                      {entry.user?.name ?? entry.user?.email ?? "System"}
                    </span>
                    <ActionBadge action={entry.action} />
                    <span className="text-xs text-gray-500 dark:text-gray-400">
                      {entry.entityType}
                    </span>
                    {entry.entityName && (
                      <>
                        <span className="text-gray-400">&middot;</span>
                        {entityLink ? (
                          <Link
                            href={entityLink as Route}
                            onClick={(e) => e.stopPropagation()}
                            className="text-sm font-medium text-blue-600 hover:underline dark:text-blue-400"
                          >
                            {entry.entityName}
                          </Link>
                        ) : (
                          <span className="text-sm text-gray-700 dark:text-gray-300">{entry.entityName}</span>
                        )}
                      </>
                    )}
                  </div>
                  {entry.summary && (
                    <p className="mt-0.5 text-sm text-gray-600 dark:text-gray-400">{entry.summary}</p>
                  )}
                </div>

                {/* Timestamp */}
                <div className="shrink-0 text-right">
                  <span
                    className="text-xs text-gray-500 dark:text-gray-400"
                    title={new Date(entry.createdAt).toLocaleString("de-DE")}
                  >
                    {relativeTime(entry.createdAt)}
                  </span>
                  {entry.source && (
                    <p className="mt-0.5 text-[10px] uppercase tracking-wide text-gray-400 dark:text-gray-500">
                      {entry.source}
                    </p>
                  )}
                </div>

                {/* Expand indicator */}
                <svg
                  className={`h-4 w-4 shrink-0 text-gray-400 transition-transform ${isExpanded ? "rotate-180" : ""}`}
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                </svg>
              </button>

              {/* Expanded Diff — fetched on demand */}
              {isExpanded && <ExpandedDiff entryId={entry.id} />}
            </div>
          );
        })}

        {/* Load More */}
        {hasNextPage && (
          <div className="flex justify-center pt-4">
            <button
              onClick={() => fetchNextPage()}
              disabled={isFetchingNextPage}
              className="rounded-lg border border-gray-300 bg-white px-6 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-800 dark:text-gray-300 dark:hover:bg-slate-700"
            >
              {isFetchingNextPage ? "Loading..." : "Load more"}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
