import { Clock3, History, Sparkles } from "lucide-react";

import type { WorkspaceLogItem } from "../../api/logs";
import { API_BASE_URL } from "../../config/constants";
import { useTranslation } from "../../hooks/useTranslation";
import { Button } from "../ui/button";

const eventBadgeStyles: Record<string, string> = {
  create: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300",
  update: "bg-sky-100 text-sky-700 dark:bg-sky-900/30 dark:text-sky-300",
  delete: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300",
  restore: "bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-300",
  archive: "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",
  unarchive: "bg-lime-100 text-lime-700 dark:bg-lime-900/30 dark:text-lime-300",
  activate: "bg-teal-100 text-teal-700 dark:bg-teal-900/30 dark:text-teal-300",
  deactivate: "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300",
};

const sectionBadgeStyles: Record<string, string> = {
  workspace: "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300",
  workspace_members: "bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300",
  clients: "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300",
  projects: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300",
  project_members: "bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-300",
  tags: "bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-300",
  time_entries: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300",
  rates: "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",
  report_exports: "bg-fuchsia-100 text-fuchsia-700 dark:bg-fuchsia-900/30 dark:text-fuchsia-300",
};

const resolveImageUrl = (value?: string | null) => {
  if (!value) return null;
  if (/^https?:\/\//i.test(value)) return value;
  return `${API_BASE_URL.replace(/\/+$/, "")}/${value.replace(/^\/+/, "")}`;
};

export function LogsFeed({
  items,
  total,
  hasMore,
  isLoading,
  isLoadingMore,
  selectedId,
  onOpen,
  onLoadMore,
}: {
  items: WorkspaceLogItem[];
  total: number;
  hasMore: boolean;
  isLoading: boolean;
  isLoadingMore: boolean;
  selectedId: number | null;
  onOpen: (id: number) => void;
  onLoadMore: () => void;
}) {
  const { t, lang } = useTranslation();

  const formatTimestamp = (value: string) =>
    new Intl.DateTimeFormat(lang === "fa" ? "fa-IR-u-ca-persian" : "en-US", {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    }).format(new Date(value));

  const buildSummary = (item: WorkspaceLogItem) => {
    const actor = item.actor?.full_name || t.logs?.unknownActor || "Unknown actor";
    const eventLabel = t.logs?.events?.[item.event] || item.event;
    const sectionLabel = t.logs?.sections?.[item.section] || item.section;
    const target = item.target?.name || "-";
    if (typeof t.logs?.summary === "function") {
      return t.logs.summary(actor, eventLabel, sectionLabel, target);
    }
    return `${actor} ${eventLabel.toLowerCase()} ${target} in ${sectionLabel.toLowerCase()}`;
  };

  const getInitials = (item: WorkspaceLogItem) => {
    const label = item.actor?.full_name || t.logs?.unknownActor || "?";
    return label.trim().charAt(0).toUpperCase();
  };

  if (isLoading) {
    return (
      <div className="rounded-3xl border border-slate-200 bg-white p-6 text-sm text-slate-500 shadow-sm dark:border-slate-800 dark:bg-slate-900 dark:text-slate-400">
        {t.logs?.loading || "Loading logs..."}
      </div>
    );
  }

  if (!items.length) {
    return (
      <div className="rounded-3xl border border-dashed border-slate-300 bg-white p-8 text-center shadow-sm dark:border-slate-700 dark:bg-slate-900">
        <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-2xl bg-slate-100 text-slate-500 dark:bg-slate-800 dark:text-slate-300">
          <History className="h-5 w-5" />
        </div>
        <p className="text-base font-semibold text-slate-900 dark:text-white">
          {t.logs?.empty || "No activity logs found"}
        </p>
        <p className="mt-2 text-sm text-slate-500 dark:text-slate-400">
          {t.logs?.emptyHint || "Adjust your filters or wait for new workspace activity."}
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="rounded-3xl border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900">
        <div className="flex items-center justify-between border-b border-slate-100 px-5 py-4 dark:border-slate-800">
          <div>
            <h2 className="text-lg font-semibold text-slate-900 dark:text-white">
              {t.logs?.resultsCount?.(total) || `${total} results`}
            </h2>
            <p className="text-sm text-slate-500 dark:text-slate-400">
              {t.logs?.detailsHint || "Select an activity item to inspect the exact field changes."}
            </p>
          </div>
          <div className="hidden items-center gap-2 rounded-2xl bg-slate-100 px-3 py-2 text-sm text-slate-600 dark:bg-slate-800 dark:text-slate-300 sm:flex">
            <Sparkles className="h-4 w-4" />
            <span>{items.length}/{total}</span>
          </div>
        </div>

        <div className="divide-y divide-slate-100 dark:divide-slate-800">
          {items.map((item) => {
            const avatarUrl = resolveImageUrl(item.actor?.profile_picture);
            return (
              <button
                key={item.id}
                type="button"
                onClick={() => onOpen(item.id)}
                className={`flex w-full flex-col gap-3 px-5 py-4 text-left transition hover:bg-slate-50 dark:hover:bg-slate-800/70 ${
                  selectedId === item.id ? "bg-sky-50 dark:bg-sky-950/20" : ""
                }`}
              >
                <div className="flex items-start gap-3">
                  <div className="flex h-11 w-11 shrink-0 items-center justify-center overflow-hidden rounded-2xl bg-slate-200 text-sm font-semibold text-slate-600 dark:bg-slate-800 dark:text-slate-300">
                    {avatarUrl ? (
                      <img src={avatarUrl} alt={item.actor?.full_name || "Actor"} className="h-full w-full object-cover" />
                    ) : (
                      <span>{getInitials(item)}</span>
                    )}
                  </div>

                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <p className="truncate text-sm font-semibold text-slate-900 dark:text-white">
                        {buildSummary(item)}
                      </p>
                      <span className={`inline-flex rounded-full px-2.5 py-1 text-[11px] font-semibold ${sectionBadgeStyles[item.section] || sectionBadgeStyles.workspace}`}>
                        {t.logs?.sections?.[item.section] || item.section}
                      </span>
                      <span className={`inline-flex rounded-full px-2.5 py-1 text-[11px] font-semibold ${eventBadgeStyles[item.event] || eventBadgeStyles.update}`}>
                        {t.logs?.events?.[item.event] || item.event}
                      </span>
                    </div>

                    <div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-slate-500 dark:text-slate-400">
                      <span className="truncate">{item.target?.name}</span>
                      <span className="inline-flex items-center gap-1">
                        <Clock3 className="h-3.5 w-3.5" />
                        {formatTimestamp(item.timestamp)}
                      </span>
                    </div>

                    {item.preview_changes.length ? (
                      <div className="mt-3 flex flex-wrap gap-2">
                        {item.preview_changes.map((change) => (
                          <span
                            key={`${item.id}-${change.field}`}
                            className="inline-flex max-w-full truncate rounded-full bg-slate-100 px-2.5 py-1 text-xs text-slate-600 dark:bg-slate-800 dark:text-slate-300"
                            title={change.summary}
                          >
                            {change.summary}
                          </span>
                        ))}
                      </div>
                    ) : null}
                  </div>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {hasMore ? (
        <div className="flex justify-center">
          <Button
            type="button"
            variant="outline"
            onClick={onLoadMore}
            disabled={isLoadingMore}
            className="rounded-2xl px-5"
          >
            {isLoadingMore ? t.loading || "Loading..." : t.logs?.loadMore || "Load more"}
          </Button>
        </div>
      ) : null}
    </div>
  );
}
