'use client';

import { useCallback, useEffect, useRef } from 'react';
import { useFeed } from './hooks/useFeed';
import { PostComposer } from './PostComposer';
import { PostCard } from './PostCard';
import { FeedSkeleton } from './FeedSkeleton';
import { apiFetchJson } from '@/lib/auth';
import { FeedPostItem } from '@kres/types';

interface FeedPageProps {
  currentUser: {
    id: string;
    role: 'ADMIN' | 'TEACHER' | 'PARENT';
    firstName: string;
    lastName: string;
  };
}

export function FeedPage({ currentUser }: FeedPageProps) {
  const {
    posts,
    isLoading,
    isFetchingMore,
    hasMore,
    loadMore,
    addPost,
    toggleLike,
    deletePost,
    pinPost,
  } = useFeed();
  const sentinelRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          loadMore();
        }
      },
      { threshold: 0.1 },
    );
    if (sentinelRef.current) {
      observer.observe(sentinelRef.current);
    }
    return () => observer.disconnect();
  }, [loadMore]);

  const handleSubmit = useCallback(
    async (content: string, audience: string, files: File[]) => {
      const formData = new FormData();
      formData.append('content', content);
      formData.append('audience', audience);
      files.forEach((f) => formData.append('files', f));

      const res = await apiFetchJson<FeedPostItem>('/v1/feed', {
        method: 'POST',
        body: formData,
      });
      if (res.data) {
        addPost(res.data);
      } else {
        throw new Error(res.error ?? 'Gönderi paylaşılamadı');
      }
    },
    [addPost],
  );

  const fullName = `${currentUser.firstName} ${currentUser.lastName}`;

  return (
    <div className="max-w-2xl mx-auto px-4 py-6 space-y-4">
      <PostComposer
        authorName={fullName}
        authorRole={currentUser.role}
        onSubmit={handleSubmit}
      />

      {isLoading ? (
        <FeedSkeleton count={3} />
      ) : posts.length === 0 ? (
        <div className="text-center py-16 text-gray-400">
          <div className="text-4xl mb-3">📭</div>
          <p className="text-sm">Henüz gönderi yok. İlk paylaşımı siz yapın!</p>
        </div>
      ) : (
        <>
          {posts.map((post) => (
            <PostCard
              key={post.id}
              post={post}
              currentUserId={currentUser.id}
              currentUserRole={currentUser.role}
              onLike={toggleLike}
              onDelete={deletePost}
              onPin={currentUser.role === 'ADMIN' ? pinPost : undefined}
            />
          ))}
          <div ref={sentinelRef} className="h-4" />
          {isFetchingMore && <FeedSkeleton count={2} />}
          {!hasMore && posts.length > 0 && (
            <p className="text-center text-xs text-gray-400 py-4">Tüm gönderiler yüklendi</p>
          )}
        </>
      )}
    </div>
  );
}
