import React, { useMemo, useState } from 'react';
import { mdiHeart, mdiHeartOutline, mdiChatOutline, mdiSendOutline, mdiBookmarkOutline, mdiDotsHorizontal, mdiAlertOctagonOutline } from '@mdi/js';
import BaseIcon from '../BaseIcon';
import UserAvatar from '../UserAvatar';
import dataFormatter from '../../helpers/dataFormatter';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { create as createReaction, deleteItem as deleteReaction } from '../../stores/post_reactions/post_reactionsSlice';
import { create as createComment } from '../../stores/post_comments/post_commentsSlice';
import { setRefetch } from '../../stores/posts/postsSlice';
import ReportModal from '../ReportModal';
import Popover from '@mui/material/Popover';
import Button from '@mui/material/Button';

type Props = {
  post: any;
  onLike?: (id: string) => void;
  onComment?: (id: string) => void;
};

export default function SocialPostCard({ post, onLike, onComment }: Props) {
  const dispatch = useAppDispatch();
  const { currentUser } = useAppSelector((state) => state.auth);
  const [commentBody, setCommentBody] = useState('');
  const [isCommenting, setIsCommenting] = useState(false);
  const [isReportModalOpen, setIsReportModalOpen] = useState(false);
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  
  const imageUrl = post.images && post.images[0] ? post.images[0].publicUrl : null;
  const authorName = post.author ? `${post.author.firstName} ${post.author.lastName}` : 'Anonymous';
  const authorAvatar = post.author ? post.author.avatar : null;

  const currentUserReaction = useMemo(() => {
    if (!currentUser || !post.post_reactions_post) return null;
    return post.post_reactions_post.find((r: any) => r.userId === currentUser.id);
  }, [currentUser, post.post_reactions_post]);

  const isLiked = !!currentUserReaction;

  const handleLikeToggle = async () => {
    if (!currentUser) return;

    if (isLiked) {
      try {
        await dispatch(deleteReaction(currentUserReaction.id)).unwrap();
        dispatch(setRefetch(true));
      } catch (err) {
        console.error('Failed to unlike', err);
      }
    } else {
      try {
        await dispatch(createReaction({
          reaction_type: 'like',
          reacted_at: new Date().toISOString(),
          post: post.id,
          user: currentUser.id,
        })).unwrap();
        dispatch(setRefetch(true));
      } catch (err) {
        console.error('Failed to like', err);
      }
    }
    
    if (onLike) onLike(post.id);
  };

  const handleCommentSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!commentBody.trim() || !currentUser) return;

    setIsCommenting(true);
    try {
      await dispatch(createComment({
        body: commentBody,
        commented_at: new Date().toISOString(),
        post: post.id,
        author: currentUser.id,
      })).unwrap();
      setCommentBody('');
      dispatch(setRefetch(true));
    } catch (err) {
      console.error('Failed to comment', err);
    } finally {
      setIsCommenting(false);
    }
  };

  const handleOpenMenu = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleCloseMenu = () => {
    setAnchorEl(null);
  };

  const handleReportClick = () => {
    handleCloseMenu();
    setIsReportModalOpen(true);
  };

  return (
    <div className="bg-white dark:bg-[#1a1d23] border border-gray-200 dark:border-gray-800 rounded-2xl overflow-hidden mb-6 max-w-lg mx-auto shadow-sm">
      {/* Header */}
      <div className="flex items-center justify-between p-4">
        <div className="flex items-center space-x-3">
          <UserAvatar username={authorName} image={authorAvatar} className="w-10 h-10" />
          <div>
            <p className="font-bold text-sm dark:text-white">{authorName}</p>
            {post.location_name && <p className="text-xs text-gray-500 dark:text-gray-400">{post.location_name}</p>}
          </div>
        </div>
        <button className="text-gray-500 dark:text-gray-400" onClick={handleOpenMenu}>
          <BaseIcon path={mdiDotsHorizontal} size={24} />
        </button>
        <Popover
          open={Boolean(anchorEl)}
          anchorEl={anchorEl}
          onClose={handleCloseMenu}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'right',
          }}
          transformOrigin={{
            vertical: 'top',
            horizontal: 'right',
          }}
        >
          <div className="bg-white dark:bg-dark-800 p-1 min-w-[120px]">
            <Button
              onClick={handleReportClick}
              className="w-full text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 px-4 py-2 text-sm flex items-center justify-start space-x-2 normal-case"
              startIcon={<BaseIcon path={mdiAlertOctagonOutline} size={18} />}
            >
              Report
            </Button>
          </div>
        </Popover>
      </div>

      {/* Image/Video */}
      <div className="aspect-square bg-gray-100 dark:bg-gray-900 flex items-center justify-center overflow-hidden">
        {imageUrl ? (
          <img src={imageUrl} alt="Post content" className="w-full h-full object-cover" />
        ) : (
          <div className="text-gray-400 italic">No media</div>
        )}
      </div>

      {/* Interactions */}
      <div className="p-4 space-y-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <button onClick={handleLikeToggle} className="hover:scale-110 transition-transform">
              <BaseIcon 
                path={isLiked ? mdiHeart : mdiHeartOutline} 
                size={28} 
                className={isLiked ? "text-red-500" : "dark:text-white"} 
              />
            </button>
            <button onClick={() => onComment && onComment(post.id)} className="hover:scale-110 transition-transform">
              <BaseIcon path={mdiChatOutline} size={26} className="dark:text-white" />
            </button>
            <button className="hover:scale-110 transition-transform">
              <BaseIcon path={mdiSendOutline} size={26} className="dark:text-white" />
            </button>
          </div>
          <button className="hover:scale-110 transition-transform">
            <BaseIcon path={mdiBookmarkOutline} size={26} className="dark:text-white" />
          </button>
        </div>

        {/* Likes Count */}
        <p className="text-sm font-bold dark:text-white">
          {post.post_reactions_post ? post.post_reactions_post.length : 0} likes
        </p>

        {/* Caption */}
        <div className="text-sm space-x-2">
          <span className="font-bold dark:text-white">{authorName}</span>
          <span className="dark:text-gray-300">{post.caption}</span>
        </div>

        {/* Comments Section */}
        {post.post_comments_post && post.post_comments_post.length > 0 && (
          <div className="space-y-1 mt-2">
            {post.post_comments_post.slice(-3).map((comment: any) => (
              <div key={comment.id} className="text-sm">
                <span className="font-bold mr-2 dark:text-white">
                  {comment.author ? `${comment.author.firstName}` : 'User'}
                </span>
                <span className="dark:text-gray-300">{comment.body}</span>
              </div>
            ))}
            {post.post_comments_post.length > 3 && (
              <button className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                View all {post.post_comments_post.length} comments
              </button>
            )}
          </div>
        )}

        {/* Time */}
        <p className="text-[10px] text-gray-400 uppercase tracking-wider pt-1">
          {dataFormatter.dateTimeFormatter(post.published_at)}
        </p>
      </div>

      {/* Comment Input */}
      <form onSubmit={handleCommentSubmit} className="border-t border-gray-100 dark:border-gray-800 p-4 flex items-center space-x-3">
        <input 
          type="text" 
          placeholder="Add a comment..." 
          className="flex-1 bg-transparent border-none focus:ring-0 text-sm dark:text-white placeholder-gray-500"
          value={commentBody}
          onChange={(e) => setCommentBody(e.target.value)}
        />
        <button 
          disabled={!commentBody.trim() || isCommenting}
          className={`text-sm font-bold ${!commentBody.trim() || isCommenting ? 'text-gray-300' : 'text-[#00d4ff]'}`}
        >
          Post
        </button>
      </form>

      <ReportModal 
        isOpen={isReportModalOpen} 
        onClose={() => setIsReportModalOpen(false)} 
        targetType="post" 
        targetRef={post.id} 
      />
    </div>
  );
}