"use client";

import { useState, useEffect } from "react";
import { UserEntity } from "@/schema/entity/UserEntity";
import { PostEntity } from "@/schema/entity/PostEntity";
import { TagEntity } from "@/schema/entity/TagEntity";

interface PostWithUser extends PostEntity {
  user: UserEntity | null;
  tags: TagEntity[];
}

export default function Home() {
  const [posts, setPosts] = useState<PostWithUser[]>([]);
  const [users, setUsers] = useState<UserEntity[]>([]);
  const [tags, setTags] = useState<TagEntity[]>([]);
  const [filteredPosts, setFilteredPosts] = useState<PostWithUser[]>([]);
  const [selectedUser, setSelectedUser] = useState<string | null>(null);
  const [selectedTag, setSelectedTag] = useState<string | null>(null);
  const [content, setContent] = useState("");
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);

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

  useEffect(() => {
    let filtered = posts;

    if (selectedUser) {
      filtered = filtered.filter(post => post.userEmail === selectedUser);
    }

    if (selectedTag) {
      filtered = filtered.filter(post =>
        post.tags && post.tags.some(tag => tag.name === selectedTag)
      );
    }

    setFilteredPosts(filtered);
  }, [posts, selectedUser, selectedTag]);

  const fetchData = async () => {
    try {
      const response = await fetch('/api/data');
      const data = await response.json();
      setPosts(data.posts || []);
      setUsers(data.users || []);
      setTags(data.tags || []);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  const handleSubmitPost = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!content.trim() || !username.trim() || !email.trim()) {
      alert('Please fill in all fields');
      return;
    }

    setLoading(true);
    try {
      const response = await fetch('/api/posts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          content: content.trim(),
          username: username.trim(),
          email: email.trim(),
        }),
      });

      if (response.ok) {
        setContent("");
        setUsername("");
        setEmail("");
        await fetchData(); // Refresh data
      } else {
        alert('Failed to create post');
      }
    } catch (error) {
      console.error('Error creating post:', error);
      alert('Error creating post');
    } finally {
      setLoading(false);
    }
  };

  const handleUserClick = (userEmail: string) => {
    if (selectedUser === userEmail) {
      setSelectedUser(null); // Deselect if clicking same user
    } else {
      setSelectedUser(userEmail);
      setSelectedTag(null); // Clear tag filter when selecting user
    }
  };

  const handleTagClick = (tagName: string) => {
    if (selectedTag === tagName) {
      setSelectedTag(null); // Deselect if clicking same tag
    } else {
      setSelectedTag(tagName);
      setSelectedUser(null); // Clear user filter when selecting tag
    }
  };

  const clearAllFilters = () => {
    setSelectedUser(null);
    setSelectedTag(null);
  };

  const renderPostContent = (content: string) => {
    // Convert hashtags to clickable elements
    const parts = content.split(/(#[a-zA-Z0-9_]+)/g);
    return parts.map((part, index) => {
      if (part.match(/^#[a-zA-Z0-9_]+$/)) {
        const tagName = part.slice(1).toLowerCase();
        return (
          <span
            key={index}
            className="text-blue-600 cursor-pointer hover:text-blue-800 font-medium"
            onClick={() => handleTagClick(tagName)}
          >
            {part}
          </span>
        );
      }
      return part;
    });
  };

  return (
    <div className="max-w-7xl mx-auto p-6 space-y-8">
      <h1 className="text-3xl font-bold text-center">Posts, Users & Tags</h1>

      {/* Post Creation Form */}
      <div className="bg-white p-6 rounded-lg shadow-md">
        <h2 className="text-2xl font-semibold mb-4">Create New Post</h2>
        <p className="text-sm text-gray-600 mb-4">
          Use hashtags like #javascript #coding to categorize your posts!
        </p>
        <form onSubmit={handleSubmitPost} className="space-y-4">
          <div>
            <label htmlFor="username" className="block text-sm font-medium text-gray-700 mb-1">
              Username
            </label>
            <input
              type="text"
              id="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="Enter your username"
              required
            />
          </div>

          <div>
            <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
              Email
            </label>
            <input
              type="email"
              id="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="Enter your email"
              required
            />
          </div>

          <div>
            <label htmlFor="content" className="block text-sm font-medium text-gray-700 mb-1">
              Post Content
            </label>
            <textarea
              id="content"
              value={content}
              onChange={(e) => setContent(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 h-32 resize-vertical"
              placeholder="What's on your mind? Use #hashtags to categorize your post!"
              required
            />
          </div>

          <button
            type="submit"
            disabled={loading}
            className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? 'Creating Post...' : 'Create Post'}
          </button>
        </form>
      </div>

      {/* Filter Status */}
      {(selectedUser || selectedTag) && (
        <div className="bg-blue-50 p-4 rounded-lg">
          <div className="flex items-center justify-between">
            <span className="text-blue-800">
              {selectedUser && `Filtering by user: ${selectedUser}`}
              {selectedTag && `Filtering by tag: #${selectedTag}`}
            </span>
            <button
              onClick={clearAllFilters}
              className="text-blue-600 hover:text-blue-800 underline"
            >
              Clear all filters
            </button>
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Users List */}
        <div className="bg-white p-6 rounded-lg shadow-md">
          <h2 className="text-2xl font-semibold mb-4">Users</h2>
          {users.length === 0 ? (
            <p className="text-gray-500">No users found</p>
          ) : (
            <div className="space-y-2">
              {users.map((user) => (
                <div
                  key={user.id}
                  className={`p-3 border rounded-md cursor-pointer transition-colors ${selectedUser === user.email
                      ? 'bg-blue-100 border-blue-300'
                      : 'hover:bg-gray-50 border-gray-200'
                    }`}
                  onClick={() => user.email && handleUserClick(user.email)}
                >
                  <div className="font-medium">{user.name || 'Unknown User'}</div>
                  <div className="text-sm text-gray-600">{user.email}</div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Tags List */}
        <div className="bg-white p-6 rounded-lg shadow-md">
          <h2 className="text-2xl font-semibold mb-4">Tags</h2>
          {tags.length === 0 ? (
            <p className="text-gray-500">No tags found</p>
          ) : (
            <div className="flex flex-wrap gap-2">
              {tags.map((tag) => (
                <span
                  key={tag.id}
                  className={`px-3 py-1 rounded-full text-sm cursor-pointer transition-colors ${selectedTag === tag.name
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                    }`}
                  onClick={() => handleTagClick(tag.name)}
                >
                  #{tag.name}
                </span>
              ))}
            </div>
          )}
        </div>

        {/* Posts List */}
        <div className="bg-white p-6 rounded-lg shadow-md">
          <h2 className="text-2xl font-semibold mb-4">
            Posts ({filteredPosts.length})
          </h2>
          {filteredPosts.length === 0 ? (
            <p className="text-gray-500">
              {selectedUser || selectedTag ? 'No posts found with current filters' : 'No posts found'}
            </p>
          ) : (
            <div className="space-y-4">
              {filteredPosts.map((post) => (
                <div key={post.id} className="border border-gray-200 rounded-md p-4">
                  <div className="flex justify-between items-start mb-2">
                    <div>
                      <span
                        className="font-medium text-blue-600 cursor-pointer hover:text-blue-800"
                        onClick={() => handleUserClick(post.userEmail)}
                      >
                        {post.username}
                      </span>
                      <span className="text-sm text-gray-500 ml-2">({post.userEmail})</span>
                    </div>
                    <span className="text-xs text-gray-400">
                      {new Date(post.createdAt).toLocaleDateString()}
                    </span>
                  </div>
                  <p className="text-gray-800 whitespace-pre-wrap mb-3">
                    {renderPostContent(post.content)}
                  </p>
                  {post.tags && post.tags.length > 0 && (
                    <div className="flex flex-wrap gap-1">
                      {post.tags.map((tag) => (
                        <span
                          key={tag.id}
                          className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded cursor-pointer hover:bg-blue-200"
                          onClick={() => handleTagClick(tag.name)}
                        >
                          #{tag.name}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
