"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import {
  ArrowLeft,
  Clock,
  Activity,
  MessageSquare,
  GitBranch,
  Search,
  Users2,
  Phone,
  Mail,
  ShieldCheck,
  TrendingUp,
  ListFilter,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { Loading } from "@/components/ui/loading";
import { useGetBusinessDealQuery } from "@/api/rtk/business-deals-api";
import type { BusinessDealRecord } from "@/api/rtk/business-deals-api";
import { useGetDealQuery, type Deal } from "@/api/rtk/deals-api";
import {
  useGetActivitiesByBusinessDealQuery,
  useGetActivitiesByDealQuery,
} from "@/api/rtk/activities-api";
import type { ApiActivityLog } from "@/api/rtk/activities-api";
import { UserAvatar } from "@/components/ui/user-avatar";
import { Input } from "@/components/ui/input";
import { ReactSelect } from "@/components/ui/react-select";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

const ALL_MEMBERS_VALUE = "__all__";

// ─── Types ────────────────────────────────────────────────────────────────────

interface UserGroupedActivities {
  userId: string;
  userName: string;
  userAvatar?: string;
  activities: ApiActivityLog[];
  stats: {
    total: number;
    calls: number;
    emails: number;
    meetings: number;
    notes: number;
    others: number;
  };
}

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

function formatDate(iso: string) {
  const d = new Date(iso);
  return {
    full: d.toLocaleString(undefined, {
      month: "short",
      day: "numeric",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    }),
    time: d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
    date: d.toLocaleDateString([], { month: "short", day: "numeric" }),
  };
}

const TYPE_CONFIG: Record<
  string,
  { color: string; light: string; text: string; icon: React.ReactNode }
> = {
  Call: {
    color: "bg-blue-600",
    light: "bg-blue-50",
    text: "text-blue-700",
    icon: <Phone size={14} />,
  },
  Email: {
    color: "bg-sky-600",
    light: "bg-sky-50",
    text: "text-sky-700",
    icon: <Mail size={14} />,
  },
  Meeting: {
    color: "bg-emerald-600",
    light: "bg-emerald-50",
    text: "text-emerald-700",
    icon: <Users2 size={14} />,
  },
  Note: {
    color: "bg-amber-500",
    light: "bg-amber-50",
    text: "text-amber-800",
    icon: <MessageSquare size={14} />,
  },
  Deal: {
    color: "bg-[#6C63FF]",
    light: "bg-[#6C63FF]/10",
    text: "text-[#6C63FF]",
    icon: <TrendingUp size={14} />,
  },
  Win: {
    color: "bg-emerald-600",
    light: "bg-emerald-50",
    text: "text-emerald-700",
    icon: <ShieldCheck size={14} />,
  },
  default: {
    color: "bg-slate-400",
    light: "bg-slate-50",
    text: "text-slate-600",
    icon: <Activity size={14} />,
  },
};

export type UserDealTimelineContext = "lead" | "sales-deal";

function businessDealToTimelineHeaderDeal(
  b: BusinessDealRecord,
): Pick<Deal, "customerName"> {
  const customerName =
    b.title?.trim() ||
    b.linkedLead?.customerName?.trim() ||
    b.linkedCustomer?.fullName?.trim() ||
    b.linkedCustomer?.companyName?.trim() ||
    b.linkedCustomer?.customerName?.trim() ||
    "Business deal";
  return { customerName };
}

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

