import React, { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { format, isToday, isYesterday } from "date-fns";
import {
  MessageCircle,
  ChevronDown,
  ChevronUp,
  RefreshCw,
  User,
  Calendar,
  Building,
  Clock3,
} from "lucide-react";
import { Card, CardContent } from "@/shared/common/ui/card";
import { useRemarks } from "@/record-management/components/hooks/useRecordAssignment";
import { useLocalizedName } from "@/shared/common/localizedName";
import { renderStatus } from "@/record-management/utils/renderDetails";

/* ============================================================================
 *  CommentCard — compact assignment/comment panel (named export)
 * ========================================================================== */

export interface CommentCardProps {
  createdAt: string;
  /** Optional Amharic-formatted timestamp shown when the locale is `am`. */
  amharicCreatedAt?: string | null;
  comment?: string | null;
  assignerName: string;
  showCommentTitle?: boolean;
  showFromText?: boolean;
  commentSection?: {
    amharicCreatedAt?: string | null;
    comment?: string | null;
    assignerName: string;
    createdAt: string;
  }[];
  variant?: "default" | "secondary" | "info" | "success";
}

const formatCreatedAt = (createdAt: string) => {
  if (!createdAt) {
    return "Unknown time";
  }

  const date = new Date(createdAt);
  if (Number.isNaN(date.getTime())) {
    return createdAt;
  }

  return date.toLocaleString(undefined, {
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
};

const getInitials = (name: string) =>
  name
    .split(" ")
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase() ?? "")
    .join("") || "A";

export const CommentCard = ({
  createdAt,
  amharicCreatedAt,
  comment,
  assignerName,
  commentSection,
  showCommentTitle = true,
  showFromText = true,
}: CommentCardProps) => {
  const { t, i18n } = useTranslation();
  const lang = i18n.language || "en";
  const [expanded, setExpanded] = useState<Set<string>>(new Set());

  const toggleExpand = (id: string) => {
    setExpanded((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  // Helper function to render a single comment
  const renderSingleComment = (
    commentText: string | null | undefined,
    assigner: string,
    date?: string,
    amharicDate?: string | null,
    key?: number,
  ) => {
    const displayedComment =
      commentText?.trim() ||
      t("viewDetail.noComment", { defaultValue: "No comment provided." });
    const initials = getInitials(assigner);

    let displayedDate = "";
    if (date) {
      displayedDate =
        lang === "am" && amharicDate ? amharicDate : formatCreatedAt(date);
    } else if (amharicDate && lang === "am") {
      displayedDate = amharicDate;
    } else {
      displayedDate = t("viewDetail.dateNotAvailable", {
        defaultValue: "Date not available",
      });
    }

    const commentId = key !== undefined ? String(key) : "single";
    const isExpanded = expanded.has(commentId);
    const isLongComment = displayedComment.length > 150;
    return (
      <li key={commentId} className="relative">
        <span className="absolute -left-[27px] top-1 h-3 w-3 rounded-full bg-primary-500 ring-4 ring-white dark:ring-gray-800" />

        <div className="rounded-lg border border-gray-200 bg-white transition-shadow hover:shadow-sm dark:border-gray-700 dark:bg-gray-800">
          <header className="flex items-start justify-between gap-2 border-b border-gray-100 p-3 dark:border-gray-700">
            <div className="flex min-w-0 items-center gap-3">
              <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-primary-500 to-primary-600 text-xs font-semibold text-white shadow-sm">
                {initials}
              </div>

              <div className="min-w-0">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="truncate text-sm font-semibold text-gray-900 dark:text-white">
                    {showFromText && <>{t("viewDetail.from", "From")} </>}
                    <span className="font-medium">
                      {assigner ||
                        t("common.unknownUser", { defaultValue: "Unknown" })}
                    </span>
                  </span>

                  {renderStatus("commented", "commented")}
                </div>

                {displayedDate && (
                  <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-600 dark:text-gray-400">
                    <span className="inline-flex items-center gap-1">
                      <Clock3 className="h-3 w-3" />
                      {displayedDate}
                    </span>
                  </div>
                )}
              </div>
            </div>
          </header>

          <div className="p-3">
            <div
              className={`transition-all duration-200 ${
                isExpanded ? "" : "max-h-20 overflow-hidden"
              }`}
            >
              <p className="whitespace-pre-wrap break-words text-sm leading-relaxed text-gray-700 dark:text-gray-200">
                {displayedComment}
              </p>
            </div>

            {isLongComment && (
              <button
                type="button"
                onClick={() => toggleExpand(commentId)}
                className="mt-2 inline-flex items-center gap-1.5 rounded-md bg-gray-50 px-2.5 py-1 text-xs font-medium text-gray-700 transition-colors hover:bg-gray-100 hover:text-gray-900 dark:bg-gray-700/50 dark:text-gray-300 dark:hover:bg-gray-700 dark:hover:text-white"
              >
                {isExpanded ? (
                  <>
                    <ChevronUp className="h-3 w-3" />
                    {t("featuredNews.readLess")}
                  </>
                ) : (
                  <>
                    <ChevronDown className="h-3 w-3" />
                    {t("featuredNews.readMore")}
                  </>
                )}
              </button>
            )}
          </div>
        </div>
      </li>
    );
  };

  const renderCommentPanel = (comments: React.ReactNode[]) => (
    <Card className="border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800">
      <CardContent className="p-0">
        {showCommentTitle && (
          <div className="rounded-t-lg border-b border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900">
            <div className="flex items-center gap-2">
              <MessageCircle className="h-5 w-5 text-primary-600 dark:text-primary-400" />
              <h3 className="font-semibold text-gray-900 dark:text-white">
                {t("viewDetail.comment", { defaultValue: "Comment" })}
                {comments.length > 1 ? ` (${comments.length})` : ""}
              </h3>
            </div>
          </div>
        )}

        <div className="p-4">
          <ul className="relative space-y-4 border-l-2 border-gray-200 pl-5 dark:border-gray-700">
            {comments}
          </ul>
        </div>
      </CardContent>
    </Card>
  );

  // Case 1: Multiple comments in commentSection
  if (commentSection && commentSection.length > 1) {
    const comments = commentSection
      .filter((section) => section.comment?.trim())
      .map((section, index) =>
        renderSingleComment(
          section.comment,
          section.assignerName,
          section.createdAt,
          section.amharicCreatedAt,
          index,
        ),
      );

    if (!comments.length) {
      return null;
    }

    return renderCommentPanel(comments);
  }

  // Case 2: Single comment in commentSection
  if (commentSection && commentSection.length === 1) {
    const singleComment = commentSection[0];
    if (
      singleComment.comment &&
      singleComment.comment !== "" &&
      singleComment.comment.trim().length > 0
    ) {
      return renderCommentPanel([
        renderSingleComment(
          singleComment.comment,
          singleComment.assignerName,
          singleComment.createdAt,
          singleComment.amharicCreatedAt,
        ),
      ]);
    }
  }

  // Case 3: No commentSection or empty array, use props
  return renderCommentPanel([
    renderSingleComment(
      comment,
      assignerName || "",
      createdAt,
      amharicCreatedAt,
    ),
  ]);
};
/* ============================================================================
 *  WorkflowCommentHistory — outgoing-record timeline (default export)
 *  Untouched visually. Renders inline cards with date grouping, action-colored
 *  dots on the rail, and status badges. Independent from CommentCard above.
 * ========================================================================== */

export interface WorkflowHistoryItem {
  id: string;
  comment?: string | null;
  action?: string | null;
  createdAt: string;
  amharicCreatedAt?: string | null;
  employeePosition?: {
    employee?: { name?: { en?: string; am?: string } | null } | null;
    position?: { name?: { en?: string; am?: string } | null } | null;
  } | null;
  delegatedEmployeePosition?: {
    employee?: { name?: { en?: string; am?: string } | null } | null;
    position?: { name?: { en?: string; am?: string } | null } | null;
  } | null;
}

export interface WorkflowCommentHistoryProps {
  /** When provided, the component fetches outgoing-history itself. */
  recordId?: string;
  /** Or pass pre-fetched items to skip the network call. */
  items?: WorkflowHistoryItem[];
  /** Override the header title. */
  title?: string;
  /** Restrict to a subset of raw API actions (case-insensitive). */
  filterActions?: string[];
  className?: string;
  showHeader?: boolean;
  emptyMessage?: string;
}

const ACTION_DOT: Record<string, string> = {
  approved: "bg-primary-500",
  accepted: "bg-primary-500",
  forwarded: "bg-blue-500",
  rejected: "bg-red-500",
  send_back: "bg-amber-500",
  sent_back: "bg-amber-500",
  adjustment: "bg-amber-500",
  adjustment_requested: "bg-amber-500",
  default: "bg-primary-500",
};

const dateBucketLabel = (
  iso: string,
  lang: string,
  amharic: string | undefined | null,
  t: (key: string) => string,
) => {
  const d = new Date(iso);
  if (isToday(d)) return t("common.today");
  if (isYesterday(d)) return t("common.yesterday");
  return lang === "en"
    ? format(d, "MMMM d, yyyy")
    : amharic?.split(" ")?.slice(0, 3).join(" ") || format(d, "MMMM d, yyyy");
};

const WorkflowCommentHistory: React.FC<WorkflowCommentHistoryProps> = ({
  recordId,
  items: providedItems,
  title,
  filterActions,
  className = "",
  showHeader = true,
  emptyMessage,
}) => {
  const { t, i18n } = useTranslation();
  const lang = i18n.language || "en";
  const localizedName = useLocalizedName();
  const shouldFetch = !providedItems && !!recordId;
  const { data, isLoading, error, refetch } = useRemarks(recordId ?? "", {
    enabled: shouldFetch,
  });

  const rawItems: WorkflowHistoryItem[] =
    providedItems ?? (data?.items as WorkflowHistoryItem[] | undefined) ?? [];

  const filteredItems = useMemo(() => {
    if (!filterActions?.length) return rawItems;
    const set = new Set(filterActions.map((a) => a.toLowerCase()));
    return rawItems.filter((i) => set.has((i.action || "").toLowerCase()));
  }, [rawItems, filterActions]);

  const [expanded, setExpanded] = useState<Set<string>>(new Set());

  const groupedByDate = useMemo(() => {
    if (!filteredItems.length)
      return [] as { label: string; items: WorkflowHistoryItem[] }[];
    const groups = new Map<
      string,
      { label: string; items: WorkflowHistoryItem[] }
    >();
    [...filteredItems]
      .sort(
        (a, b) =>
          new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
      )
      .forEach((item) => {
        const key = format(new Date(item.createdAt), "yyyy-MM-dd");
        const label = dateBucketLabel(
          item.createdAt,
          lang,
          item.amharicCreatedAt,
          t,
        );
        const bucket = groups.get(key);
        if (bucket) bucket.items.push(item);
        else groups.set(key, { label, items: [item] });
      });
    return Array.from(groups.values());
  }, [filteredItems, lang, t]);

  if (shouldFetch && isLoading) {
    return (
      <div
        className={`flex justify-center items-center p-8 ${className}`}
        role="status"
      >
        <RefreshCw className="h-6 w-6 animate-spin mr-2 text-gray-600 dark:text-gray-400" />
        <span className="text-sm text-gray-600 dark:text-gray-400">
          {t("viewDetail.loadingRemarks")}
        </span>
      </div>
    );
  }

  if (shouldFetch && error) {
    return (
      <div
        className={`flex flex-col items-center justify-center p-6 text-center ${className}`}
      >
        <div className="rounded-full bg-red-100 dark:bg-red-900/30 p-3 mb-3">
          <MessageCircle className="h-6 w-6 text-red-600 dark:text-red-400" />
        </div>
        <p className="text-red-600 dark:text-red-400 font-medium mb-2">
          {t("viewDetail.failedToLoadRemarks")}
        </p>
        <button
          onClick={() => refetch()}
          className="mt-2 text-sm text-primary-600 dark:text-primary-400 hover:text-primary-800 dark:hover:text-primary-300 font-medium"
        >
          {t("common.retry")}
        </button>
      </div>
    );
  }

  if (!filteredItems.length) {
    return (
      <div
        className={`text-center p-8 border-2 border-dashed border-gray-200 dark:border-gray-700 rounded-lg ${className}`}
      >
        <MessageCircle className="h-12 w-12 text-gray-400 dark:text-gray-500 mx-auto mb-3" />
        <p className="text-muted-foreground dark:text-gray-400 font-medium">
          {emptyMessage || t("viewDetail.noRemarksAvailable")}
        </p>
      </div>
    );
  }

  const toggleExpand = (id: string) => {
    setExpanded((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const initialsOf = (name?: string) =>
    (name || "?")
      .split(/\s+/)
      .filter(Boolean)
      .slice(0, 2)
      .map((p) => p[0]?.toUpperCase())
      .join("") || "?";

  return (
    <Card
      className={`shadow-sm border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 ${className}`}
    >
      <CardContent className="p-0">
        {showHeader && (
          <div className="p-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900 rounded-t-lg">
            <div className="flex items-center gap-2">
              <MessageCircle className="h-5 w-5 text-primary-600 dark:text-primary-400" />
              <h3 className="font-semibold text-gray-900 dark:text-white">
                {title || t("viewDetail.remarks")} ({filteredItems.length})
              </h3>
            </div>
          </div>
        )}

        <div className="p-4 space-y-6">
          {groupedByDate.map((group) => (
            <section key={group.label} aria-label={group.label}>
              <div className="flex items-center gap-3 mb-3">
                <span className="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
                  {group.label}
                </span>
                <div className="flex-1 h-px bg-gray-200 dark:bg-gray-700" />
              </div>

              <ul className="relative border-l-2 border-gray-200 dark:border-gray-700 pl-5 space-y-4">
                {group.items.map((item, idx) => {
                  const isExpanded = expanded.has(item.id);
                  const delegatedEmployeeName = item.delegatedEmployeePosition
                    ? localizedName(
                        item.delegatedEmployeePosition?.employee?.name as {
                          am: string;
                          en: string;
                        },
                      )
                    : "";
                  const assignedEmployeeName = item.employeePosition?.employee
                    ? localizedName(
                        (item.employeePosition.employee.name as {
                          am: string;
                          en: string;
                        }) || {
                          en: "",
                          am: "",
                        },
                      )
                    : "";
                  const employeeName =
                    delegatedEmployeeName && delegatedEmployeeName !== ""
                      ? `${delegatedEmployeeName} (${t("viewDetail.for")} ${assignedEmployeeName})`
                      : assignedEmployeeName;

                  const positionName =
                    lang === "en"
                      ? item.employeePosition?.position?.name?.en ||
                        item.employeePosition?.position?.name?.am
                      : item.employeePosition?.position?.name?.am ||
                        item.employeePosition?.position?.name?.en;
                  const hasComment =
                    !!item.comment && item.comment.trim().length > 0;
                  const prev = idx > 0 ? group.items[idx - 1] : null;
                  const sameSenderAsPrev =
                    !!prev &&
                    prev.employeePosition?.employee?.name?.en ===
                      item.employeePosition?.employee?.name?.en;
                  const actionKey = (item.action || "").toLowerCase();
                  const dotClass = ACTION_DOT[actionKey] || ACTION_DOT.default;
                  const statusKey = actionKey || "commented";

                  return (
                    <li key={item.id} className="relative">
                      <span
                        className={`absolute -left-[27px] top-1 h-3 w-3 rounded-full ring-4 ring-white dark:ring-gray-800 ${dotClass}`}
                      />
                      <div className="rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 hover:shadow-sm transition-shadow">
                        <header className="flex items-start justify-between gap-2 p-3 border-b border-gray-100 dark:border-gray-700">
                          <div className="flex items-center gap-3 min-w-0">
                            {sameSenderAsPrev ? (
                              <div className="w-8 h-8 flex-shrink-0" />
                            ) : (
                              <div className="flex-shrink-0 w-8 h-8 bg-gradient-to-br from-primary-500 to-primary-600 rounded-full flex items-center justify-center text-white text-xs font-semibold shadow-sm">
                                {employeeName ? (
                                  initialsOf(employeeName)
                                ) : (
                                  <User className="h-4 w-4" />
                                )}
                              </div>
                            )}
                            <div className="min-w-0">
                              <div className="flex flex-wrap items-center gap-2">
                                <span className="font-semibold text-gray-900 dark:text-white text-sm truncate">
                                  {t("viewDetail.from", "From")}{" "}
                                  <span className="font-medium">
                                    {employeeName || t("common.unknownUser")}
                                  </span>
                                </span>
                                {renderStatus(statusKey, statusKey)}
                              </div>
                              <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-600 dark:text-gray-400">
                                {positionName && (
                                  <span className="inline-flex items-center gap-1">
                                    <Building className="h-3 w-3" />
                                    <span className="truncate">
                                      {positionName}
                                    </span>
                                  </span>
                                )}
                                <span
                                  className="inline-flex items-center gap-1"
                                  title={format(
                                    new Date(item.createdAt),
                                    "PPpp",
                                  )}
                                >
                                  <Calendar className="h-3 w-3" />
                                  {lang === "en"
                                    ? format(new Date(item.createdAt), "h:mm a")
                                    : item.amharicCreatedAt ||
                                      format(
                                        new Date(item.createdAt),
                                        "h:mm a",
                                      )}
                                </span>
                              </div>
                            </div>
                          </div>
                        </header>

                        <div className="p-3">
                          {hasComment ? (
                            <>
                              <div
                                className={`transition-all duration-200 ${
                                  isExpanded ? "" : "max-h-20 overflow-hidden"
                                }`}
                              >
                                <p className="text-sm text-gray-700 dark:text-gray-200 whitespace-pre-wrap leading-relaxed">
                                  {item.comment}
                                </p>
                              </div>
                              {(item.comment?.length ?? 0) > 150 && (
                                <button
                                  onClick={() => toggleExpand(item.id)}
                                  className="mt-2 inline-flex items-center gap-1.5 rounded-md bg-gray-50 px-2.5 py-1 text-xs font-medium text-gray-700 transition-colors hover:bg-gray-100 hover:text-gray-900 dark:bg-gray-700/50 dark:text-gray-300 dark:hover:bg-gray-700 dark:hover:text-white"
                                >
                                  {isExpanded ? (
                                    <>
                                      <ChevronUp className="h-3 w-3" />
                                      {t("featuredNews.readLess")}
                                    </>
                                  ) : (
                                    <>
                                      <ChevronDown className="h-3 w-3" />
                                      {t("featuredNews.readMore")}
                                    </>
                                  )}
                                </button>
                              )}
                            </>
                          ) : (
                            <p className="text-sm text-gray-500 dark:text-gray-400 italic">
                              {t("viewDetail.noComment")}
                            </p>
                          )}
                        </div>
                      </div>
                    </li>
                  );
                })}
              </ul>
            </section>
          ))}
        </div>
      </CardContent>
    </Card>
  );
};

export default WorkflowCommentHistory;
