import React, { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Post } from '../../types';
import { PostCard } from './PostCard';
import { CreatePostModal } from './CreatePostModal';
import { ImageIcon, Video, Mic2, BarChart, Loader2 } from 'lucide-react';
import { useToast } from '../../context/ToastContext';
import { socialService } from '../../services/socialService';
import { logger } from '@/utils/logger';

export const FeedView: React.FC = () => {
  const { addToast } = useToast();
  const [posts, setPosts] = useState<Post[]>([]);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [loading, setLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);

  useEffect(() => {
    loadFeed();
  }, []);

  const loadFeed = async () => {
    setLoading(true);
    try {
      const res = await socialService.getFeed();
      setPosts(res.posts);
    } catch (e) {
      logger.error('Error loading feed', {
        error: e instanceof Error ? e.message : String(e),
        stack: e instanceof Error ? e.stack : undefined,
      });
    } finally {
      setLoading(false);
    }
  };

  const handleCreatePost = async (data: {
    content: string;
    visibility: string;
    type: string;
  }) => {
    try {
      const res = await socialService.createPost(data);
      setPosts([res.post, ...posts]);
      addToast('Post published successfully', 'success');
    } catch (e) {
      addToast('Failed to post', 'error');
    }
  };

  const loadMore = async () => {
    setLoadingMore(true);
    try {
      const res = await socialService.getFeed({ page: 2 });
      // In real app, append unique posts. Here just appending same mock for demo length
      setPosts((prev) => [
        ...prev,
        ...res.posts.map((p) => ({ ...p, id: `more-${Math.random()}` })),
      ]);
    } catch (e) {
      logger.error('Error loading more feed posts', {
        error: e instanceof Error ? e.message : String(e),
        stack: e instanceof Error ? e.stack : undefined,
      });
    } finally {
      setLoadingMore(false);
    }
  };

  if (loading)
    return (
      <div className="flex justify-center py-20">
        <Loader2 className="w-10 h-10 text-kodo-cyan animate-spin" />
      </div>
    );

  return (
    <div className="space-y-6">
      {/* Create Post Widget */}
      <Card variant="default" className="border-t-4 border-t-kodo-cyan p-4">
        <div className="flex gap-4">
          <div className="w-10 h-10 rounded-full bg-gray-700 flex-shrink-0 overflow-hidden cursor-pointer">
            <img
              src="https://picsum.photos/id/237/100/100"
              className="w-full h-full object-cover"
            />
          </div>
          <div
            className="flex-1 cursor-pointer"
            onClick={() => setShowCreateModal(true)}
          >
            <div className="w-full bg-kodo-void/50 border border-kodo-steel rounded-full px-4 py-2.5 text-gray-500 hover:bg-kodo-void hover:border-kodo-cyan/50 transition-all text-sm">
              What are you working on today?
            </div>
          </div>
        </div>
        <div className="flex justify-between items-center mt-3 pl-14">
          <div className="flex gap-4">
            <button
              className="flex items-center gap-1 text-gray-400 hover:text-kodo-cyan text-xs font-bold"
              onClick={() => setShowCreateModal(true)}
            >
              <ImageIcon className="w-4 h-4" /> Photo
            </button>
            <button
              className="flex items-center gap-1 text-gray-400 hover:text-kodo-magenta text-xs font-bold"
              onClick={() => setShowCreateModal(true)}
            >
              <Video className="w-4 h-4" /> Video
            </button>
            <button
              className="flex items-center gap-1 text-gray-400 hover:text-kodo-lime text-xs font-bold"
              onClick={() => setShowCreateModal(true)}
            >
              <Mic2 className="w-4 h-4" /> Audio
            </button>
            <button
              className="flex items-center gap-1 text-gray-400 hover:text-kodo-gold text-xs font-bold"
              onClick={() => setShowCreateModal(true)}
            >
              <BarChart className="w-4 h-4" /> Poll
            </button>
          </div>
        </div>
      </Card>

      {/* Posts Feed */}
      <div>
        {posts.map((post) => (
          <PostCard key={post.id} post={post} />
        ))}
      </div>

      {/* Load More Trigger */}
      <div className="text-center py-4">
        <Button variant="ghost" onClick={loadMore} disabled={loadingMore}>
          {loadingMore ? 'Loading...' : 'Load More'}
        </Button>
      </div>

      {showCreateModal && (
        <CreatePostModal
          onClose={() => setShowCreateModal(false)}
          onCreate={handleCreatePost}
        />
      )}
    </div>
  );
};
