/**
 * File: page.tsx
 * Created by: AI Assistant
 * Date: 2025-11-29
 * Purpose: Forum detail page for kreatiVortex platform
 * Part of: kreatiVortex - Platform Pembelajaran Tari Online
 */

'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';

interface ForumPost {
  id: string;
  title: string;
  content: string;
  createdAt: string;
  author: {
    user: {
      name: string;
      image?: string;
    };
  };
}

interface Forum {
  id: string;
  title: string;
  description?: string;
  createdAt: string;
  classId: string;
  creator: {
    user: {
      name: string;
      image?: string;
    };
  };
  posts: ForumPost[];
}

export default function ForumDetailPage() {
  const params = useParams();
  const [forum, setForum] = useState<Forum | null>(null);
  const [loading, setLoading] = useState(true);
  const [replyContent, setReplyContent] = useState('');
  const [submittingReply, setSubmittingReply] = useState(false);

  useEffect(() => {
    const fetchForum = async () => {
      try {
        const response = await fetch(`/api/forums/${params.id}`);
        const result = await response.json();

        if (result.success) {
          setForum(result.data);
        } else {
          console.error('Failed to fetch forum:', result.message);
        }
      } catch (error) {
        console.error('Error fetching forum:', error);
      } finally {
        setLoading(false);
      }
    };

    if (params.id) {
      fetchForum();
    }
  }, [params.id]);

  const handleReplySubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!replyContent.trim()) return;

    setSubmittingReply(true);

    try {
      const response = await fetch(`/api/forums/${params.id}/posts`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          content: replyContent,
        }),
      });

      const result = await response.json();

      if (result.success) {
        // Add the new post to the forum posts
        setForum(prev => prev ? {
          ...prev,
          posts: [result.data, ...prev.posts],
        } : null);

        // Clear the reply form
        setReplyContent('');
      } else {
        console.error('Failed to create reply:', result.message);
      }
    } catch (error) {
      console.error('Error creating reply:', error);
    } finally {
      setSubmittingReply(false);
    }
  };

  if (loading) {
    return <div className="text-white text-center">Loading...</div>;
  }

  if (!forum) {
    return <div className="text-white text-center">Forum not found</div>;
  }

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div className="flex justify-between items-center">
        <Link href={`/dashboard/forum/${forum.classId ? forum.classId : 'umum'}`} className="text-gray-400 hover:text-white flex items-center">
          <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
          Kembali ke Forum
        </Link>
      </div>

      {/* Main Post */}
      <div className="bg-white/10 backdrop-blur-sm rounded-xl p-6 border border-white/20">
        <div className="flex justify-between items-start mb-4">
          <div>
            <div className="flex items-center space-x-2 mb-2">
              <span className="text-xs text-gray-500">
                {new Date(forum.createdAt).toLocaleString()}
              </span>
            </div>
            <h1 className="text-2xl font-bold text-white mb-2">{forum.title}</h1>
          </div>
        </div>

        {forum.description && (
          <div className="flex items-start space-x-4 mb-6">
            <div className="w-10 h-10 bg-gold-400 rounded-full flex items-center justify-center flex-shrink-0">
              <span className="text-navy-900 font-bold">{forum.creator.user.name.charAt(0)}</span>
            </div>
            <div>
              <div className="flex items-center space-x-2">
                <span className="font-medium text-white">{forum.creator.user.name}</span>
                <span className="text-xs bg-gold-500/20 text-gold-400 px-2 py-0.5 rounded-full">
                  Pembuat Forum
                </span>
              </div>
              <div className="mt-2 text-gray-300 leading-relaxed">
                {forum.description}
              </div>
            </div>
          </div>
        )}

      </div>

      {/* Posts */}
      <div className="space-y-4">
        <h3 className="text-lg font-semibold text-white ml-2">{forum.posts.length} Diskusi</h3>

        {forum.posts.map((post) => (
          <div key={post.id} className="bg-white/5 backdrop-blur-sm rounded-xl p-6 border border-white/10 ml-8">
            <div className="flex items-start space-x-4">
              <div className="w-8 h-8 bg-gray-600 rounded-full flex items-center justify-center flex-shrink-0">
                <span className="text-white font-bold text-xs">{post.author.user.name.charAt(0)}</span>
              </div>
              <div className="flex-1">
                <div className="flex justify-between items-start mb-2">
                  <div className="flex items-center space-x-2">
                    <span className="font-medium text-white">{post.author.user.name}</span>
                  </div>
                  <span className="text-xs text-gray-500">
                    {new Date(post.createdAt).toLocaleString()}
                  </span>
                </div>
                <div className="text-gray-300 text-sm leading-relaxed">
                  {post.content}
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Reply Form */}
      <div className="bg-white/10 backdrop-blur-sm rounded-xl p-6 border border-white/20 mt-8">
        <h3 className="text-lg font-semibold text-white mb-4">Tulis Balasan</h3>
        <form onSubmit={handleReplySubmit}>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="reply" className="text-gray-300">
                Isi Balasan
              </Label>
              <Textarea
                id="reply"
                rows={4}
                value={replyContent}
                onChange={(e) => setReplyContent(e.target.value)}
                placeholder="Tulis balasan Anda di sini..."
                className="bg-white/10 border-white/20 text-white placeholder:text-gray-400"
                required
              />
            </div>
            <div className="flex justify-end">
              <Button
                type="submit"
                disabled={submittingReply || !replyContent.trim()}
                className="bg-gold-500 hover:bg-gold-600 text-navy-900"
              >
                {submittingReply ? 'Mengirim...' : 'Kirim Balasan'}
              </Button>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}