import React, { useState } from 'react';
import { mdiHeart, mdiHeartOutline, mdiCommentOutline, mdiShareVariantOutline } from '@mdi/js';
import BaseIcon from '../BaseIcon';
import UserAvatar from '../UserAvatar';
import ImageField from '../ImageField';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { create as createReaction } from '../../stores/reactions/reactionsSlice';
import { update as updatePost } from '../../stores/posts/postsSlice';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);

type Props = {
  post: any;
};

const PostCard = ({ post }: Props) => {
  const dispatch = useAppDispatch();
  const { currentUser } = useAppSelector((state) => state.auth);
  const [isLiked, setIsLiked] = useState(false); // Simple local state for demo
  const [likeCount, setLikeCount] = useState(post.like_count || 0);

  const handleLike = async () => {
    if (isLiked) return;
    
    setIsLiked(true);
    setLikeCount(likeCount + 1);

    try {
      await dispatch(createReaction({
        target_type: 'post',
        reaction_type: 'like',
        postId: post.id,
        userId: currentUser?.id,
        reacted_at: new Date().toISOString()
      }));
      
      // Update post like count in DB
      await dispatch(updatePost({
        id: post.id,
        data: {
          like_count: likeCount + 1
        }
      }));
    } catch (error) {
      console.error('Failed to like post', error);
      setIsLiked(false);
      setLikeCount(likeCount);
    }
  };

  return (
    <div className="bg-white dark:bg-dark-800 rounded-xl shadow-sm mb-6 border border-gray-100 dark:border-dark-700 overflow-hidden">
      {/* Header */}
      <div className="flex items-center p-4">
        <UserAvatar 
          username={post.author?.firstName || 'User'} 
          image={post.author?.avatar}
          className="w-10 h-10 mr-3" 
        />
        <div>
          <h4 className="font-bold text-sm dark:text-white hover:underline cursor-pointer">
            {post.author?.firstName} {post.author?.lastName}
          </h4>
          <p className="text-xs text-gray-500 dark:text-dark-600">
            {dayjs(post.createdAt).fromNow()}
          </p>
        </div>
      </div>

      {/* Content */}
      <div className="px-4 pb-3 text-sm dark:text-gray-200">
        <p>{post.caption}</p>
      </div>

      {/* Image */}
      {post.media_images && post.media_images.length > 0 && (
        <div className="w-full">
           <ImageField
             name="post-image"
             image={post.media_images}
             className="w-full h-auto max-h-[500px] overflow-hidden bg-gray-100 dark:bg-dark-900"
             imageClassName="w-full h-full object-cover"
           />
        </div>
      )}

      {/* Actions */}
      <div className="p-4 flex items-center justify-between border-t border-gray-50 dark:border-dark-700">
        <div className="flex items-center space-x-6">
          <button 
            onClick={handleLike}
            className={`flex items-center space-x-2 transition-colors ${isLiked ? 'text-rose-500' : 'text-gray-500 dark:text-dark-600 hover:text-rose-500'}`}
          >
            <BaseIcon path={isLiked ? mdiHeart : mdiHeartOutline} size="20" />
            <span className="text-xs font-semibold">{likeCount}</span>
          </button>
          
          <button className="flex items-center space-x-2 text-gray-500 dark:text-dark-600 hover:text-indigo-500 transition-colors">
            <BaseIcon path={mdiCommentOutline} size="20" />
            <span className="text-xs font-semibold">{post.comment_count || 0}</span>
          </button>
          
          <button className="flex items-center space-x-2 text-gray-500 dark:text-dark-600 hover:text-green-500 transition-colors">
            <BaseIcon path={mdiShareVariantOutline} size="20" />
            <span className="text-xs font-semibold">{post.share_count || 0}</span>
          </button>
        </div>
        
        <div className="text-xs text-gray-400">
            {post.view_count || 0} views
        </div>
      </div>
    </div>
  );
};

export default PostCard;