"use client";

import { useState } from "react";
import { formatDistanceToNow } from "date-fns";
import { User, MoreHorizontal, Edit2, Trash2, Check, X } from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { FileAttachments } from "@/components/ui/file-attachments";
import { FileUpload } from "@/components/ui/file-upload";
import { RichTextEditor } from "@/components/ui/rich-text-editor";

import { useConfirm } from "@/hooks/use-confirm";
import { useCurrent } from "@/features/auth/api/use-curent";
import { useUpdateComment } from "../api/use-update-comment";
import { useDeleteComment } from "../api/use-delete-comment";
import { useMembersForMentions } from "@/features/members/hooks/use-members-for-mentions";
import { useWorkspaceId } from "@/features/workspaces/hooks/use-workspace-id";

interface CommentItemProps {
  comment: {
    id: string;
    content: string;
    attachments?: string[];
    createdAt: string | Date;
    updatedAt?: string | Date;
    author: {
      id: string;
      name?: string | null;
      email: string;
      image?: string | null;
    };
  };
  taskId: string;
}

export const CommentItem = ({ comment, taskId }: CommentItemProps) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editContent, setEditContent] = useState(comment.content);
  const [editAttachments, setEditAttachments] = useState<string[]>(comment.attachments || []);
  
  const { data: currentUser } = useCurrent();
  const { mutate: updateComment, isPending: isUpdating } = useUpdateComment();
  const { mutate: deleteComment, isPending: isDeleting } = useDeleteComment();
  const workspaceId = useWorkspaceId();
  const { members: mentionableMembers } = useMembersForMentions({ workspaceId });
  
  const [DeleteDialog, confirmDelete] = useConfirm(
    "Delete Comment",
    "Are you sure you want to delete this comment? This action cannot be undone.",
    "destructive"
  );

  const createdAt = typeof comment.createdAt === 'string' 
    ? new Date(comment.createdAt) 
    : comment.createdAt;

  const timeAgo = formatDistanceToNow(createdAt, { addSuffix: true });
  const authorName = comment.author.name || comment.author.email;
  const authorInitials = authorName
    .split(' ')
    .map(n => n[0])
    .join('')
    .toUpperCase()
    .slice(0, 2);

  const isOwner = currentUser?.id === comment.author.id;

  const handleEdit = () => {
    setIsEditing(true);
    setEditContent(comment.content);
    setEditAttachments(comment.attachments || []);
  };

  const handleCancelEdit = () => {
    setIsEditing(false);
    setEditContent(comment.content);
    setEditAttachments(comment.attachments || []);
  };

  const handleSaveEdit = () => {
    if (!editContent.trim() && editAttachments.length === 0) {
      return;
    }

    updateComment({
      json: { content: editContent.trim(), attachments: editAttachments },
      param: { taskId, commentId: comment.id },
    }, {
      onSuccess: () => {
        setIsEditing(false);
      }
    });
  };

  const handleDelete = async () => {
    const ok = await confirmDelete();
    if (!ok) return;

    deleteComment({
      param: { taskId, commentId: comment.id },
    });
  };

  return (
    <>
      <DeleteDialog />
      <div className="flex gap-3 group p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
        <Avatar className="h-9 w-9 flex-shrink-0 ring-2 ring-white shadow-sm">
          <AvatarImage src={comment.author.image || undefined} />
          <AvatarFallback className="text-xs font-semibold bg-blue-100 text-blue-700">
            {comment.author.image ? (
              <User className="h-4 w-4" />
            ) : (
              authorInitials
            )}
          </AvatarFallback>
        </Avatar>
        
        <div className="flex-1 space-y-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="text-sm font-semibold text-gray-900">
                {authorName}
              </span>
              <span className="text-xs text-gray-500 bg-white px-2 py-1 rounded-full">
                {timeAgo}
              </span>
              {comment.updatedAt && new Date(comment.createdAt).getTime() !== new Date(comment.updatedAt).getTime() && (
                <span className="text-xs text-gray-400 italic">
                  (edited)
                </span>
              )}
            </div>
            
            {isOwner && !isEditing && (
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-8 w-8 p-0 opacity-0 group-hover:opacity-100 transition-opacity"
                  >
                    <MoreHorizontal className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem onClick={handleEdit}>
                    <Edit2 className="h-4 w-4 mr-2" />
                    Edit
                  </DropdownMenuItem>
                  <DropdownMenuItem 
                    onClick={handleDelete}
                    className="text-destructive focus:text-destructive"
                    disabled={isDeleting}
                  >
                    <Trash2 className="h-4 w-4 mr-2" />
                    {isDeleting ? "Deleting..." : "Delete"}
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            )}
          </div>
          
          {/* Rich Text Comment Content */}
          {isEditing ? (
            <div className="space-y-3">
              <div className="border rounded-lg">
                <RichTextEditor
                  key={`comment-edit-${comment.id}`}
                  content={editContent}
                  onChange={setEditContent}
                  placeholder="Edit your comment..."
                  editable={true}
                  className="min-h-[100px]"
                  members={mentionableMembers}
                  workspaceId={workspaceId}
                />
              </div>
              
              {/* File Upload for Edit */}
              <FileUpload
                value={editAttachments}
                onChange={setEditAttachments}
                disabled={isUpdating}
                placeholder="Drop files here or click to attach"
                className="border-dashed border-gray-300"
              />
              
              <div className="flex gap-2 justify-end">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={handleCancelEdit}
                  disabled={isUpdating}
                >
                  <X className="h-4 w-4 mr-1" />
                  Cancel
                </Button>
                <Button
                  size="sm"
                  onClick={handleSaveEdit}
                  disabled={isUpdating || (!editContent.trim() && editAttachments.length === 0)}
                >
                  <Check className="h-4 w-4 mr-1" />
                  {isUpdating ? "Saving..." : "Save"}
                </Button>
              </div>
            </div>
          ) : (
            <div className="bg-white p-3 rounded-lg border prose prose-sm max-w-none">
              <RichTextEditor
                key={`comment-${comment.id}`}
                content={comment.content}
                onChange={() => {}}
                editable={false}
                className="border-0 p-0 [&_.ProseMirror]:p-0 [&_.ProseMirror]:m-0 [&_.ProseMirror]:min-h-0 [&_.ProseMirror_p]:my-1 [&_.ProseMirror_h1]:mt-3 [&_.ProseMirror_h1]:mb-2 [&_.ProseMirror_h2]:mt-3 [&_.ProseMirror_h2]:mb-2 [&_.ProseMirror_h3]:mt-2 [&_.ProseMirror_h3]:mb-1 [&_.ProseMirror_ul]:my-2 [&_.ProseMirror_ol]:my-2 [&_.ProseMirror_blockquote]:my-2"
              />
            </div>
          )}
          
          {/* Comment Attachments */}
          {comment.attachments && comment.attachments.length > 0 && !isEditing && (
            <div className="ml-1">
              <p className="text-xs font-medium text-gray-600 mb-2">
                Attachments ({comment.attachments.length})
              </p>
              <FileAttachments 
                files={comment.attachments}
                compact={true}
                className="max-w-md"
              />
            </div>
          )}
        </div>
      </div>
    </>
  );
}; 