import React, { useEffect, useMemo, useRef, useState } from "react";
import {
  Loader2,
  MessageSquare,
  Pencil,
  RotateCcw,
  Trash2,
} from "lucide-react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";

import { useRecordCollaboratorComments } from "../hooks/useRecordCollaboratorComments";
import { useMyCollaborations } from "../hooks/useMyCollaborations";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { Button } from "@/shared/common/ui/button";
import { Card, CardContent } from "@/shared/common/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import { ScrollArea } from "@/shared/common/ui/scroll-area";
import { Textarea } from "@/shared/common/ui/textarea";
import { Badge } from "@/shared/common/ui/badge";
import { Avatar, AvatarFallback } from "@/shared/common/ui/avatar";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { useAuthUser } from "@/shared/hooks/useAuthUser";

interface CollaborationCommentsDialogProps {
  open: boolean;
  onClose: () => void;
  recordId: string;
  contentId?: string;
  collaborationId?: string;
  recordStatus: string;
}

const formatCommentTime = (
  timestamp: string,
  locale: string,
  fallback: string | null | undefined,
) => {
  if (locale.startsWith("am") && fallback) {
    return fallback;
  }

  const date = new Date(timestamp);
  if (Number.isNaN(date.getTime())) {
    return fallback || "";
  }

  return date.toLocaleString();
};

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

const CollaborationCommentsDialog: React.FC<
  CollaborationCommentsDialogProps
