import React, { useState } from 'react'
import { AnimatePresence } from 'framer-motion'
import PostItem from './PostItem'
import { MediaItem } from './MediaManager'
import CreatePost from './CreatePost'
import { Location, SocialPost } from '@/types/intranet'
import { mockSocialPosts } from '@/mocks/mockIntranet'

const SocialWall: React.FC = () => {
  const [posts, setPosts] = useState<SocialPost[]>(mockSocialPosts)
  const [filter, setFilter] = useState<'all' | 'mine'>('all')

  const handleCreatePost = (postData: {
    content: string
    location?: Location
    media?: {
      type: 'mixed' | 'poll'
      mediaItems?: MediaItem[]
      poll?: {
        question: string
        options: Array<{ text: string }>
      }
    }
  }) => {
    let mediaForPost = undefined

    if (postData.media) {
      if (postData.media.type === 'mixed' && postData.media.mediaItems) {
        // Convert MediaItems to post format
        const images = postData.media.mediaItems.filter(m => m.type === 'image')
        const videos = postData.media.mediaItems.filter(m => m.type === 'video')
        
        if (images.length > 0 && videos.length === 0) {
          mediaForPost = {
            type: 'image' as const,
            urls: images.map(i => i.url)
          }
        } else if (videos.length > 0 && images.length === 0) {
          mediaForPost = {
            type: 'video' as const,
            url: videos[0].url
          }
        } else if (images.length > 0 || videos.length > 0) {
          // Mixed media - use first image for now
          mediaForPost = {
            type: 'image' as const,
            urls: images.map(i => i.url)
          }
        }
      } else if (postData.media.type === 'poll' && postData.media.poll) {
        mediaForPost = {
          type: 'poll' as const,
          poll: {
            question: postData.media.poll.question,
            options: postData.media.poll.options.map((opt, index) => ({
              id: `opt-${index}`,
              text: opt.text,
              votes: 0
            })),
            totalVotes: 0,
            endsAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
          }
        }
      }
    }

    const newPost: SocialPost = {
      id: Date.now().toString(),
      author: {
        id: 'currentUser',
        name: 'Siz',
        avatar: 'https://i.pravatar.cc/150?img=1',
        title: 'Çalışan'
      },
      content: postData.content,
      creationTime: new Date(),
      media: mediaForPost,
      location: postData.location,
      likes: {
        count: 0,
        isLiked: false,
        users: []
      },
      comments: [],
      isOwnPost: true
    }

    setPosts([newPost, ...posts])
  }

  const handleLike = (postId: string) => {
    setPosts(
      posts.map((post) => {
        if (post.id === postId) {
          return {
            ...post,
            likes: {
              ...post.likes,
              count: post.likes.isLiked ? post.likes.count - 1 : post.likes.count + 1,
              isLiked: !post.likes.isLiked
            }
          }
        }
        return post
      })
    )
  }

  const handleComment = (postId: string, content: string) => {
    setPosts(
      posts.map((post) => {
        if (post.id === postId) {
          const newComment = {
            id: Date.now().toString(),
            author: {
              id: 'currentUser',
              name: 'Siz',
              avatar: 'https://i.pravatar.cc/150?img=1'
            },
            content,
            creationTime: new Date()
          }
          return {
            ...post,
            comments: [...post.comments, newComment]
          }
        }
        return post
      })
    )
  }

  const handleDelete = (postId: string) => {
    if (window.confirm('Bu gönderiyi silmek istediğinizden emin misiniz?')) {
      setPosts(posts.filter((post) => post.id !== postId))
    }
  }

  const handleVote = (postId: string, optionId: string) => {
    setPosts(
      posts.map((post) => {
        if (post.id === postId && post.media?.type === 'poll' && post.media.poll) {
          const poll = post.media.poll
          
          // If user already voted, don't allow voting again
          if (poll.userVote) {
            return post
          }

          return {
            ...post,
            media: {
              ...post.media,
              poll: {
                ...poll,
                options: poll.options.map((opt) =>
                  opt.id === optionId ? { ...opt, votes: opt.votes + 1 } : opt
                ),
                totalVotes: poll.totalVotes + 1,
                userVote: optionId
              }
            }
          }
        }
        return post
      })
    )
  }

  const filteredPosts = filter === 'mine' ? posts.filter((post) => post.isOwnPost) : posts

  return (
    <div className="mx-auto px-4">
      {/* Filter Tabs */}
      <div className="flex gap-4 mb-6 border-b border-gray-200 dark:border-gray-700">
        <button
          onClick={() => setFilter('all')}
          className={`pb-3 px-1 border-b-2 transition-colors font-medium ${
            filter === 'all'
              ? 'border-blue-600 text-blue-600'
              : 'border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
          }`}
        >
          Tüm Gönderiler
        </button>
        <button
          onClick={() => setFilter('mine')}
          className={`pb-3 px-1 border-b-2 transition-colors font-medium ${
            filter === 'mine'
              ? 'border-blue-600 text-blue-600'
              : 'border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
          }`}
        >
          Gönderilerim
        </button>
      </div>

      {/* Create Post */}
      <CreatePost onCreatePost={handleCreatePost} />

      {/* Posts Feed */}
      <AnimatePresence>
        {filteredPosts.length > 0 ? (
          filteredPosts.map((post) => (
            <PostItem
              key={post.id}
              post={post}
              onLike={handleLike}
              onComment={handleComment}
              onDelete={handleDelete}
              onVote={handleVote}
            />
          ))
        ) : (
          <div className="text-center py-12">
            <p className="text-gray-500 dark:text-gray-400 text-lg">
              {filter === 'mine' ? 'Henüz bir gönderi paylaşmadınız.' : 'Henüz gönderi yok.'}
            </p>
          </div>
        )}
      </AnimatePresence>
    </div>
  )
}

export default SocialWall
