"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Bot, History } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { SectionCard } from "@/components/app/page";
import { apiClient } from "@/app/lib/apiClient";
import { formatDate } from "@/app/lib/format";
import { EmptyState, ErrorState } from "@/app/components/ui/page-states";

const DAY_KEY = new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Dhaka", year: "numeric", month: "2-digit", day: "2-digit" });
const TIME = new Intl.DateTimeFormat("en-US", { timeZone: "Asia/Dhaka", hour: "numeric", minute: "2-digit" });

// "2 d ago" style age for the collapsed summary.
function ago(value) {
  const minutes = Math.max(0, Math.round((Date.now() - new Date(value).getTime()) / 60000));
  if (minutes < 60) return minutes <= 1 ? "just now" : `${minutes} min ago`;
  const hours = Math.round(minutes / 60);
  if (hours < 24) return `${hours} h ago`;
  return `${Math.round(hours / 24)} d ago`;
}

/**
 * Loads an activity endpoint that returns { data: [{ id, action, summary, actor, recordLabel, sourceChannel, createdAt }] }
 * (newest first). `reloadKey` refetches when the record changes (e.g. its updated status).
 */
export function useRecordActivity(path, reloadKey) {
  const [items, setItems] = useState([]);
  const [isLoading, setIsLoading] = useState(Boolean(path));
  const [error, setError] = useState(null);
  const loaded = useRef(false);

  const refresh = useCallback(async () => {
    if (!path) return;
    if (!loaded.current) setIsLoading(true);
    setError(null);
    try {
      const payload = await apiClient(path);
      setItems(payload.data || []);
      loaded.current = true;
    } catch (nextError) {
      setError(nextError);
    } finally {
      setIsLoading(false);
    }
  }, [path]);

  useEffect(() => {
    refresh();
  }, [refresh, reloadKey]);

  return { items, isLoading, error, refresh };
}

/**
 * Collapsible "Activity" section for a record page, grouped by day (Asia/Dhaka). The collapsed summary names the
 * latest entry ("Last: Quote QT-00012 sent by Rafa · 2 d ago"). Used on inquiry, style and cost sheet pages.
 */
export function RecordActivitySection({ path, reloadKey, id = "activity", title = "Activity", description = "Who changed what on this record and the records under it, newest first.", className }) {
  const { items, isLoading, error, refresh } = useRecordActivity(path, reloadKey);
  const groups = useMemo(() => {
    const byDay = new Map();
    items.forEach((item) => {
      const key = item.createdAt ? DAY_KEY.format(new Date(item.createdAt)) : "unknown";
      if (!byDay.has(key)) byDay.set(key, []);
      byDay.get(key).push(item);
    });
    return [...byDay.entries()];
  }, [items]);
  const latest = items[0];
  const summary = isLoading ? "Loading…" : latest
    ? `Last: ${latest.summary || latest.actionLabel}${latest.actor?.name ? ` by ${latest.actor.name}` : ""} · ${ago(latest.createdAt)}`
    : "No activity recorded yet";

  return <SectionCard id={id} icon={History} title={title} description={description} collapsible summary={summary} className={className} contentClassName="grid gap-4">
    {isLoading && <div className="grid gap-2">{Array.from({ length: 4 }).map((_, index) => <Skeleton key={index} className="h-10" />)}</div>}
    {!isLoading && error && <ErrorState compact error={error} title="Could not load the activity" onRetry={refresh} />}
    {!isLoading && !error && !items.length && <EmptyState compact icon={History} title="No activity yet" detail="Changes to this record appear here with who made them and when." />}
    {!isLoading && !error && groups.map(([day, rows]) => <section key={day} className="grid gap-2" aria-label={day === "unknown" ? "Date not recorded" : formatDate(day)}>
      <h3 className="text-xs font-medium text-muted-foreground">{day === "unknown" ? "Date not recorded" : formatDate(day)}</h3>
      <ol className="grid gap-1.5 border-l pl-4">
        {rows.map((item) => <li key={item.id} className="relative grid gap-0.5 text-sm">
          <span className="absolute top-1.5 -left-[1.3rem] size-2 rounded-full bg-border" aria-hidden="true" />
          <span className="flex flex-wrap items-center gap-x-2 gap-y-1">
            <span className="font-medium">{item.summary || item.actionLabel}</span>
            {item.recordLabel && <Badge variant="outline" className="h-5 px-1.5 font-normal">{item.recordLabel}</Badge>}
            {item.sourceChannel === "mcp" && <Badge variant="secondary" className="h-5 gap-1 px-1.5 font-normal"><Bot aria-hidden="true" /> AI assistant</Badge>}
          </span>
          <span className="text-xs text-muted-foreground">{item.actor?.name || "System"} · {item.createdAt ? TIME.format(new Date(item.createdAt)) : "time not recorded"}</span>
        </li>)}
      </ol>
    </section>)}
  </SectionCard>;
}
