'use client';

import { useState, useEffect } from 'react';
import { MessageCircle, Send, Inbox } from 'lucide-react';
import { useAuthStore } from '@/stores/authStore';
import { format } from 'date-fns';

export default function Forum() {
  const user = useAuthStore((state) => state.user);
  const [posts, setPosts] = useState([]);
  const [filteredPosts, setFilteredPosts] = useState([]);
  const [newPost, setNewPost] = useState('');
  const [newTags, setNewTags] = useState('');
  const [newResponses, setNewResponses] = useState({});
  const [loading, setLoading] = useState(false);
  const [token, setToken] = useState('');
  const [selectedTag, setSelectedTag] = useState('');
  const [availableTags, setAvailableTags] = useState([]);

  const formatDate = (iso) => {
    if (!iso) return '';
    return format(new Date(iso), 'dd MMM yyyy, HH:mm');
  };

  useEffect(() => {
    const storedToken = localStorage.getItem('token');
    if (storedToken) setToken(storedToken);
    fetchPosts();
  }, []);

  useEffect(() => {
    if (selectedTag === '') {
      setFilteredPosts(posts);
    } else {
      setFilteredPosts(posts.filter(post => post.tags?.includes(selectedTag)));
    }
  }, [selectedTag, posts]);

  const fetchPosts = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/forum/posts');
      const data = await res.json();
      const enriched = data.map((post) => ({
        ...post,
        tags: post.tags || [],
      }));
      setPosts(enriched);
      setFilteredPosts(enriched);

      const tagSet = new Set();
      enriched.forEach((post) => {
        post.tags.forEach((tag) => tagSet.add(tag));
      });
      setAvailableTags(Array.from(tagSet).sort());
    } catch (error) {
      console.error('Failed to fetch posts:', error);
    } finally {
      setLoading(false);
    }
  };

  const handlePostSubmit = async () => {
    if (!newPost.trim()) return;

    const tagList = newTags
      .split(',')
      .map((tag) => tag.trim())
      .filter((tag) => tag !== '');

    try {
      const res = await fetch('/api/forum/posts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          content: newPost,
          tags: tagList,
        }),
      });

      if (!res.ok) throw new Error('Post creation failed');
      const created = await res.json();
      const enrichedPost = {
        ...created,
        tags: tagList,
        author: created.author || user,
        responses: [],
      };
      const updatedPosts = [enrichedPost, ...posts];
      setPosts(updatedPosts);
      setNewPost('');
      setNewTags('');

      const newTagSet = new Set(tagList.concat(...availableTags));
      setAvailableTags(Array.from(newTagSet).sort());
    } catch (err) {
      console.error(err.message);
    }
  };

  const handleResponseSubmit = async (postId) => {
    const responseText = newResponses[postId];
    if (!responseText?.trim()) return;
    try {
      const res = await fetch(`/api/forum/posts/${postId}/responses`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ content: responseText }),
      });
      if (!res.ok) throw new Error('Failed to add response');
      const response = await res.json();
      const enrichedResponse = {
        ...response,
        author: response.author || user,
      };
      setPosts((prev) =>
        prev.map((post) =>
          post.id === postId
            ? {
                ...post,
                responses: [...post.responses, enrichedResponse],
              }
            : post
        )
      );
      setNewResponses((prev) => ({ ...prev, [postId]: '' }));
    } catch (err) {
      console.error(err.message);
    }
  };

  const renderAuthorName = (author) => {
    if (!author || !author.id) return 'Unknown Doctor';
    if (user && user.id === author.id) return 'You';
    return `${author.firstName || ''} ${author.last_name || ''}`.trim() || 'Doctor';
  };

  return (
    <div className="space-y-6 max-w-5xl mx-auto px-4 py-8">
      {/* Header */}
      <div className="bg-white p-6 rounded-lg shadow-md text-center">
        <h2 className="text-3xl font-bold text-gray-800 mb-1">Doctor Forum</h2>
        <p className="text-sm text-gray-500">
          Post and respond to medical topics shared by fellow Nigerian doctors.
        </p>
      </div>

      {/* New Post */}
      <div className="bg-white p-4 rounded-lg shadow-md">
        <textarea
          rows={3}
          className="w-full p-2 border border-gray-300 rounded focus:outline-none focus:ring text-sm"
          placeholder="Share a tip, ask a question, or start a discussion..."
          value={newPost}
          onChange={(e) => setNewPost(e.target.value)}
        />
        <input
          type="text"
          className="mt-2 w-full p-2 border border-gray-300 rounded text-sm"
          placeholder="Add tags (comma-separated e.g. surgery, pediatrics)"
          value={newTags}
          onChange={(e) => setNewTags(e.target.value)}
        />
        <button
          onClick={handlePostSubmit}
          className="mt-2 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-2"
        >
          <Send className="w-4 h-4" /> Post
        </button>
      </div>

      {/* Tag Filters */}
      {availableTags.length > 0 && (
        <div className="flex flex-wrap gap-2 mt-4">
          <button
            className={`px-3 py-1 text-sm rounded-full border ${selectedTag === '' ? 'bg-blue-600 text-white' : 'text-blue-600'}`}
            onClick={() => setSelectedTag('')}
          >
            All
          </button>
          {availableTags.map((tag) => (
            <button
              key={tag}
              onClick={() => setSelectedTag(tag)}
              className={`px-3 py-1 text-sm rounded-full border ${selectedTag === tag ? 'bg-blue-600 text-white' : 'text-blue-600'}`}
            >
              #{tag}
            </button>
          ))}
        </div>
      )}

      {/* Posts */}
      {loading ? (
        <div className="flex justify-center items-center text-gray-500">Loading posts...</div>
      ) : filteredPosts.length === 0 ? (
        <div className="bg-white p-6 rounded-lg shadow text-center flex flex-col items-center gap-3">
          <Inbox className="w-12 h-12 text-blue-400" />
          <p className="text-lg font-semibold text-gray-700">No forum posts yet</p>
          <p className="text-sm text-gray-500">
            Be the first to share your experience, raise a question, or offer guidance.
          </p>
        </div>
      ) : (
        <div className="space-y-6">
          {filteredPosts.map((post) => (
            <div key={post.id} className="bg-white p-4 rounded-lg shadow-sm">
              <p className="font-semibold text-gray-800">
                {renderAuthorName(post.author)}{' '}
                <span className="text-gray-400 text-xs font-normal">
                  • {formatDate(post.createdAt)}
                </span>
              </p>
              <p className="text-gray-700 mt-1">{post.content}</p>

              {/* Tags */}
              {post.tags?.length > 0 && (
                <div className="mt-2 flex flex-wrap gap-2">
                  {post.tags.map((tag, idx) => (
                    <span
                      key={idx}
                      className="bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full text-xs"
                    >
                      #{tag}
                    </span>
                  ))}
                </div>
              )}

              {/* Responses */}
              {post.responses?.length > 0 && (
                <div className="mt-4 space-y-2 border-t pt-2 border-gray-200">
                  {[...post.responses]
                    .sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
                    .map((res) => (
                      <div key={res.id} className="pl-2 border-l-2 border-blue-400">
                        <p className="text-sm text-gray-800">
                          <span className="font-semibold">
                            {renderAuthorName(res.author)}:
                          </span>{' '}
                          {res.content}
                        </p>
                        <p className="text-xs text-gray-400 ml-2">{formatDate(res.createdAt)}</p>
                      </div>
                    ))}
                </div>
              )}

              {/* Response Input */}
              <div className="mt-3">
                <textarea
                  rows={2}
                  className="w-full p-2 border border-gray-300 rounded text-sm"
                  placeholder="Write a response..."
                  value={newResponses[post.id] || ''}
                  onChange={(e) =>
                    setNewResponses((prev) => ({
                      ...prev,
                      [post.id]: e.target.value,
                    }))
                  }
                />
                <button
                  onClick={() => handleResponseSubmit(post.id)}
                  className="mt-1 px-3 py-1 bg-green-600 text-white text-sm rounded hover:bg-green-700 flex items-center gap-1"
                >
                  <MessageCircle className="w-4 h-4" /> Respond
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
