'use client';

import { motion } from 'framer-motion';
import { api } from '@/lib/trpc/client';
import { formatDistanceToNow } from 'date-fns';
import { ThumbsUp, ThumbsDown } from 'lucide-react';
import React, { useState, useEffect } from 'react';

import {
  Avatar,
  AvatarImage,
  AvatarFallback,
} from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';

import { useSession } from '@/lib/auth/auth-client';
import { REACTION_TYPES, type ReactionType } from '@/config/enums';

import { EditCommentSheet } from './edit-comment-sheet';
import { CreateCommentSheet } from './create-comment-sheet';
import { DeleteCommentDialog } from './delete-comment-dialog';

interface CommentData {
  id: string;
  postId: string;
  userId: string;
  parentId?: string | null;
  content: string;
  upvotes: number;
  downvotes: number;
  repliesCount: number;
  isEdited: boolean;
  isDeleted: boolean;
  createdAt: string | Date;
  updatedAt: string | Date;
  userName: string;
  userEmail: string;
  userImage?: string | null;
  replies?: CommentData[];
}

type CommentCardProps = CommentData;

export const CommentCard: React.FC<CommentCardProps> = ({
  id,
  postId,
  userId,
  content,
  upvotes,
  downvotes,
  isEdited,
  isDeleted,
  createdAt,
  userName,
  userImage,
  replies = []
}) => {
  const [opened, setOpened] = useState(false);
  const [currentUpvotes, setCurrentUpvotes] = useState(upvotes);
  const [currentDownvotes, setCurrentDownvotes] = useState(downvotes);
  const [userReaction, setUserReaction] = useState<ReactionType | null>(null);

  // Get current user session
  const { data: session } = useSession();
  const isAuthor = session?.user?.id === userId;

  // Get user's current reaction
  // const { data: currentReaction } =
  //   api.comments.getUserCommentReaction.useQuery(
  //     { commentId: id },
  //     {
  //       enabled: !!id
  //     }
  //   );

  // Toggle reaction mutation
  // const toggleReactionMutation = api.comments.toggleCommentReaction.useMutation(
  //   {
  //     onSuccess: (data) => {
  //       setCurrentUpvotes(data.upvotes);
  //       setCurrentDownvotes(data.downvotes);
  //       setUserReaction(data.currentReaction);
  //     },
  //     onError: () => {
  //       // Failed to toggle reaction
  //     }
  //   }
  // );

  // useEffect(() => {
  //   if (currentReaction !== undefined && currentReaction !== null) {
  //     setUserReaction(currentReaction as ReactionType);
  //   }
  // }, [currentReaction]);

  // const handleShowReplies = () => {
  //   setOpened(!opened);
  // };

  // const handleReaction = (reactionType: ReactionType) => {
  //   if (toggleReactionMutation.isPending) return;

  //   toggleReactionMutation.mutate({
  //     commentId: id,
  //     reactionType
  //   });
  // };

  const formatDate = (date: string | Date) => {
    return formatDistanceToNow(new Date(date), { addSuffix: true });
  };

  const getInitials = (name: string) => {
    return name
      .split(' ')
      .map((n) => n[0])
      .join('')
      .toUpperCase()
      .slice(0, 2);
  };

  // const netScore = currentUpvotes - currentDownvotes;

  return (
    <div className="relative mt-4 ml-6 block before:absolute before:-left-2.5 before:min-h-full before:w-px before:bg-gray-500 before:content-['']">
      <div className='min-w-full rounded-lg p-3'>
        {/* User info */}
        <div className='mb-3 flex items-center gap-3'>
          <Avatar className='h-8 w-8'>
            <AvatarImage src={userImage || undefined} alt={userName} />
            <AvatarFallback className='text-xs'>
              {getInitials(userName)}
            </AvatarFallback>
          </Avatar>
          <div className='flex flex-col'>
            <span className='text-card-foreground text-sm font-medium'>
              {userName}
            </span>
            <div className='text-muted-foreground flex items-center gap-2 text-xs'>
              <span>{formatDate(createdAt)}</span>
              {isEdited && (
                <Badge variant='outline' className='px-1 py-0 text-xs'>
                  edited
                </Badge>
              )}
            </div>
          </div>
        </div>

        {/* Comment content */}
        <div className='mb-4'>
          {isDeleted ? (
            <p className='text-muted-foreground italic'>
              This comment was deleted
            </p>
          ) : (
            <p className='text-card-foreground whitespace-pre-wrap'>
              {content}
            </p>
          )}
        </div>

        {/* Actions */}
        <div className='flex items-center justify-between gap-6 text-sm'>
          {/* <div className='flex items-center gap-4'>
            {!isDeleted && (
              <>
                <button
                  onClick={() => handleReaction(REACTION_TYPES.LIKE)}
                  disabled={toggleReactionMutation.isPending}
                  className={`flex cursor-pointer items-center gap-1 transition-colors ${
                    userReaction === REACTION_TYPES.LIKE
                      ? 'font-medium text-green-600'
                      : 'text-muted-foreground hover:text-green-600'
                  } ${toggleReactionMutation.isPending ? 'opacity-50' : ''}`}
                >
                  <ThumbsUp className='size-3' />
                  <span>{currentUpvotes}</span>
                </button>

                <button
                  onClick={() => handleReaction(REACTION_TYPES.DISLIKE)}
                  disabled={toggleReactionMutation.isPending}
                  className={`flex cursor-pointer items-center gap-1 transition-colors ${
                    userReaction === REACTION_TYPES.DISLIKE
                      ? 'font-medium text-red-600'
                      : 'text-muted-foreground hover:text-red-600'
                  } ${toggleReactionMutation.isPending ? 'opacity-50' : ''}`}
                >
                  <ThumbsDown className='size-3' />
                  <span>{currentDownvotes}</span>
                </button>
              </>
            )}
          </div>

          <div className='flex items-center gap-2'>
            {replies && replies.length > 0 && (
              <button
                onClick={handleShowReplies}
                className='text-primary hover:text-primary/80 cursor-pointer transition-colors'
              >
                {opened ? 'Hide Replies' : `Show ${replies.length} Replies`}
              </button>
            )}

            {isAuthor && !isDeleted && (
              <>
                <EditCommentSheet
                  commentId={id}
                  postId={postId}
                  currentContent={content}
                />
                <DeleteCommentDialog commentId={id} postId={postId} />
              </>
            )}

            {!isDeleted && <CreateCommentSheet postId={postId} parentId={id} />}
          </div> */}
        </div>
      </div>

      {/* Render replies */}
      {replies &&
        opened &&
        replies.map((reply) => (
          <motion.div
            key={reply.id}
            initial={{ opacity: 0, y: 20, marginTop: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
          >
            <CommentCard {...reply} />
          </motion.div>
        ))}
    </div>
  );
};
