'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import {
  ChevronLeft,
  CheckCircle2,
  Send,
  ShieldCheck,
  MessageCircle,
  Eye,
  Calendar,
  ThumbsUp,
  Award,
  Sparkles,
  Check,
} from 'lucide-react';
import { CommunityPost, CommunityReply } from '@/types';
import { useAuth } from '@/context/AuthContext';

export default function CommunityPostDetailClient({ post }: { post: CommunityPost }) {
  const { user, isAdmin } = useAuth();
  const [currentPost, setCurrentPost] = useState<CommunityPost>(post);
  const [replies, setReplies] = useState<CommunityReply[]>(post.replies || []);
  const [replyText, setReplyText] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const activeUserId = user?.id || 'usr-demo';
  const isPostOwner = currentPost.user_id === activeUserId || isAdmin;

  // Upvote Post
  const handlePostUpvote = async () => {
    try {
      const res = await fetch(`/api/community/${currentPost.id}/upvote`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ user_id: activeUserId }),
      });
      const data = await res.json();
      if (data.upvotes !== undefined) {
        setCurrentPost({
          ...currentPost,
          upvotes: data.upvotes,
          upvoters: data.userHasUpvoted
            ? [...(currentPost.upvoters || []), activeUserId]
            : (currentPost.upvoters || []).filter((u) => u !== activeUserId),
        });
      }
    } catch {
      setCurrentPost({ ...currentPost, upvotes: (currentPost.upvotes || 0) + 1 });
    }
  };

  // Upvote Reply
  const handleReplyUpvote = async (replyId: string) => {
    try {
      const res = await fetch(`/api/community/${currentPost.id}/upvote`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ user_id: activeUserId, reply_id: replyId }),
      });
      const data = await res.json();
      if (data.upvotes !== undefined) {
        setReplies(
          replies.map((r) =>
            r.id === replyId
              ? {
                  ...r,
                  upvotes: data.upvotes,
                  upvoters: data.userHasUpvoted
                    ? [...(r.upvoters || []), activeUserId]
                    : (r.upvoters || []).filter((u) => u !== activeUserId),
                }
              : r
          )
        );
      }
    } catch {
      setReplies(
        replies.map((r) => (r.id === replyId ? { ...r, upvotes: (r.upvotes || 0) + 1 } : r))
      );
    }
  };

  // Mark as Accepted Solution
  const handleAcceptSolution = async (replyId: string) => {
    try {
      const res = await fetch(`/api/community/${currentPost.id}/solution`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reply_id: replyId }),
      });
      const data = await res.json();
      if (data.success) {
        setCurrentPost({
          ...currentPost,
          is_solved: true,
          solution_reply_id: replyId,
        });
        setReplies(
          replies.map((r) => ({
            ...r,
            is_solution: r.id === replyId,
          }))
        );
      }
    } catch {
      setReplies(
        replies.map((r) => ({
          ...r,
          is_solution: r.id === replyId,
        }))
      );
      setCurrentPost({ ...currentPost, is_solved: true, solution_reply_id: replyId });
    }
  };

  const handleReplySubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!replyText.trim()) return;

    setIsSubmitting(true);
    try {
      const payload = {
        user_id: activeUserId,
        user_name: user?.name || 'Developer Guest',
        user_avatar: user?.avatar,
        user_badge: isAdmin ? 'Admin' : 'Verified Buyer',
        is_admin: isAdmin,
        content: replyText.trim(),
      };

      const res = await fetch(`/api/community/${currentPost.id}/reply`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await res.json();
      if (data.reply) {
        setReplies([...replies, data.reply]);
        setReplyText('');
      }
    } catch {
      const localRep: CommunityReply = {
        id: `rep-${Date.now()}`,
        post_id: currentPost.id,
        user_id: activeUserId,
        user_name: user?.name || 'Developer Guest',
        user_badge: 'Verified Buyer',
        is_admin: Boolean(isAdmin),
        content: replyText.trim(),
        is_solution: false,
        upvotes: 0,
        upvoters: [],
        created_at: new Date().toISOString(),
      };
      setReplies([...replies, localRep]);
      setReplyText('');
    } finally {
      setIsSubmitting(false);
    }
  };

  const hasPostUpvoted = currentPost.upvoters?.includes(activeUserId);

  return (
    <div className="py-8 md:py-14 bg-gray-50 min-h-screen">
      <div className="container mx-auto px-4 max-w-4xl space-y-8">
        {/* Back Link */}
        <Link
          href="/community"
          className="inline-flex items-center gap-1.5 text-xs font-bold text-indigo-600 hover:text-indigo-700 transition"
        >
          <ChevronLeft className="w-4 h-4" />
          <span>Back to All Discussions</span>
        </Link>

        {/* Main Post Card */}
        <div className="bg-white rounded-3xl p-6 sm:p-10 shadow-sm border border-gray-100 space-y-6">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <div className="flex flex-wrap items-center gap-2">
              {currentPost.is_solved && (
                <span className="inline-flex items-center gap-1 text-[10px] font-black uppercase px-2.5 py-0.5 rounded-full bg-emerald-100 text-emerald-800">
                  <CheckCircle2 className="w-3.5 h-3.5" /> Accepted Solution
                </span>
              )}
              <span className="text-[10px] font-extrabold uppercase px-2.5 py-0.5 rounded-full bg-indigo-50 text-indigo-700">
                {currentPost.category_type || 'Question'}
              </span>
              {currentPost.product_title && (
                <span className="text-xs font-semibold bg-gray-100 text-gray-800 px-3 py-1 rounded-full">
                  {currentPost.product_title}
                </span>
              )}
              {currentPost.tags?.map((t) => (
                <span key={t} className="text-xs text-gray-400 font-medium">
                  #{t}
                </span>
              ))}
            </div>

            <button
              type="button"
              onClick={handlePostUpvote}
              className={`flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl font-bold text-xs transition ${
                hasPostUpvoted
                  ? 'bg-indigo-600 text-white shadow-sm'
                  : 'bg-gray-50 hover:bg-indigo-50 text-gray-700 hover:text-indigo-600'
              }`}
            >
              <ThumbsUp className="w-3.5 h-3.5" />
              <span>Upvote ({currentPost.upvotes || 0})</span>
            </button>
          </div>

          <h1 className="text-xl sm:text-3xl font-black text-gray-900 leading-tight">
            {currentPost.title}
          </h1>

          {/* Author info */}
          <div className="flex items-center gap-3 pt-2 pb-4 border-b border-gray-100 text-xs text-gray-500">
            <div className="w-9 h-9 rounded-full bg-indigo-100 text-indigo-700 font-black flex items-center justify-center">
              {currentPost.user_name.charAt(0)}
            </div>
            <div>
              <div className="flex items-center gap-2">
                <span className="font-extrabold text-gray-900">{currentPost.user_name}</span>
                {currentPost.user_badge && (
                  <span className="text-[9px] font-black uppercase px-1.5 py-0.5 bg-indigo-100 text-indigo-700 rounded-md">
                    {currentPost.user_badge}
                  </span>
                )}
              </div>
              <div className="flex items-center gap-2 text-[11px] text-gray-400 mt-0.5">
                <Calendar className="w-3 h-3" />
                <span>{new Date(currentPost.created_at).toLocaleDateString()}</span>
                <span>•</span>
                <Eye className="w-3 h-3" />
                <span>{currentPost.views || 1} views</span>
              </div>
            </div>
          </div>

          {/* Question content */}
          <div className="prose max-w-none text-gray-800 text-sm leading-relaxed whitespace-pre-line font-medium">
            {currentPost.content}
          </div>
        </div>

        {/* Replies List */}
        <div className="space-y-4">
          <h3 className="text-lg font-black text-gray-900 flex items-center gap-2">
            <MessageCircle className="w-5 h-5 text-indigo-600" />
            <span>Community Answers & Discussion ({replies.length})</span>
          </h3>

          {replies.map((reply) => {
            const hasReplyUpvoted = reply.upvoters?.includes(activeUserId);

            return (
              <div
                key={reply.id}
                className={`p-6 sm:p-7 rounded-3xl bg-white shadow-sm border transition relative space-y-4 ${
                  reply.is_solution
                    ? 'border-emerald-500 bg-emerald-50/20 ring-2 ring-emerald-500/20'
                    : reply.is_admin
                    ? 'border-indigo-200 bg-indigo-50/15'
                    : 'border-gray-100'
                }`}
              >
                {/* Solution Banner */}
                {reply.is_solution && (
                  <div className="inline-flex items-center gap-1.5 text-xs font-black uppercase bg-emerald-500 text-white px-3 py-1 rounded-xl shadow-xs">
                    <CheckCircle2 className="w-4 h-4" />
                    <span>Accepted Solution</span>
                  </div>
                )}

                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div
                      className={`w-8 h-8 rounded-full flex items-center justify-center font-black text-xs ${
                        reply.is_admin ? 'bg-indigo-600 text-white' : 'bg-gray-100 text-gray-700'
                      }`}
                    >
                      {reply.user_name.charAt(0)}
                    </div>
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-extrabold text-xs text-gray-900">
                          {reply.user_name}
                        </span>
                        {reply.user_badge && (
                          <span
                            className={`text-[9px] font-black uppercase px-1.5 py-0.5 rounded-md ${
                              reply.user_badge === 'Admin'
                                ? 'bg-indigo-600 text-white'
                                : 'bg-emerald-100 text-emerald-800'
                            }`}
                          >
                            {reply.user_badge}
                          </span>
                        )}
                      </div>
                      <span className="text-[10px] text-gray-400 block">
                        {new Date(reply.created_at).toLocaleDateString()}
                      </span>
                    </div>
                  </div>

                  {/* Actions: Upvote & Mark Solution */}
                  <div className="flex items-center gap-2">
                    <button
                      type="button"
                      onClick={() => handleReplyUpvote(reply.id)}
                      className={`flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-bold transition ${
                        hasReplyUpvoted
                          ? 'bg-indigo-600 text-white'
                          : 'bg-gray-100 hover:bg-indigo-50 text-gray-600 hover:text-indigo-600'
                      }`}
                    >
                      <ThumbsUp className="w-3 h-3" />
                      <span>{reply.upvotes || 0}</span>
                    </button>

                    {isPostOwner && !reply.is_solution && (
                      <button
                        type="button"
                        onClick={() => handleAcceptSolution(reply.id)}
                        className="px-3 py-1 bg-emerald-50 hover:bg-emerald-100 text-emerald-700 font-bold text-xs rounded-lg transition flex items-center gap-1"
                      >
                        <Check className="w-3.5 h-3.5" />
                        <span>Accept Solution</span>
                      </button>
                    )}
                  </div>
                </div>

                <div className="text-xs sm:text-sm text-gray-800 leading-relaxed whitespace-pre-line font-medium">
                  {reply.content}
                </div>
              </div>
            );
          })}
        </div>

        {/* Add Reply Form */}
        <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-gray-100 space-y-4">
          <h3 className="text-base font-extrabold text-gray-900">Post an Answer / Reply</h3>
          <form onSubmit={handleReplySubmit} className="space-y-4">
            <textarea
              rows={4}
              required
              placeholder="Write your solution, suggestion, or comment..."
              value={replyText}
              onChange={(e) => setReplyText(e.target.value)}
              className="w-full text-xs p-3.5 bg-gray-50 border border-gray-200 rounded-2xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600 font-medium"
            />

            <div className="flex justify-end">
              <button
                type="submit"
                disabled={isSubmitting || !replyText.trim()}
                className="px-6 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-extrabold text-xs rounded-xl shadow-md transition active:scale-95 flex items-center gap-2 disabled:opacity-50"
              >
                <Send className="w-3.5 h-3.5" />
                <span>{isSubmitting ? 'Submitting...' : 'Post Reply'}</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
