import React, { useState } from "react";
import { ForumComment } from "../types";
import CommentForm from "./CommentForm";
import ForumImageUpload from "./ForumImageUpload";
import { getImageUrl } from "../services/uploadService";
import { IMAGE_LIMITS } from "../config/imageLimits";

interface CommentThreadProps {
  comment: ForumComment;
  onReply: (commentId: string, content: string, images?: File[]) => Promise<void>;
  onEdit?: (commentId: string, content: string, existingImageKeys: string[], newImageFiles: File[]) => Promise<void>;
  onDelete?: (commentId: string) => Promise<void>;
  onMarkAsAnswer?: (commentId: string) => Promise<void>;
  currentUserId?: string;
  isPostAuthor?: boolean;
  acceptedAnswerId?: string;
  depth?: number;
  isAdmin?: boolean;
  onAdminDelete?: (commentId: string) => Promise<void>;
  onAdminRestore?: (commentId: string) => Promise<void>;
  canReply?: boolean;
}

const CommentThread: React.FC<CommentThreadProps> = ({
  comment,
  onReply,
  onEdit,
  onDelete,
  onMarkAsAnswer,
  currentUserId,
  isPostAuthor = false,
  acceptedAnswerId,
  depth = 0,
  isAdmin = false,
  onAdminDelete,
  onAdminRestore,
  canReply = true,
}) => {
  const [showReplyForm, setShowReplyForm] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editContent, setEditContent] = useState(comment.content);
  const [isCollapsed, setIsCollapsed] = useState(false);

  // Image editing state
  const [existingImageKeys, setExistingImageKeys] = useState<string[]>([]);
  const [editImageFiles, setEditImageFiles] = useState<File[]>([]);
  const [editImagePreviews, setEditImagePreviews] = useState<string[]>([]);

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMinutes = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMinutes / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffMinutes < 1) {
      return "Just now";
    } else if (diffMinutes < 60) {
      return `${diffMinutes}m ago`;
    } else if (diffHours < 24) {
      return `${diffHours}h ago`;
    } else if (diffDays < 7) {
      return `${diffDays}d ago`;
    } else {
      return date.toLocaleDateString();
    }
  };

  const handleReply = async (content: string, images: File[]) => {
    await onReply(comment.id, content, images);
    setShowReplyForm(false);
  };

  const startEditing = () => {
    setIsEditing(true);
    setEditContent(comment.content);
    const existingKeys = comment.imageFilenames || [];
    setExistingImageKeys(existingKeys);
    setEditImagePreviews(existingKeys.map((key) => getImageUrl(key, 'thumbnail')));
    setEditImageFiles([]);
  };

  const cancelEditing = () => {
    setIsEditing(false);
    setEditContent(comment.content);
    setExistingImageKeys([]);
    setEditImageFiles([]);
    setEditImagePreviews([]);
  };

  const handleEditImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    const totalImages = existingImageKeys.length + editImageFiles.length;
    const remainingSlots = IMAGE_LIMITS.forum - totalImages;
    const filesToAdd = files.slice(0, remainingSlots);

    setEditImageFiles((prev) => [...prev, ...filesToAdd]);

    filesToAdd.forEach((file) => {
      const reader = new FileReader();
      reader.onloadend = () => {
        setEditImagePreviews((prev) => [...prev, reader.result as string]);
      };
      reader.readAsDataURL(file);
    });

    e.target.value = "";
  };

  const handleRemoveEditImage = (index: number) => {
    if (index < existingImageKeys.length) {
      // Removing an existing S3 image
      setExistingImageKeys((prev) => prev.filter((_, i) => i !== index));
    } else {
      // Removing a new upload
      const newFileIndex = index - existingImageKeys.length;
      setEditImageFiles((prev) => prev.filter((_, i) => i !== newFileIndex));
    }
    setEditImagePreviews((prev) => prev.filter((_, i) => i !== index));
  };

  const handleEdit = async () => {
    if (onEdit && editContent.trim()) {
      await onEdit(comment.id, editContent, existingImageKeys, editImageFiles);
      setIsEditing(false);
      setExistingImageKeys([]);
      setEditImageFiles([]);
      setEditImagePreviews([]);
    } else {
      cancelEditing();
    }
  };

  const handleDelete = async () => {
    if (
      onDelete &&
      window.confirm("Are you sure you want to delete this comment?")
    ) {
      await onDelete(comment.id);
    }
  };

  const isAuthor = currentUserId === comment.authorId;
  const maxDepth = 5;
  const canNest = depth < maxDepth;
  const isAcceptedAnswer = acceptedAnswerId === comment.id;
  const canMarkAsAnswer =
    isPostAuthor && depth === 0 && onMarkAsAnswer && !comment.isDeleted;

  const handleMarkAsAnswer = async () => {
    if (onMarkAsAnswer) {
      await onMarkAsAnswer(comment.id);
    }
  };

  if (comment.isDeleted && !isAdmin) {
    return (
      <div className={`comment-deleted ${depth > 0 ? "ms-4" : ""} mb-3`}>
        <div className="card bg-light">
          <div className="card-body py-2">
            <small className="text-muted fst-italic">[Comment deleted]</small>
          </div>
        </div>
        {comment.replies && comment.replies.length > 0 && (
          <div className="replies mt-2">
            {comment.replies.map((reply) => (
              <CommentThread
                key={reply.id}
                comment={reply}
                onReply={onReply}
                onEdit={onEdit}
                onDelete={onDelete}
                onMarkAsAnswer={onMarkAsAnswer}
                currentUserId={currentUserId}
                isPostAuthor={isPostAuthor}
                acceptedAnswerId={acceptedAnswerId}
                depth={depth + 1}
                isAdmin={isAdmin}
                onAdminDelete={onAdminDelete}
                onAdminRestore={onAdminRestore}
              />
            ))}
          </div>
        )}
      </div>
    );
  }

  return (
    <div className={`comment ${depth > 0 ? "ms-4" : ""} mb-3`}>
      <div className={`card ${isAcceptedAnswer ? "border-success" : ""} ${comment.isDeleted && isAdmin ? "border-danger" : ""}`}>
        <div className="card-body">
          {comment.isDeleted && isAdmin && (
            <div className="alert alert-danger alert-sm py-1 px-2 mb-2">
              <small>
                <i className="bi bi-trash me-1"></i>
                <strong>Deleted by Admin</strong>
                {comment.deletedAt && ` on ${formatDate(comment.deletedAt)}`}
              </small>
            </div>
          )}
          {isAcceptedAnswer && (
            <div className="mb-2">
              <span className="badge bg-success">
                <i className="bi bi-check-circle-fill me-1"></i>
                Answer
              </span>
            </div>
          )}
          <div className="d-flex justify-content-between align-items-start mb-2">
            <div className="d-flex align-items-center">
              <div
                className="avatar bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2"
                style={{ width: "32px", height: "32px", fontSize: "14px" }}
              >
                {comment.author?.firstName?.charAt(0) || "?"}
              </div>
              <div>
                <strong className="d-block">
                  {comment.author?.firstName || "Unknown"}{" "}
                  {comment.author?.lastName || ""}
                </strong>
                <small className="text-muted">
                  {formatDate(comment.createdAt)}
                  {comment.updatedAt !== comment.createdAt && " (edited)"}
                </small>
              </div>
            </div>
            {comment.replies && comment.replies.length > 0 && (
              <button
                className="btn btn-sm btn-link text-decoration-none"
                onClick={() => setIsCollapsed(!isCollapsed)}
              >
                <i
                  className={`bi bi-chevron-${isCollapsed ? "down" : "up"}`}
                ></i>
              </button>
            )}
          </div>

          {isEditing ? (
            <div className="mb-2">
              <textarea
                className="form-control mb-2"
                rows={3}
                value={editContent}
                onChange={(e) => setEditContent(e.target.value)}
              />
              <ForumImageUpload
                imageFiles={editImageFiles}
                imagePreviews={editImagePreviews}
                onImageChange={handleEditImageChange}
                onRemoveImage={handleRemoveEditImage}
                compact={true}
              />
              <div className="d-flex gap-2 mt-2">
                <button
                  className="btn btn-sm btn-primary"
                  onClick={handleEdit}
                  disabled={!editContent.trim()}
                >
                  Save
                </button>
                <button
                  className="btn btn-sm btn-secondary"
                  onClick={cancelEditing}
                >
                  Cancel
                </button>
              </div>
            </div>
          ) : (
            <>
              <p className="card-text mb-2" style={{ whiteSpace: "pre-wrap" }}>
                {comment.content}
              </p>
              {comment.imageFilenames && comment.imageFilenames.length > 0 && (
                <div className="row g-2 mb-2">
                  {comment.imageFilenames.map((image, index) => (
                    <div key={index} className="col-4 col-md-3">
                      <img
                        src={getImageUrl(image, 'thumbnail')}
                        alt={`Comment image`}
                        className="img-fluid rounded"
                        style={{
                          width: "100%",
                          maxHeight: "300px",
                          objectFit: "contain",
                          cursor: "pointer",
                        }}
                        onError={(e) => {
                          const target = e.currentTarget;
                          if (!target.dataset.fallback) {
                            target.dataset.fallback = 'true';
                            target.src = getImageUrl(image, 'original');
                          }
                        }}
                        onClick={() =>
                          window.open(getImageUrl(image, 'original'), "_blank")
                        }
                      />
                    </div>
                  ))}
                </div>
              )}
            </>
          )}

          <div className="d-flex gap-2">
            {!isEditing && canNest && canReply && (
              <button
                className="btn btn-sm btn-link text-decoration-none p-0"
                onClick={() => setShowReplyForm(!showReplyForm)}
              >
                <i className="bi bi-reply me-1"></i>
                Reply
              </button>
            )}
            {canMarkAsAnswer && !isEditing && (
              <button
                className={`btn btn-sm btn-link text-decoration-none p-0 ${
                  isAcceptedAnswer ? "text-success" : "text-success"
                }`}
                onClick={handleMarkAsAnswer}
              >
                <i
                  className={`bi ${
                    isAcceptedAnswer
                      ? "bi-check-circle-fill"
                      : "bi-check-circle"
                  } me-1`}
                ></i>
                {isAcceptedAnswer ? "Unmark Answer" : "Mark as Answer"}
              </button>
            )}
            {isAuthor && onEdit && !isEditing && (
              <button
                className="btn btn-sm btn-link text-decoration-none p-0"
                onClick={startEditing}
              >
                <i className="bi bi-pencil me-1"></i>
                Edit
              </button>
            )}
            {isAuthor && onDelete && !isEditing && (
              <button
                className="btn btn-sm btn-link text-danger text-decoration-none p-0"
                onClick={handleDelete}
              >
                <i className="bi bi-trash me-1"></i>
                Delete
              </button>
            )}
            {isAdmin && onAdminDelete && !comment.isDeleted && !isEditing && (
              <button
                className="btn btn-sm btn-link text-danger text-decoration-none p-0"
                onClick={() => onAdminDelete(comment.id)}
              >
                <i className="bi bi-trash me-1"></i>
                Delete (Admin)
              </button>
            )}
            {isAdmin && onAdminRestore && comment.isDeleted && !isEditing && (
              <button
                className="btn btn-sm btn-link text-success text-decoration-none p-0"
                onClick={() => onAdminRestore(comment.id)}
              >
                <i className="bi bi-arrow-counterclockwise me-1"></i>
                Restore (Admin)
              </button>
            )}
          </div>
        </div>
      </div>

      {showReplyForm && (
        <div className="mt-2">
          <CommentForm
            onSubmit={handleReply}
            onCancel={() => setShowReplyForm(false)}
            placeholder="Write your reply..."
            buttonText="Post Reply"
            isReply={true}
          />
        </div>
      )}

      {!isCollapsed && comment.replies && comment.replies.length > 0 && (
        <div className="replies mt-2">
          {comment.replies.map((reply) => (
            <CommentThread
              key={reply.id}
              comment={reply}
              onReply={onReply}
              onEdit={onEdit}
              onDelete={onDelete}
              onMarkAsAnswer={onMarkAsAnswer}
              currentUserId={currentUserId}
              isPostAuthor={isPostAuthor}
              acceptedAnswerId={acceptedAnswerId}
              depth={depth + 1}
              isAdmin={isAdmin}
              onAdminDelete={onAdminDelete}
              onAdminRestore={onAdminRestore}
              canReply={canReply}
            />
          ))}
        </div>
      )}
    </div>
  );
};

export default CommentThread;