export function UserDealTimeline({
  dealId,
  dealContext = "lead",
}: {
  dealId: string;
  dealContext?: UserDealTimelineContext;
}) {
  const router = useRouter();
  const listPath = dealContext === "sales-deal" ? "/sales-deals" : "/leads";
  const dealDetailPath =
    dealContext === "sales-deal"
      ? `/sales-deals/${dealId}`
      : `/leads/${dealId}`;
  const auditSubtitle =
    dealContext === "sales-deal"
      ? "Audit overview · team actions on this sale"
      : "Audit overview · team actions on this lead";
  const isSalesDealBoard = dealContext === "sales-deal";
  const { data: leadDeal, isLoading: leadDealLoading } = useGetDealQuery(
    dealId,
    {
      skip: isSalesDealBoard,
    },
  );
  const { data: businessDeal, isLoading: businessDealLoading } =
    useGetBusinessDealQuery(dealId, {
      skip: !isSalesDealBoard,
    });
  const deal = isSalesDealBoard
    ? businessDeal
      ? (businessDealToTimelineHeaderDeal(businessDeal) as Deal)
      : undefined
    : leadDeal;
  const dealLoading = isSalesDealBoard ? businessDealLoading : leadDealLoading;
  const { data: leadActivities = [], isLoading: leadActivitiesLoading } =
    useGetActivitiesByDealQuery({ dealId }, { skip: isSalesDealBoard });
  const {
    data: businessActivities = [],
    isLoading: businessActivitiesLoading,
  } = useGetActivitiesByBusinessDealQuery(
    { businessDealId: dealId },
    {
      skip: !isSalesDealBoard,
    },
  );
  const rawActivities = isSalesDealBoard ? businessActivities : leadActivities;
  const activitiesLoading = isSalesDealBoard
    ? businessActivitiesLoading
    : leadActivitiesLoading;
  const [searchQuery, setSearchQuery] = React.useState("");
  const [selectedUser, setSelectedUser] = React.useState<string | null>(null);

  const userGroups = React.useMemo(() => {
    const groups: Record<string, UserGroupedActivities> = {};

    rawActivities.forEach((act) => {
      const uid = act.userId;
      if (!groups[uid]) {
        groups[uid] = {
          userId: uid,
          userName: act.user?.name || "Unknown User",
          userAvatar: act.user?.profile?.avatar,
          activities: [],
          stats: {
            total: 0,
            calls: 0,
            emails: 0,
            meetings: 0,
            notes: 0,
            others: 0,
          },
        };
      }

      groups[uid].activities.push(act);
      groups[uid].stats.total++;

      if (act.type === "Call") groups[uid].stats.calls++;
      else if (act.type === "Email") groups[uid].stats.emails++;
      else if (act.type === "Meeting") groups[uid].stats.meetings++;
      else if (act.type === "Note") groups[uid].stats.notes++;
      else groups[uid].stats.others++;
    });

    return Object.values(groups).sort((a, b) => b.stats.total - a.stats.total);
  }, [rawActivities]);

  const filteredActivities = React.useMemo(() => {
    let items = [...rawActivities];
    if (selectedUser) {
      items = items.filter((a) => a.userId === selectedUser);
    }
    if (searchQuery) {
      const lowQuery = searchQuery.toLowerCase();
      items = items.filter(
        (a) =>
          a.subject?.toLowerCase().includes(lowQuery) ||
          a.description?.toLowerCase().includes(lowQuery) ||
          a.type?.toLowerCase().includes(lowQuery),
      );
    }
    return items.sort(
      (a, b) =>
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
    );
  }, [rawActivities, selectedUser, searchQuery]);

  const totalActivities = rawActivities.length;
  const uniqueUsersCount = userGroups.length;
  const memberFilterOptions = React.useMemo(
    () => [
      { value: ALL_MEMBERS_VALUE, label: "All activity" },
      ...userGroups.map((group) => ({
        value: group.userId,
        label: `${group.userName} (${group.stats.total} actions)`,
      })),
    ],
    [userGroups],
  );
  const isLoading = dealLoading || activitiesLoading;

  if (isLoading) {
    return (
      <Loading
        layout="panel"
        className="h-full p-12"
        size="lg"
        message="Loading timeline…"
        spinnerClassName="text-[#6C63FF]"
      />
    );
  }

  if (!deal) {
    return (
      <div className="flex flex-col items-center justify-center h-full p-12 text-center">
        <p className="text-[14px] font-semibold text-gray-700">
          Deal not found
        </p>
        <div className="mt-3">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => router.push(listPath)}
          >
            <ArrowLeft size={14} className="mr-1.5" />{" "}
            {dealContext === "sales-deal" ? "Back to sales" : "Back to leads"}
          </Button>
        </div>
      </div>
    );
  }

  return (
    <TooltipProvider>
      <div className="flex min-h-0 h-full flex-1 flex-col animate-in fade-in duration-300">
        {/* Header + KPIs — aligned with BusinessDealDetailView / Deal Overview cards */}
        <div className="shrink-0 border-b border-gray-100 px-4 pb-6 pt-6 sm:px-8 sm:pb-8 sm:pt-8">
          <div className="flex flex-col gap-6">
            <div className="flex items-start gap-3 min-w-0 sm:gap-4">
              <Button
                type="button"
                variant="outline"
                size="icon"
                className="mt-1 h-10 w-10 shrink-0 rounded-xl border-gray-200 font-['Lexend_Deca'] hover:bg-gray-50"
                onClick={() => router.push(dealDetailPath)}
                aria-label="Back to deal"
              >
                <ArrowLeft className="size-4 text-gray-700" />
              </Button>
              <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl border border-[#6C63FF]/20 bg-[#6C63FF]/10 shadow-inner sm:h-16 sm:w-16">
                <Users2
                  className="size-7 text-[#6C63FF] sm:size-8"
                  aria-hidden
                />
              </div>
              <div className="min-w-0 flex-1">
                <div className="mb-1 flex flex-wrap items-center gap-2">
                  <Badge
                    variant="secondary"
                    className="shrink-0 rounded-lg border-none bg-[#6C63FF]/10 font-['Lexend'] text-[10px] font-semibold normal-case tracking-tight text-[#6C63FF] hover:bg-[#6C63FF]/20"
                  >
                    User activity
                  </Badge>
                </div>
                <h1 className="break-words font-['Lexend'] text-xl font-semibold leading-tight tracking-tight text-gray-900 sm:text-[28px]">
                  {deal?.customerName || "Unnamed deal"}
                </h1>
                <p className="mt-1.5 font-['Lexend_Deca'] text-[10px] font-medium uppercase tracking-widest text-gray-400">
                  {auditSubtitle}
                </p>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
              {(
                [
                  {
                    label: "Activity logs",
                    value: totalActivities,
                    icon: <Activity className="size-3.5" aria-hidden />,
                  },
                  {
                    label: "Team members",
                    value: uniqueUsersCount,
                    icon: <Users2 className="size-3.5" aria-hidden />,
                  },
                  {
                    label: selectedUser ? "Shown (filter)" : "Showing",
                    value: filteredActivities.length,
                    icon: <GitBranch className="size-3.5" aria-hidden />,
                  },
                  {
                    label: "Filter",
                    value: selectedUser ? "1 member" : "All",
                    icon: <ListFilter className="size-3.5" aria-hidden />,
                  },
                ] as const
              ).map((stat) => (
                <div
                  key={stat.label}
                  className="group min-w-0 rounded-2xl border border-gray-100/80 bg-gray-50/50 p-4 transition-all hover:border-[#6C63FF]/20 hover:bg-white"
                >
                  <div className="mb-1.5 flex min-w-0 items-center gap-2">
                    <span className="shrink-0 text-gray-400 transition-colors group-hover:text-[#6C63FF]">
                      {stat.icon}
                    </span>
                    <span className="truncate font-['Lexend_Deca'] text-[10px] font-medium uppercase tracking-widest text-gray-400">
                      {stat.label}
                    </span>
                  </div>
                  <p className="break-words font-['Lexend'] text-[15px] font-medium text-gray-800 [overflow-wrap:anywhere]">
                    {stat.value}
                  </p>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="min-h-0 flex-1 overflow-y-auto px-4 py-6 sm:px-8 scrollbar-themed">
          <div className="mx-auto flex w-full flex-col gap-6">
            {/* Team filter */}
            <div className="rounded-2xl border border-gray-100/80 bg-gray-50/50 p-4 sm:p-5">
              <div className="mb-3 flex items-center gap-2">
                <span className="text-[#6C63FF]/60">
                  <Users2 size={14} aria-hidden />
                </span>
                <h2 className="text-[11px] font-semibold uppercase tracking-widest text-gray-400">
                  Team members
                </h2>
                <div className="ml-1 h-px min-w-[2rem] flex-1 bg-gray-100" />
                <Badge
                  variant="secondary"
                  className="shrink-0 rounded-lg font-['Lexend'] text-[10px] font-semibold"
                >
                  {uniqueUsersCount}
                </Badge>
              </div>
              <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <ReactSelect
                  value={selectedUser ?? ALL_MEMBERS_VALUE}
                  onValueChange={(v) =>
                    setSelectedUser(v === ALL_MEMBERS_VALUE ? null : v)
                  }
                  options={memberFilterOptions}
                  placeholder="Select a team member"
                  align="end"
                  triggerClassName="h-10 min-h-10 w-full rounded-xl border-gray-200 bg-white font-['Lexend_Deca'] text-[13px] font-bold shadow-sm sm:w-[min(100%,20rem)]"
                  contentClassName="rounded-xl"
                />
              </div>
            </div>

            {/* Timeline panel */}
            <div className="overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm">
              <div className="flex flex-col gap-3 border-b border-gray-100 px-4 py-4 sm:flex-row sm:items-center sm:px-5">
                <div className="flex min-w-0 flex-wrap items-center gap-2">
                  <Clock
                    size={14}
                    className="shrink-0 text-[#6C63FF]/70"
                    aria-hidden
                  />
                  <h2 className="font-['Lexend'] text-[13px] font-bold text-gray-800">
                    {selectedUser
                      ? `${userGroups.find((g) => g.userId === selectedUser)?.userName ?? "User"} · timeline`
                      : "Full activity stream"}
                  </h2>
                  <Badge
                    variant="outline"
                    className="rounded-lg border-gray-200 font-['Lexend'] text-[10px] text-gray-600"
                  >
                    {filteredActivities.length} logs
                  </Badge>
                </div>
                <div className="relative w-full sm:ml-auto ">
                  <Search
                    className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-gray-400"
                    aria-hidden
                  />
                  <Input
                    type="search"
                    placeholder="Search logs…"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="h-10 rounded-xl border-gray-200 bg-gray-50/80 pl-9 font-['Lexend_Deca'] text-[13px] focus:bg-white"
                  />
                </div>
              </div>

              <div className="p-4 sm:p-5">
                {filteredActivities.length === 0 ? (
                  <div className="flex flex-col items-center justify-center py-12 text-center">
                    <Clock size={32} className="text-gray-200 mb-3" />
                    <p className="text-[13px] font-semibold text-gray-600">
                      No logs found
                    </p>
                    <p className="text-[11px] text-gray-400 mt-1 max-w-sm">
                      Try another team member or clear your search.
                    </p>
                  </div>
                ) : (
                  <div className="space-y-10 pb-6">
                    {Array.from(
                      new Set(
                        filteredActivities.map((a) =>
                          new Date(a.createdAt).toDateString(),
                        ),
                      ),
                    ).map((date) => (
                      <section key={date}>
                        <div className="flex items-center gap-4 mb-5">
                          <Badge
                            variant="outline"
                            className="text-[10px] font-bold uppercase tracking-widest text-gray-600 border-gray-200 bg-white/80"
                          >
                            {new Date(date).toLocaleDateString(undefined, {
                              weekday: "long",
                              month: "short",
                              day: "numeric",
                            })}
                          </Badge>
                          <div className="flex-1 h-px bg-gray-100" />
                        </div>

                        <div className="relative pl-12 md:pl-14 space-y-5 before:absolute before:left-[15px] md:before:left-[17px] before:top-2 before:bottom-0 before:w-px before:bg-gray-100">
                          {filteredActivities
                            .filter(
                              (a) =>
                                new Date(a.createdAt).toDateString() === date,
                            )
                            .map((act) => {
                              const config =
                                TYPE_CONFIG[act.type] || TYPE_CONFIG.default;
                              const { time } = formatDate(act.createdAt);

                              return (
                                <div
                                  key={act.id}
                                  className="relative flex gap-4"
                                >
                                  <div
                                    className={cn(
                                      "absolute -left-12 md:-left-14 top-0.5 h-8 w-8 rounded-full flex items-center justify-center text-white shrink-0 shadow-sm z-10 border-2 border-white",
                                      config.color,
                                    )}
                                  >
                                    {config.icon}
                                  </div>

                                  <div className="flex-1 min-w-0 rounded-2xl border border-[#e5e7eb] bg-white shadow-[0px_2px_12px_0px_rgba(0,0,0,0.04)] overflow-hidden">
                                    <div className="flex flex-col md:flex-row">
                                      <div className="flex-1 p-4 md:p-5 flex flex-col gap-3">
                                        <div className="flex flex-col md:flex-row md:items-start justify-between gap-3">
                                          <div className="min-w-0 space-y-1">
                                            <div className="flex flex-wrap items-center gap-2">
                                              <span className="text-[14px] font-semibold text-gray-900 leading-snug">
                                                {act.subject}
                                              </span>
                                              <Badge
                                                className={cn(
                                                  "text-[9px] font-bold h-5 uppercase tracking-tight rounded-md border-0",
                                                  config.light,
                                                  config.text,
                                                )}
                                              >
                                                {act.type}
                                              </Badge>
                                            </div>
                                            <p className="text-[12px] text-gray-500 leading-relaxed">
                                              {act.description &&
                                              act.description.includes("-") &&
                                              act.description.startsWith(
                                                "Activity",
                                              )
                                                ? `${act.type || "System"} interaction log entry`
                                                : act.description ||
                                                  "Administrative system update log."}
                                            </p>
                                          </div>
                                          <div className="flex items-center gap-2 text-gray-400 shrink-0 bg-gray-50/80 px-3 py-1.5 rounded-xl border border-gray-100 self-start">
                                            <div className="text-right">
                                              <span className="text-[12px] font-bold text-gray-700 block">
                                                {time}
                                              </span>
                                              <span className="text-[9px] font-semibold uppercase tracking-tight text-gray-400">
                                                Recorded
                                              </span>
                                            </div>
                                          </div>
                                        </div>

                                        {act.metadata &&
                                          Object.keys(act.metadata).length >
                                            0 && (
                                            <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
                                              {Object.entries(act.metadata).map(
                                                ([k, v]) => (
                                                  <div
                                                    key={k}
                                                    className="rounded-xl p-2.5 border border-gray-100 bg-gray-50/50"
                                                  >
                                                    <p className="text-[8px] font-bold text-gray-400 uppercase tracking-widest mb-0.5">
                                                      {k}
                                                    </p>
                                                    <p className="text-[11px] font-semibold text-gray-600 truncate">
                                                      {String(v)}
                                                    </p>
                                                  </div>
                                                ),
                                              )}
                                            </div>
                                          )}
                                      </div>

                                      <div className="md:w-48 border-t md:border-t-0 md:border-l border-gray-100 p-4 flex flex-row md:flex-col items-center md:text-center gap-3 md:gap-2 bg-gray-50/30">
                                        <Tooltip>
                                          <TooltipTrigger asChild>
                                            <div className="flex md:flex-col items-center gap-2 md:gap-0">
                                              <UserAvatar
                                                name={act.user?.name}
                                                avatar={
                                                  act.user?.profile?.avatar
                                                }
                                                size="md"
                                                className="shadow-sm shrink-0"
                                              />
                                              <div className="min-w-0 text-left md:text-center">
                                                <h4 className="text-[12px] font-semibold text-gray-800 truncate">
                                                  {act.user?.name}
                                                </h4>
                                                <p className="text-[9px] font-semibold text-gray-400 uppercase tracking-tight mt-0.5">
                                                  Team member
                                                </p>
                                              </div>
                                            </div>
                                          </TooltipTrigger>
                                          <TooltipContent side="bottom">
                                            {act.user?.name ?? "User"}
                                          </TooltipContent>
                                        </Tooltip>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              );
                            })}
                        </div>
                      </section>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </TooltipProvider>
  );
}
