import React, { useMemo } from "react";
import { AlertCircle, Clock3, MessageSquareText, Users } from "lucide-react";
import { useTranslation } from "react-i18next";

import { useCollaborationByRecordId } from "../hooks/useMyCollaborations";
import { renderStatus } from "@/record-management/utils/renderDetails";
import { useLocalizedName } from "@/shared/common/localizedName";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import { ScrollArea } from "@/shared/common/ui/scroll-area";
import { Separator } from "@/shared/common/ui/separator";

interface TeamRecordCollaborationDetailsDialogProps {
  open: boolean;
  onClose: () => void;
  recordId: string;
}

const TeamRecordCollaborationDetailsDialog: React.FC<
  TeamRecordCollaborationDetailsDialogProps
> = ({ open, onClose, recordId }) => {
  const { t, i18n } = useTranslation();
  const localizedName = useLocalizedName();
  const { data, isLoading, error } = useCollaborationByRecordId(recordId, {
    enabled: open && !!recordId,
  });

  const items = data?.items ?? [];
  const signedCount = useMemo(
    () => items.filter((item) => item.signStatus === "signed").length,
    [items],
  );
  const pendingCount = useMemo(
    () =>
      items.filter((item) => !item.signStatus || item.signStatus === "draft")
        .length,
    [items],
  );
  const rejectedCount = useMemo(
    () => items.filter((item) => item.signStatus === "rejected").length,
    [items],
  );
  const adjustmentCount = useMemo(
    () =>
      items.filter((item) => item.signStatus === "adjustment_requested").length,
    [items],
  );
  const commentCount = useMemo(
    () => items.filter((item) => Boolean(item.comment?.trim())).length,
    [items],
  );
  const reviewedCount = useMemo(
    () =>
      items.filter(
        (item) =>
          item.signStatus === "signed" ||
          item.signStatus === "rejected" ||
          item.signStatus === "team_rejected" ||
          item.signStatus === "adjustment_requested" ||
          Boolean(item.comment?.trim()),
      ).length,
    [items],
  );

  const formatActionDate = (
    signedAt?: string | null,
    amharicSignedAt?: string | null,
  ) => {
    if (i18n.language.startsWith("am") && amharicSignedAt) {
      return amharicSignedAt;
    }

    if (!signedAt) {
      return t("common.notAvailable", "Not Available");
    }

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

    return date.toLocaleString();
  };

  const getLocalizedLabel = (name?: { am?: string; en?: string }) =>
    name
      ? localizedName({
          am: name.am ?? "",
          en: name.en ?? "",
        })
      : "";

  const getCollaboratorName = (item: (typeof items)[number]) =>
    getLocalizedLabel(item.employeePosition?.employee?.name) ||
    item.employeePosition?.employee?.id ||
    item.userId ||
    t("common.unknownUser", "Unknown user");

  const getPositionName = (item: (typeof items)[number]) =>
    getLocalizedLabel(item.employeePosition?.position?.name) ||
    item.employeePositionId ||
    t("common.notAvailable", "Not Available");

  return (
    <Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
      <DialogContent className="sm:max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {t("header.navigation.collaboration")} {t("userRecord.View Detail")}
          </DialogTitle>
          <DialogDescription>
            {t(
              "collaboration.detailsDescription",
              "Review each collaborator, their current action status, and any comment they left on this record.",
            )}
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
          <div className="rounded-lg border bg-slate-50 p-4">
            <div className="flex items-center gap-3">
              <Users className="h-4 w-4 text-slate-600" />
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-slate-500">
                  {t("viewDetail.collaborators", "Collaborators")}
                </p>
                <p className="text-2xl font-semibold text-slate-900">
                  {items.length}
                </p>
              </div>
            </div>
          </div>
          <div className="rounded-lg border bg-primary-50 p-4">
            <div className="flex items-center gap-3">
              <div className="h-3 w-3 rounded-full bg-primary-500" />
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-slate-500">
                  {t("statusBar.signed", "Signed")}
                </p>
                <p className="text-2xl font-semibold text-slate-900">
                  {signedCount}
                </p>
              </div>
            </div>
          </div>
          <div className="rounded-lg border bg-amber-50 p-4">
            <div className="flex items-center gap-3">
              <Clock3 className="h-4 w-4 text-amber-700" />
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-slate-500">
                  {t("statusBar.InProgress", "Pending")}
                </p>
                <p className="text-2xl font-semibold text-slate-900">
                  {pendingCount}
                </p>
              </div>
            </div>
          </div>
          <div className="rounded-lg border bg-rose-50 p-4">
            <div className="flex items-center gap-3">
              <AlertCircle className="h-4 w-4 text-rose-700" />
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-slate-500">
                  {t("statusBar.Rejected", "Rejected")}
                </p>
                <p className="text-2xl font-semibold text-slate-900">
                  {rejectedCount}
                </p>
              </div>
            </div>
          </div>
          <div className="rounded-lg border bg-amber-50 p-4">
            <div className="flex items-center gap-3">
              <Clock3 className="h-4 w-4 text-amber-700" />
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-slate-500">
                  {t("statusBar.AdjustmentRequested", "Adjustment Requested")}
                </p>
                <p className="text-2xl font-semibold text-slate-900">
                  {adjustmentCount}
                </p>
              </div>
            </div>
          </div>
        </div>

        {isLoading ? (
          <div className="flex min-h-56 items-center justify-center rounded-lg border border-dashed text-sm text-slate-500">
            {t("common.loading", "Loading")}
          </div>
        ) : error ? (
          <div className="flex min-h-56 flex-col items-center justify-center gap-3 rounded-lg border border-red-200 bg-red-50 px-6 text-center">
            <AlertCircle className="h-6 w-6 text-red-600" />
            <p className="text-sm text-red-700">
              {error instanceof Error
                ? error.message
                : t("msg.error", "Failed to load collaborations")}
            </p>
          </div>
        ) : items.length === 0 ? (
          <div className="flex min-h-56 flex-col items-center justify-center gap-3 rounded-lg border border-dashed text-center">
            <Users className="h-6 w-6 text-slate-400" />
            <p className="text-sm text-slate-500">{t("msg.noMsg")}</p>
          </div>
        ) : (
          <ScrollArea className="max-h-[65vh] rounded-lg border">
            <div className="divide-y">
              {items.map((item) => (
                <div key={item.id} className="space-y-4 p-4">
                  <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                    <div className="space-y-1">
                      <div className="font-medium text-slate-900">
                        {getCollaboratorName(item)}
                      </div>
                      {/* <div className="text-sm text-slate-500">
                        {getPositionName(item)}
                      </div> */}
                    </div>
                    <div>{renderStatus(item.signStatus, item.signStatus)}</div>
                  </div>

                  <Separator />

                  <div className="space-y-2">
                    <div className="flex items-center gap-2 text-sm font-medium text-slate-700">
                      <MessageSquareText className="h-4 w-4" />
                      {t("collaboration.comments", "Comments")}
                    </div>
                    <div className="rounded-md border bg-white p-3 text-sm text-slate-700">
                      {item.comment?.trim() ||
                        t("userRecord.noComment", "No Comment")}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </ScrollArea>
        )}

        {items.length > 0 && (
          <div className="text-xs text-slate-500">
            {t(
              "collaboration.reviewedCount",
              "{{count}} collaborator(s) reviewed",
              {
                count: reviewedCount,
              },
            )}
          </div>
        )}
        {items.length > 0 && (
          <div className="text-xs text-slate-500">
            {t("collaboration.commentsCount", "{{count}} comment(s)", {
              count: commentCount,
            })}
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
};

export default TeamRecordCollaborationDetailsDialog;
