'use client';

import { formatDistanceToNow } from 'date-fns';
import { tr } from 'date-fns/locale';
import { Heart, MessageCircle, Share2, MoreHorizontal, Pin, Trash2 } from 'lucide-react';
import { useState, useRef, useEffect } from 'react';
import { cn } from '@/lib/utils';
import { FeedPostItem } from '@kres/types';
import { Button } from '@/components/ui/button';
import { PostMedia } from './PostMedia';
import { PostComments } from './PostComments';

const ROLE_LABELS: Record<string, string> = {
  ADMIN: 'Okul yönetimi',
  TEACHER: 'Öğretmen',
  PARENT: 'Veli',
};

const ROLE_AVATAR_CLASS: Record<string, string> = {
  ADMIN: 'bg-violet-100 text-violet-700',
  TEACHER: 'bg-emerald-100 text-emerald-700',
  PARENT: 'bg-orange-100 text-orange-700',
};

const AUDIENCE_CONFIG: Record<string, { label: string; className: string }> = {
  ALL: { label: 'Herkes', className: 'bg-green-100 text-green-700' },
  TEACHERS_ONLY: { label: 'Öğretmenler', className: 'bg-purple-100 text-purple-700' },
  PARENTS_ONLY: { label: 'Veliler', className: 'bg-orange-100 text-orange-700' },
};

interface PostCardProps {
  post: FeedPostItem;
  currentUserId: string;
  currentUserRole: string;
  onLike: (postId: string) => void;
  onDelete: (postId: string) => void;
  onPin?: (postId: string) => void;
}

export function PostCard({
  post,
  currentUserId,
  currentUserRole,
  onLike,
  onDelete,
  onPin,
}: PostCardProps) {
  const [showComments, setShowComments] = useState(false);
  const [liked, setLiked] = useState(post.likedByMe);
  const [likeCount, setLikeCount] = useState(post._count.reactions);
  const [menuOpen, setMenuOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);

  const initials = `${post.author.firstName?.[0] ?? ''}${post.author.lastName?.[0] ?? ''}`.toUpperCase() || '?';
  const audience = AUDIENCE_CONFIG[post.audience] ?? AUDIENCE_CONFIG.ALL;
  const canDelete = currentUserId === post.author.id || currentUserRole === 'ADMIN';
  const canPin = currentUserRole === 'ADMIN';

  useEffect(() => {
    if (!menuOpen) return;
    const handler = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setMenuOpen(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [menuOpen]);

  const handleLike = () => {
    setLiked((p) => !p);
    setLikeCount((p) => (liked ? p - 1 : p + 1));
    onLike(post.id);
  };

  return (
    <article
      className={cn(
        'bg-white rounded-2xl border border-gray-100 shadow-sm hover:shadow-md transition-shadow duration-200 overflow-hidden',
        post.isPinned && 'border-l-4 border-l-amber-400',
      )}
    >
      {post.isPinned && (
        <div className="flex items-center gap-1.5 px-5 pt-3 pb-0 text-xs font-medium text-amber-600">
          <Pin size={12} className="fill-amber-500" />
          Sabitlenmiş gönderi
        </div>
      )}

      <div className="flex items-start gap-3 p-5 pb-3">
        <div
          className={cn(
            'w-9 h-9 rounded-full flex items-center justify-center text-xs font-semibold flex-shrink-0',
            ROLE_AVATAR_CLASS[post.author.role] ?? 'bg-gray-100 text-gray-700',
          )}
        >
          {initials}
        </div>
        <div className="flex-1 min-w-0">
          <span className="font-semibold text-sm text-black leading-tight block">
            {post.author.firstName} {post.author.lastName}
          </span>
          <span className="text-xs text-gray-500 leading-tight block">
            {ROLE_LABELS[post.author.role]}
          </span>
          <div className="flex items-center gap-2 mt-1">
            <span
              className={cn(
                'inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium',
                audience.className,
              )}
            >
              {audience.label}
            </span>
            <span className="text-xs text-gray-400">
              {formatDistanceToNow(new Date(post.createdAt), { addSuffix: true, locale: tr })}
            </span>
          </div>
        </div>
        {(canDelete || canPin) && (
          <div className="relative" ref={menuRef}>
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8 text-gray-400 hover:text-gray-600"
              onClick={() => setMenuOpen((p) => !p)}
            >
              <MoreHorizontal size={16} />
            </Button>
            {menuOpen && (
              <div className="absolute right-0 top-9 z-10 min-w-[160px] bg-white rounded-xl border border-gray-100 shadow-lg py-1">
                {canPin && onPin && (
                  <button
                    onClick={() => { onPin(post.id); setMenuOpen(false); }}
                    className="flex items-center gap-2 w-full px-4 py-2 text-sm text-gray-700 hover:bg-gray-50"
                  >
                    <Pin size={14} />
                    {post.isPinned ? 'Sabitlemeyi kaldır' : 'Sabitle'}
                  </button>
                )}
                {canDelete && (
                  <button
                    onClick={() => { onDelete(post.id); setMenuOpen(false); }}
                    className="flex items-center gap-2 w-full px-4 py-2 text-sm text-red-600 hover:bg-red-50"
                  >
                    <Trash2 size={14} />
                    Sil
                  </button>
                )}
              </div>
            )}
          </div>
        )}
      </div>

      <div className="px-5 pb-3">
        <p className="text-sm text-gray-700 leading-relaxed whitespace-pre-wrap">{post.content}</p>
      </div>

      {post.media.length > 0 && <PostMedia media={post.media} />}

      <div className="flex items-center gap-1 px-4 py-3 border-t border-gray-50">
        <button
          onClick={handleLike}
          className={cn(
            'flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors',
            liked
              ? 'text-rose-500 bg-rose-50 hover:bg-rose-100'
              : 'text-gray-500 hover:bg-gray-100',
          )}
        >
          <Heart size={14} className={cn(liked && 'fill-rose-500')} />
          {likeCount > 0 && likeCount}
        </button>
        <button
          onClick={() => setShowComments((p) => !p)}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-gray-500 hover:bg-gray-100 transition-colors"
        >
          <MessageCircle size={14} />
          {post._count.comments > 0 ? `${post._count.comments} yorum` : 'Yorum yaz'}
        </button>
        <button className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-gray-500 hover:bg-gray-100 transition-colors ml-auto">
          <Share2 size={14} />
        </button>
      </div>

      {showComments && (
        <PostComments
          postId={post.id}
          previewComments={post.comments}
          totalCount={post._count.comments}
        />
      )}
    </article>
  );
}