> = ({ open, onClose, recordId, contentId, collaborationId, recordStatus }) => {
  const { t, i18n } = useTranslation();
  const localizedName = useLocalizedName();
  const { handleError } = useErrorHandler(t);
  const { signCollaboration, signStatus } = useMyCollaborations();
  const { selectedPosition, activePositionLookupId } = useAuthUser();
  const {
    comments,
    isLoading,
    isFetching,
    error,
    createComment,
    updateComment,
    deleteComment,
    isCreatingComment,
    isUpdatingComment,
    isDeletingComment,
  } = useRecordCollaboratorComments({
    recordId,
    contentId,
    collaborationId,
    enabled: open,
  });

  const [newComment, setNewComment] = useState("");
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editingText, setEditingText] = useState("");
  const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
  const prevErrorRef = useRef<unknown>(null);
  const currentEmployeePositionId =
    selectedPosition?.employeePositionId ||
    selectedPosition?.id ||
    activePositionLookupId;

  useEffect(() => {
    if (error && error !== prevErrorRef.current) {
      prevErrorRef.current = error;
      void handleError(error);
    }
  }, [error, handleError]);

  useEffect(() => {
    if (!editingId) return;

    const editingComment = comments.find((comment) => comment.id === editingId);
    if (editingComment) {
      setEditingText(editingComment.comment);
    }
  }, [comments, editingId]);

  useEffect(() => {
    if (!open) {
      setNewComment("");
      setEditingId(null);
      setEditingText("");
      setDeleteTargetId(null);
    }
  }, [open]);

  const isBusy = isCreatingComment || isUpdatingComment || isDeletingComment;
  const canManageOwnComment = Boolean(collaborationId);

  const isCommentModificationAllowed =
    collaborationId && recordStatus !== "Dispatched";
  const sortedComments = useMemo(() => comments, [comments]);
  const ownComment = useMemo(
    () =>
      sortedComments.find(
        (comment) =>
          comment.recordCollaborator?.employeePosition?.id ===
          currentEmployeePositionId,
      ) ?? null,
    [currentEmployeePositionId, sortedComments],
  );

  const handleCreate = async () => {
    const comment = newComment.trim();
    if (!comment) {
      toast.error(
        t("collaboration.commentRequired", "Comment cannot be empty."),
      );
      return;
    }

    try {
      await createComment({ recordId, comment });
      setNewComment("");
      toast.success(t("collaboration.commentSubmitted", "Comment submitted."));
    } catch {
      return;
    }
  };

  const handleEditStart = (commentId: string, commentText: string) => {
    setEditingId(commentId);
    setEditingText(commentText);
  };

  const handleEditCancel = () => {
    setEditingId(null);
    setEditingText("");
  };

  const handleUpdate = async () => {
    const comment = editingText.trim();
    if (!editingId || !comment) {
      toast.error(
        t("collaboration.commentRequired", "Comment cannot be empty."),
      );
      return;
    }

    try {
      await updateComment({ id: editingId, comment });
      toast.success(
        t("collaboration.commentUpdated", "Comment updated successfully."),
      );
      setEditingId(null);
      setEditingText("");
    } catch {
      return;
    }
  };

  const handleDelete = async () => {
    if (!deleteTargetId) return;

    try {
      await deleteComment(deleteTargetId);
      toast.success(
        t("collaboration.commentDeleted", "Comment deleted successfully."),
      );
      setDeleteTargetId(null);
      setEditingId(null);
      setEditingText("");
    } catch {
      return;
    }
  };

  const handleAdjust = async (commentText: string) => {
    if (!collaborationId) {
      toast.error(
        t(
          "collaboration.adjustFailed",
          "Failed to send the adjustment request.",
        ),
      );
      return;
    }

    const trimmedComment = commentText.trim();
    if (!trimmedComment) {
      toast.error(
        t(
          "collaboration.adjustCommentMissing",
          "No comment found to use for adjustment.",
        ),
      );
      return;
    }

    try {
      await signCollaboration({
        payload: {
          collabId: collaborationId,
          signStatus: "adjustment_requested",
          comment: trimmedComment,
        },
      });

      toast.success(
        t("collaboration.adjustSubmitted", "Adjustment sent successfully."),
      );
    } catch {
      return;
    }
  };
  return (
    <>
      <Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
        <DialogContent className="sm:max-w-3xl w-full overflow-hidden">
          <DialogHeader>
            <DialogTitle>
              {t("collaboration.commentTitle", "Collaboration comments")}
            </DialogTitle>
            <DialogDescription>
              {t(
                "collaboration.commentDialogDescription",
                "Review all collaborator comments here. If you have not commented yet, you can add yours below.",
              )}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 min-w-0">
            <div className="rounded-2xl border border-border/60 bg-muted/20 p-3 min-w-0">
              <div className="mb-3 flex items-center justify-between gap-3">
                <div className="flex items-center gap-2">
                  <div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                    <MessageSquare className="h-5 w-5" />
                  </div>
                  <div>
                    <p className="text-sm font-semibold">
                      {t("collaboration.comments", "Comments")}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {sortedComments.length === 0
                        ? t(
                            "collaboration.commentsEmpty",
                            "No comments have been added yet.",
                          )
                        : t(
                            "collaboration.commentsCount",
                            "{{count}} comment(s)",
                            { count: sortedComments.length },
                          )}
                    </p>
                  </div>
                </div>
                {(isLoading || isFetching) && (
                  <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
                )}
              </div>

              <ScrollArea className="max-h-[360px] overflow-y-scroll pr-3">
                <div className="space-y-3">
                  {sortedComments.length === 0 && !isLoading ? (
                    <div className="rounded-2xl border border-dashed border-border/70 bg-background/70 px-4 py-8 text-center text-sm text-muted-foreground">
                      {t(
                        "collaboration.commentsEmptyState",
                        "Once collaborators start commenting, their feedback will appear here.",
                      )}
                    </div>
                  ) : (
                    sortedComments.map((comment) => {
                      const isOwnComment =
                        comment.recordCollaborator?.employeePosition?.id ===
                        currentEmployeePositionId;
                      const isEditingThis = editingId === comment.id;
                      const displayName =
                        localizedName(
                          comment.recordCollaborator?.employeePosition?.employee
                            ?.name,
                        ) || t("collaboration.unknownUser", "Unknown user");
                      const updated =
                        Boolean(comment.updatedAt) &&
                        comment.updatedAt !== comment.createdAt;

                      return (
                        <Card
                          key={comment.id}
                          className="overflow-hidden rounded-2xl border border-border/70 bg-background/95 shadow-sm min-w-0"
                        >
                          <div className="h-1 w-full bg-gradient-to-r from-primary/80 via-primary/40 to-transparent" />
                          <CardContent className="space-y-4 p-4 min-w-0">
                            <div className="flex items-start justify-between gap-3">
                              <div className="flex min-w-0 items-center gap-3">
                                <Avatar className="h-10 w-10 border border-primary/10">
                                  <AvatarFallback className="bg-primary/10 text-primary">
                                    {buildInitials(displayName)}
                                  </AvatarFallback>
                                </Avatar>
                                <div className="min-w-0">
                                  <div className="flex flex-wrap items-center gap-2">
                                    <p className="truncate text-sm font-semibold text-foreground">
                                      {displayName}
                                    </p>
                                    {isOwnComment && (
                                      <Badge
                                        variant="secondary"
                                        className="rounded-full"
                                      >
                                        {t(
                                          "collaboration.yourComment",
                                          "Your comment",
                                        )}
                                      </Badge>
                                    )}
                                    {updated && (
                                      <Badge
                                        variant="outline"
                                        className="rounded-full"
                                      >
                                        {t("collaboration.edited", "Edited")}
                                      </Badge>
                                    )}
                                  </div>
                                  <p className="text-xs text-muted-foreground">
                                    {formatCommentTime(
                                      updated
                                        ? comment.updatedAt
                                        : comment.createdAt,
                                      i18n.language,
                                      updated
                                        ? comment.amharicUpdatedAt
                                        : comment.amharicCreatedAt,
                                    )}
                                  </p>
                                </div>
                              </div>

                              {isOwnComment &&
                                !isEditingThis &&
                                canManageOwnComment &&
                                isCommentModificationAllowed && (
                                  <div className="flex items-center gap-2">
                                    <Button
                                      type="button"
                                      variant="outline"
                                      size="sm"
                                      onClick={() =>
                                        void handleAdjust(comment.comment)
                                      }
                                      disabled={isBusy || signStatus.isLoading}
                                      className="gap-2 rounded-full"
                                    >
                                      <RotateCcw className="h-3.5 w-3.5" />
                                      {t("collaboration.adjust", "Adjust")}
                                    </Button>
                                    <Button
                                      type="button"
                                      variant="outline"
                                      size="sm"
                                      onClick={() =>
                                        handleEditStart(
                                          comment.id,
                                          comment.comment,
                                        )
                                      }
                                      disabled={isBusy}
                                      className="gap-2 rounded-full"
                                    >
                                      <Pencil className="h-3.5 w-3.5" />
                                      {t("common.Edit", "Edit")}
                                    </Button>
                                    <Button
                                      type="button"
                                      variant="outline"
                                      size="sm"
                                      onClick={() =>
                                        setDeleteTargetId(comment.id)
                                      }
                                      disabled={isBusy || signStatus.isLoading}
                                      className="gap-2 rounded-full border-red-200 text-red-700 hover:bg-red-50 hover:text-red-700"
                                    >
                                      <Trash2 className="h-3.5 w-3.5" />
                                      {t("common.delete", "Delete")}
                                    </Button>
                                  </div>
                                )}
                            </div>

                            {isEditingThis ? (
                              <div className="space-y-3">
                                <Textarea
                                  value={editingText}
                                  onChange={(e) =>
                                    setEditingText(e.target.value)
                                  }
                                  rows={4}
                                  placeholder={t(
                                    "collaboration.commentPlaceholder",
                                    "Write your comment...",
                                  )}
                                  className="w-full max-w-full resize-none [field-sizing:fixed] break-all"
                                />
                                <div className="flex justify-end gap-2">
                                  <Button
                                    type="button"
                                    variant="outline"
                                    onClick={handleEditCancel}
                                    disabled={isUpdatingComment}
                                  >
                                    {t("common.cancel", "Cancel")}
                                  </Button>
                                  <Button
                                    type="button"
                                    onClick={handleUpdate}
                                    disabled={isUpdatingComment}
                                  >
                                    {isUpdatingComment && (
                                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                    )}
                                    {t("common.save", "Save")}
                                  </Button>
                                </div>
                              </div>
                            ) : (
                              <p className="whitespace-pre-wrap break-all text-sm leading-6 text-muted-foreground min-w-0">
                                {comment.comment}
                              </p>
                            )}
                          </CardContent>
                        </Card>
                      );
                    })
                  )}
                </div>
              </ScrollArea>
            </div>

            {!ownComment &&
              !isLoading &&
              canManageOwnComment &&
              isCommentModificationAllowed && (
                <div className="rounded-2xl border border-border/60 bg-background p-4 shadow-sm">
                  <div className="mb-3">
                    <p className="text-sm font-semibold">
                      {t("collaboration.addComment", "Add your comment")}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {t(
                        "collaboration.singleCommentRule",
                        "You can submit one comment for the current record version.",
                      )}
                    </p>
                  </div>
                  <Textarea
                    value={newComment}
                    onChange={(e) => setNewComment(e.target.value)}
                    rows={4}
                    placeholder={t(
                      "collaboration.commentPlaceholder",
                      "Write your comment...",
                    )}
                    disabled={isCreatingComment}
                    className="w-full max-w-full resize-none [field-sizing:fixed] break-all"
                  />
                  <div className="mt-3 flex justify-end">
                    <Button
                      type="button"
                      onClick={handleCreate}
                      disabled={isCreatingComment}
                      className="min-w-32"
                    >
                      {isCreatingComment && (
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      )}
                      {t("collaboration.postComment", "Post comment")}
                    </Button>
                  </div>
                </div>
              )}
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>
              {t("collaboration.close", "Close")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <AlertDialog
        open={Boolean(deleteTargetId)}
        onOpenChange={(nextOpen) => !nextOpen && setDeleteTargetId(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {t("collaboration.deleteCommentTitle", "Delete comment?")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t(
                "collaboration.deleteCommentDescription",
                "This will remove your current comment. You can add a fresh one again afterward.",
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeletingComment}>
              {t("common.cancel", "Cancel")}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={isDeletingComment}
              className="bg-red-600 hover:bg-red-700"
            >
              {isDeletingComment && (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              )}
              {t("common.delete", "Delete")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};

export default CollaborationCommentsDialog;
