import React, { useState } from 'react';
import { Heart, MessageCircle, Share, MoreHorizontal, Lock, Users, Globe, Clock, Calendar } from 'lucide-react';
import { Post, ContentBlock } from '../types';

interface PostCardProps {
  post: Post;
  onToggleLike: (postId: string) => void;
}

const PostCard: React.FC<PostCardProps> = ({ post, onToggleLike }) => {
  const [showComments, setShowComments] = useState(false);

  const formatTime = (date: Date) => {
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return 'Just now';
    if (minutes < 60) return `${minutes}m`;
    if (hours < 24) return `${hours}h`;
    return `${days}d`;
  };

  const getSharingIcon = () => {
    switch (post.sharing.type) {
      case 'public': return Globe;
      case 'groups': return Users;
      default: return Lock;
    }
  };

  const getSharingText = () => {
    switch (post.sharing.type) {
      case 'public': return 'Public';
      case 'groups': return 'Groups';
      default: 'Private';
    }
  };

  const getSharingDescription = () => {
    return post.sharing.description || getSharingText();
  };

  const renderContent = () => {
    try {
      const contentBlocks: ContentBlock[] = JSON.parse(post.content);
      return (
        <div className="space-y-4">
          {contentBlocks.map((block) => {
            if (block.type === 'text' && block.content.trim()) {
              return (
                <div key={block.id} className="text-gray-900 dark:text-white leading-relaxed whitespace-pre-wrap">
                  {block.content}
                </div>
              );
            } else if (block.type === 'image' && block.mediaFile) {
              return (
                <div key={block.id} className="rounded-xl overflow-hidden">
                  <img
                    src={block.mediaFile.url}
                    alt={block.mediaFile.filename}
                    className="w-full object-cover max-h-96"
                  />
                </div>
              );
            } else if (block.type === 'video' && block.mediaFile) {
              return (
                <div key={block.id} className="rounded-xl overflow-hidden">
                  <video
                    src={block.mediaFile.url}
                    controls
                    className="w-full object-cover max-h-96"
                  />
                </div>
              );
            }
            return null;
          })}
        </div>
      );
    } catch {
      // Fallback for old format posts
      return (
        <div className="text-gray-900 dark:text-white leading-relaxed">
          {post.content}
        </div>
      );
    }
  };

  const SharingIcon = getSharingIcon();

  return (
    <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden hover:shadow-xl transition-shadow duration-300">
      {/* Header */}
      <div className="flex items-center justify-between p-4">
        <div className="flex items-center space-x-3">
          <img
            src={post.author.avatar}
            alt={post.author.name}
            className="w-10 h-10 rounded-full object-cover"
          />
          <div>
            <h4 className="font-semibold text-gray-900 dark:text-white">{post.author.name}</h4>
            <div className="flex items-center space-x-2 text-sm text-gray-500 dark:text-gray-400">
              <span>{formatTime(post.timestamp)}</span>
              <span>•</span>
              <div className="flex items-center space-x-1">
                <SharingIcon size={14} />
                <span>{getSharingDescription()}</span>
              </div>
              {post.isScheduled && (
                <>
                  <span>•</span>
                  <div className="flex items-center space-x-1 text-gray-600 dark:text-gray-400">
                    <Clock size={14} />
                    <span>Scheduled</span>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
        <button className="text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 transition-colors p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700">
          <MoreHorizontal size={20} />
        </button>
      </div>

      {/* Title */}
      <div className="px-4 pb-2">
        <h3 className="text-xl font-bold text-gray-900 dark:text-white">{post.title}</h3>
      </div>

      {/* Content */}
      <div className="px-4 pb-4">
        {renderContent()}
      </div>

      {/* Scheduled Post Notice */}
      {post.isScheduled && post.scheduledFor && (
        <div className="mx-4 mb-4 p-3 bg-gray-100 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg">
          <div className="flex items-center space-x-2 text-gray-700 dark:text-gray-300">
            <Calendar size={16} />
            <span className="text-sm font-medium">
              Scheduled for {post.scheduledFor.toLocaleDateString()} at{' '}
              {post.scheduledFor.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
            </span>
          </div>
        </div>
      )}

      {/* Actions */}
      <div className="px-4 py-3 border-t border-gray-100 dark:border-gray-700">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-6">
            <button
              onClick={() => onToggleLike(post.id)}
              className={`flex items-center space-x-2 transition-all duration-200 ${
                post.isLiked
                  ? 'text-red-500 hover:text-red-600'
                  : 'text-gray-600 dark:text-gray-400 hover:text-red-500'
              }`}
            >
              <Heart
                size={20}
                className={post.isLiked ? 'fill-current' : ''}
              />
              <span className="text-sm font-medium">{post.likes}</span>
            </button>

            <button
              onClick={() => setShowComments(!showComments)}
              className="flex items-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
            >
              <MessageCircle size={20} />
              <span className="text-sm font-medium">{post.comments.length}</span>
            </button>

            <button className="flex items-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors">
              <Share size={20} />
              <span className="text-sm font-medium">Share</span>
            </button>
          </div>
        </div>
      </div>

      {/* Comments Section */}
      {showComments && (
        <div className="px-4 py-3 border-t border-gray-100 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50">
          <div className="space-y-3">
            {post.comments.map((comment) => (
              <div key={comment.id} className="flex space-x-3">
                <img
                  src={comment.author.avatar}
                  alt={comment.author.name}
                  className="w-8 h-8 rounded-full object-cover"
                />
                <div className="flex-1">
                  <div className="bg-white dark:bg-gray-700 rounded-xl px-3 py-2">
                    <h5 className="font-medium text-sm text-gray-900 dark:text-white">
                      {comment.author.name}
                    </h5>
                    <p className="text-sm text-gray-700 dark:text-gray-300">{comment.content}</p>
                  </div>
                  <div className="text-xs text-gray-500 dark:text-gray-400 mt-1 ml-3">
                    {formatTime(comment.timestamp)}
                  </div>
                </div>
              </div>
            ))}
            
            <div className="flex space-x-3 mt-4">
              <div className="w-8 h-8 rounded-full bg-gray-900 dark:bg-white flex items-center justify-center text-white dark:text-gray-900 font-medium text-sm">
                Y
              </div>
              <div className="flex-1">
                <input
                  type="text"
                  placeholder="Write a comment..."
                  className="w-full bg-white dark:bg-gray-700 rounded-full px-4 py-2 border border-gray-200 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-500 dark:focus:ring-gray-400 focus:border-transparent text-sm text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400"
                />
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default PostCard;