import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
  MessageSquare,
  Clock,
  Pencil,
  Trash2,
  AlertTriangle,
  Loader2,
} from "lucide-react";
import { Card, CardContent } from "@/shared/common/ui/card";
import { Button } from "@/shared/common/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/common/ui/dialog";
import FileList from "@/record-management/common/fileListComponent";
import { ReplyModal } from "@/record-management/common/ReplyModal";
import type { ReplyToEdit } from "@/record-management/common/ReplyModal";
import { deleteReplies } from "../services/api/recordOfficerService";
import { useLocalizedName } from "@/shared/common/localizedName";

interface ReplySectionProps {
  recordId: string;
  replies: any[];
  isRecordOfficer: boolean;
  onRefresh: () => void;
  isAddOpen: boolean;
  onCloseAdd: () => void;
}

export const ReplySection: React.FC<ReplySectionProps> = ({
  recordId,
  replies,
  isRecordOfficer,
  onRefresh,
  isAddOpen,
  onCloseAdd,
}) => {
  const { t, i18n } = useTranslation();
  const [isAddReplyModalOpen, setIsAddReplyModalOpen] = useState(false);
  const [replyToEdit, setReplyToEdit] = useState<ReplyToEdit | null>(null);
  const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
  const [replyToDeleteId, setReplyToDeleteId] = useState<string | null>(null);
  const [isDeletingReply, setIsDeletingReply] = useState(false);
  const localizedName = useLocalizedName();
  const lang = i18n.language;
  // Sync isAddOpen prop to internal state
  useEffect(() => {
    if (isAddOpen) {
      setReplyToEdit(null);
      setIsAddReplyModalOpen(true);
    }
  }, [isAddOpen]);

  const handleEditReply = (reply: any) => {
    setReplyToEdit({
      id: reply.id,
      comment: reply.comment,
      attachment: reply.attachment || null,
      attachments:
        reply.attachments?.map((att: any) => ({
          fileInfo: {
            bucket: att.fileInfo?.bucket || "",
            fileName: att.fileInfo?.fileName || att.name,
            contentType: att.fileInfo?.contentType || att.type || "",
            originalname: att.fileInfo?.originalname || att.name || "",
            size: att.fileInfo?.size || att.size || 0,
          },
          name: att.name || {
            am: att.fileInfo?.originalname || "",
            en: att.fileInfo?.originalname || "",
          },
        })) ?? [],
    });
    setIsAddReplyModalOpen(true);
  };

  const handleDeleteReply = async () => {
    if (!replyToDeleteId) return;
    setIsDeletingReply(true);
    try {
      await deleteReplies(replyToDeleteId);
      toast.success(t("msg.replyDeleted", "Reply deleted successfully!"));
      onRefresh();
    } catch (err: any) {
      const serverMessage =
        err?.response?.data?.message || err?.message || null;
      toast.error(
        serverMessage ?? t("msg.replyDeleteError", "Failed to delete reply."),
      );
    } finally {
      setIsDeletingReply(false);
      setIsDeleteConfirmOpen(false);
      setReplyToDeleteId(null);
    }
  };

  const confirmDeleteReply = (replyId: string) => {
    setReplyToDeleteId(replyId);
    setIsDeleteConfirmOpen(true);
  };

  const handleModalClose = () => {
    setIsAddReplyModalOpen(false);
    setReplyToEdit(null);
    onCloseAdd();
  };

  return (
    <div className="space-y-4">
      <Card className="border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800">
        <CardContent className="p-0">
          <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">
              <MessageSquare className="h-5 w-5 text-primary" />
              <h3 className="font-semibold text-gray-900 dark:text-white">
                {t("common.replies", "Replies")}{" "}
                {replies?.length > 0 && `(${replies.length})`}
              </h3>
            </div>
          </div>

          <div className="p-4">
            {replies?.length > 0 ? (
              <ul className="relative space-y-4 border-l-2 border-gray-200 pl-5 dark:border-gray-700">
                {replies.map((reply: any) => {
                  const nameStr = reply.employeePosition?.employee.name
                    ? localizedName(reply.employeePosition?.employee.name)
                    : "";
                  const initials = nameStr
                    ? nameStr
                        .split(" ")
                        .filter(Boolean)
                        .slice(0, 2)
                        .map((n: string) => n[0].toUpperCase())
                        .join("")
                    : "RO";

                  return (
                    <li key={reply.id} className="relative">
                      <span className="absolute -left-[27px] top-1 h-3 w-3 rounded-full bg-primary 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">
                                  {localizedName(
                                    reply.employeePosition?.employee.name,
                                  )}
                                </span>
                                <span className="text-xs text-gray-500 dark:text-gray-400">
                                  (
                                  {localizedName(
                                    reply.employeePosition?.position.name,
                                  )}
                                  )
                                </span>
                              </div>
                              <div className="mt-1 flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400">
                                <Clock className="h-3 w-3" />
                                <span>
                                  {lang === "en"
                                    ? new Date(reply.updatedAt).toLocaleString()
                                    : reply.amharicUpdatedAt ||
                                      new Date(
                                        reply.updatedAt,
                                      ).toLocaleString()}
                                </span>
                              </div>
                            </div>
                          </div>

                          {/* Edit / Delete buttons — RO only */}
                          {isRecordOfficer && (
                            <div className="flex items-center gap-1 shrink-0">
                              <button
                                type="button"
                                onClick={() => handleEditReply(reply)}
                                className="p-1.5 rounded-md text-gray-400 hover:text-primary-600 hover:bg-primary-50 dark:hover:bg-primary-900/20 transition-colors"
                                title={t("common.edit", "Edit")}
                              >
                                <Pencil className="h-4 w-4" />
                              </button>
                              <button
                                type="button"
                                onClick={() => confirmDeleteReply(reply.id)}
                                className="p-1.5 rounded-md text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
                                title={t("common.delete", "Delete")}
                              >
                                <Trash2 className="h-4 w-4" />
                              </button>
                            </div>
                          )}
                        </header>

                        <div className="p-3 space-y-3">
                          <div>
                            <p className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-1">
                              {t("common.comment", "Comment")}
                            </p>
                            <p className="whitespace-pre-wrap break-words text-sm leading-relaxed text-gray-700 dark:text-gray-200">
                              {reply.comment}
                            </p>
                          </div>

                          {(reply.attachment) && (
                            <div className="pt-2 border-t border-gray-100 dark:border-gray-700 space-y-2">
                              <p className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                                {t(
                                  "common.replyAttachments",
                                  "Reply Attachments",
                                )}
                              </p>
                              <FileList
                                attachments={[reply.attachment]}
                                showDelete={false}
                              />
                            </div>
                          )}
                        </div>
                      </div>
                    </li>
                  );
                })}
              </ul>
            ) : (
              <div className="text-center p-6 border-2 border-dashed border-gray-200 dark:border-gray-700 rounded-lg">
                <MessageSquare className="h-10 w-10 text-gray-400 dark:text-gray-500 mx-auto mb-2" />
                <p className="text-sm text-gray-500 dark:text-gray-400 italic">
                  {t("common.noReplies", "No replies added yet.")}
                </p>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {recordId && (
        <ReplyModal
          isOpen={isAddReplyModalOpen}
          onClose={handleModalClose}
          recordId={recordId}
          onSuccess={onRefresh}
          replyToEdit={replyToEdit}
        />
      )}

      {/* Delete Confirmation Dialog */}
      <Dialog
        open={isDeleteConfirmOpen}
        onOpenChange={(open) => {
          if (!open && !isDeletingReply) {
            setIsDeleteConfirmOpen(false);
            setReplyToDeleteId(null);
          }
        }}
      >
        <DialogContent className="max-w-sm bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 shadow-2xl p-6 rounded-xl">
          <DialogHeader>
            <DialogTitle className="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
              <AlertTriangle className="h-5 w-5 text-red-500" />
              {t("common.confirmDelete", "Confirm Delete")}
            </DialogTitle>
          </DialogHeader>
          <p className="text-sm text-gray-600 dark:text-gray-300 py-3">
            {t(
              "common.deleteReplyConfirmation",
              "Are you sure you want to delete this reply? This action cannot be undone.",
            )}
          </p>
          <DialogFooter className="gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setIsDeleteConfirmOpen(false);
                setReplyToDeleteId(null);
              }}
              disabled={isDeletingReply}
            >
              {t("common.cancel", "Cancel")}
            </Button>
            <Button
              type="button"
              onClick={handleDeleteReply}
              disabled={isDeletingReply}
              className="bg-red-600 hover:bg-red-700 text-white"
            >
              {isDeletingReply ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin mr-2" />
                  {t("common.deleting", "Deleting...")}
                </>
              ) : (
                <>
                  <Trash2 className="h-4 w-4 mr-2" />
                  {t("common.delete", "Delete")}
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};
