import { useState, useEffect } from "react";
import { PencilIcon, XIcon, MessageCircleIcon, Paperclip } from "lucide-react";

import { Button } from "@/components/ui/button";
import { DottedSeparator } from "@/components/dotted-separator";
import { FileAttachments } from "@/components/ui/file-attachments";
import { RichTextEditor } from "@/components/ui/rich-text-editor";

import { Task } from "../types";
import { useUpdateTask } from "../api/use-update-task";
import { useGetComments } from "../api/use-get-comments";
import { useMembersForMentions } from "@/features/members/hooks/use-members-for-mentions";
import { useWorkspaceId } from "@/features/workspaces/hooks/use-workspace-id";
import { TaskCommentsSection } from "./task-comments-section";

interface TaskDescriptionProps {
  task: Task;
}

export const TaskDescription = ({ task }: TaskDescriptionProps) => {
  const [isEditingDescription, setIsEditingDescription] = useState(false);
  const [descriptionValue, setDescriptionValue] = useState(task.description || "");

  // Update description value when task description changes
  useEffect(() => {
    setDescriptionValue(task.description || "");
  }, [task.description]);
  
  const workspaceId = useWorkspaceId();
  const { mutate: updateTask, isPending: isUpdatingDescription } = useUpdateTask();
  const { data: comments, isLoading: isLoadingComments } = useGetComments({ taskId: task.id });
  const { members: mentionableMembers } = useMembersForMentions({ workspaceId });

  const handleDescriptionSave = () => {
    updateTask({
      json: { description: descriptionValue },
      param: { taskId: task.id },
    }, {
      onSuccess: () => {
        setIsEditingDescription(false);
      }
    });
  };

  const handleCancelEdit = () => {
    setDescriptionValue(task.description || "");
    setIsEditingDescription(false);
  };

  console.log(mentionableMembers)

  return (
    <div className="flex flex-col gap-y-4 ">
      {/* Description Section - Completely Rebuilt */}
      <div className="p-4 border rounded-lg bg-white">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold">Description</h2>
          <Button
            onClick={() => setIsEditingDescription((prev) => !prev)}
            size="sm"
            variant="outline"
          >
            {isEditingDescription ? (
              <>
                <XIcon className="size-4 mr-2" />
                Cancel
              </>
            ) : (
              <>
                <PencilIcon className="size-4 mr-2" />
                Edit
              </>
            )}
          </Button>
        </div>
        
        <DottedSeparator className="mb-4" />
        
        {isEditingDescription ? (
          <div className="space-y-4">
            <div className="border rounded-lg">
              <RichTextEditor
                key="description-editor-editing"
                content={descriptionValue}
                onChange={setDescriptionValue}
                placeholder="Add a description for this task..."
                editable={true}
                className="min-h-[200px]"
                members={mentionableMembers}
                workspaceId={workspaceId}
              />
            </div>
            <div className="flex gap-2 justify-end">
              <Button
                variant="outline"
                size="sm"
                onClick={handleCancelEdit}
                disabled={isUpdatingDescription}
              >
                Cancel
              </Button>
              <Button
                size="sm"
                onClick={handleDescriptionSave}
                disabled={isUpdatingDescription}
              >
                {isUpdatingDescription ? "Saving..." : "Save Changes"}
              </Button>
            </div>
          </div>
        ) : (
          <div className="min-h-[100px]">
            {task.description ? (
              <div className="prose prose-sm max-w-none">
                <RichTextEditor
                  key="description-editor-readonly"
                  content={task.description}
                  onChange={() => {}}
                  editable={false}
                  className="border-0 p-0 [&_.ProseMirror]:p-0 [&_.ProseMirror]:m-0 [&_.ProseMirror]:min-h-0"
                />
              </div>
            ) : (
              <div className="flex items-center justify-center h-20 text-muted-foreground border-2 border-dashed rounded-lg">
                <span>No description set. Click Edit to add one.</span>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Task Attachments Section */}
      {task.attachments && task.attachments.length > 0 && (
        <div className="p-4 border rounded-lg">
          <div className="flex items-center gap-x-2 mb-4">
            <Paperclip className="size-5" />
            <p className="text-lg font-semibold">
              Attachments ({task.attachments.length})
            </p>
          </div>
          <DottedSeparator className="mb-4" />
          <FileAttachments files={task.attachments} />
        </div>
      )}

      {/* Comments Section with Scroll-to-Comment Support */}
      <div className="p-4 border rounded-lg bg-white">
        {isLoadingComments ? (
          <div className="text-center text-muted-foreground py-8">
            <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-2">Loading comments...</p>
          </div>
        ) : (
          <TaskCommentsSection 
            taskId={task.id} 
            comments={comments || []} 
          />
        )}
      </div>
    </div>
  );
};
