'use client';

/**
 * 동적 게시판 상세 페이지
 * mode=edit인 경우 수정 폼 렌더링
 */

import { useParams, useRouter, useSearchParams } from 'next/navigation';
import { DynamicBoardEditForm } from '@/components/board/DynamicBoard/DynamicBoardEditForm';
import { useState, useEffect, useCallback, Suspense } from 'react';
import { DetailPageSkeleton } from '@/components/ui/skeleton';
import { format } from 'date-fns';
import { ArrowLeft, Edit, Trash2, MessageSquare, Eye } from 'lucide-react';
import { useMenuStore } from '@/stores/menuStore';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import {
  getDynamicBoardPost,
  getDynamicBoardComments,
  createDynamicBoardComment,
  updateDynamicBoardComment,
  deleteDynamicBoardComment,
  deleteDynamicBoardPost,
} from '@/components/board/DynamicBoard/actions';
import { getBoardByCode } from '@/components/board/BoardManagement/actions';
import { transformApiToComment } from '@/components/customer-center/shared/types';
import type { PostApiData } from '@/components/customer-center/shared/types';
import { sanitizeHTML } from '@/lib/sanitize';

interface BoardPost {
  id: string;
  title: string;
  content: string;
  authorId: string;
  authorName: string;
  status: string;
  views: number;
  isNotice: boolean;
  createdAt: string;
  updatedAt: string;
}

interface Comment {
  id: string;
  inquiryId: string;
  authorId: string;
  authorName: string;
  authorProfileImage?: string;
  content: string;
  createdAt: string;
  updatedAt: string;
}

// API 데이터 → 프론트엔드 타입 변환
function transformApiToPost(apiData: PostApiData): BoardPost {
  return {
    id: String(apiData.id),
    title: apiData.title,
    content: apiData.content,
    authorId: String(apiData.user_id),
    authorName: apiData.author?.name || '회원',
    status: apiData.status,
    views: apiData.views,
    isNotice: apiData.is_notice,
    createdAt: apiData.created_at,
    updatedAt: apiData.updated_at,
  };
}

// Suspense로 감싸는 wrapper 컴포넌트
export default function DynamicBoardDetailPage() {
  return (
    <Suspense fallback={<DetailPageSkeleton />}>
      <DetailModeRouter />
    </Suspense>
  );
}

// mode에 따라 다른 컴포넌트 렌더링 (hooks rule 준수)
function DetailModeRouter() {
  const params = useParams();
  const searchParams = useSearchParams();
  const boardCode = params.boardCode as string;
  const postId = params.postId as string;
  const mode = searchParams.get('mode');

  // mode=edit인 경우 수정 폼 렌더링
  if (mode === 'edit') {
    return <DynamicBoardEditForm boardCode={boardCode} postId={postId} />;
  }

  return <DynamicBoardDetailContent boardCode={boardCode} postId={postId} />;
}

// 실제 상세 컴포넌트 (자체 hooks 사용)
function DynamicBoardDetailContent({ boardCode, postId }: { boardCode: string; postId: string }) {
  const router = useRouter();
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);

  // 게시판 정보
  const [boardName, setBoardName] = useState<string>('게시판');

  // 게시글 및 댓글
  const [post, setPost] = useState<BoardPost | null>(null);
  const [comments, setComments] = useState<Comment[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [currentUserId, setCurrentUserId] = useState<string>('');

  // 댓글 입력
  const [newComment, setNewComment] = useState('');
  const [editingCommentId, setEditingCommentId] = useState<string | null>(null);
  const [editingContent, setEditingContent] = useState('');

  // 삭제 다이얼로그
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  // 현재 사용자 ID 가져오기
  useEffect(() => {
    const userStr = localStorage.getItem('user');
    if (userStr) {
      try {
        const user = JSON.parse(userStr);
        setCurrentUserId(String(user.id || ''));
      } catch {
        setCurrentUserId('');
      }
    }
  }, []);

  // 게시판 정보 로드
  useEffect(() => {
    async function fetchBoardInfo() {
      const result = await getBoardByCode(boardCode);
      if (result.success && result.data) {
        setBoardName(result.data.boardName);
      }
    }
    fetchBoardInfo();
  }, [boardCode]);

  // 데이터 로드
  useEffect(() => {
    async function fetchData() {
      setIsLoading(true);
      setError(null);

      const [postResult, commentsResult] = await Promise.all([
        getDynamicBoardPost(boardCode, postId),
        getDynamicBoardComments(boardCode, postId),
      ]);

      if (postResult.success && postResult.data) {
        setPost(transformApiToPost(postResult.data));
      } else {
        setError(postResult.error || '게시글을 찾을 수 없습니다.');
      }

      if (commentsResult.success && commentsResult.data) {
        setComments(commentsResult.data.map(transformApiToComment));
      }

      setIsLoading(false);
    }

    fetchData();
  }, [boardCode, postId]);

  // 댓글 추가
  const handleAddComment = useCallback(async () => {
    if (!newComment.trim()) return;

    const result = await createDynamicBoardComment(boardCode, postId, newComment);
    if (result.success && result.data) {
      setComments((prev) => [...prev, transformApiToComment(result.data!)]);
      setNewComment('');
    } else {
      console.error('댓글 등록 실패:', result.error);
    }
  }, [boardCode, postId, newComment]);

  // 댓글 수정
  const handleUpdateComment = useCallback(async (commentId: string) => {
    if (!editingContent.trim()) return;

    const result = await updateDynamicBoardComment(boardCode, postId, commentId, editingContent);
    if (result.success && result.data) {
      setComments((prev) =>
        prev.map((c) => (c.id === commentId ? transformApiToComment(result.data!) : c))
      );
      setEditingCommentId(null);
      setEditingContent('');
    } else {
      console.error('댓글 수정 실패:', result.error);
    }
  }, [boardCode, postId, editingContent]);

  // 댓글 삭제
  const handleDeleteComment = useCallback(async (commentId: string) => {
    const result = await deleteDynamicBoardComment(boardCode, postId, commentId);
    if (result.success) {
      setComments((prev) => prev.filter((c) => c.id !== commentId));
    } else {
      console.error('댓글 삭제 실패:', result.error);
    }
  }, [boardCode, postId]);

  // 게시글 삭제
  const handleDeletePost = useCallback(async () => {
    const result = await deleteDynamicBoardPost(boardCode, postId);
    if (result.success) {
      router.push(`/ko/boards/${boardCode}`);
    } else {
      console.error('게시글 삭제 실패:', result.error);
    }
  }, [boardCode, postId, router]);

  // 수정 페이지로 이동
  const handleEdit = useCallback(() => {
    router.push(`/ko/boards/${boardCode}/${postId}?mode=edit`);
  }, [router, boardCode, postId]);

  // 목록으로 이동
  const handleBack = useCallback(() => {
    router.push(`/ko/boards/${boardCode}`);
  }, [router, boardCode]);

  if (isLoading) {
    return (
      <PageLayout>
        <DetailPageSkeleton />
      </PageLayout>
    );
  }

  if (error || !post) {
    return (
      <PageLayout>
        <div className="flex flex-col items-center justify-center min-h-[400px] gap-4">
          <p className="text-muted-foreground">{error || '게시글을 찾을 수 없습니다.'}</p>
          <Button variant="outline" onClick={handleBack}>
            <ArrowLeft className="h-4 w-4 mr-2" />
            목록으로
          </Button>
        </div>
      </PageLayout>
    );
  }

  const isAuthor = currentUserId === post.authorId;

  return (
    <PageLayout>
      <PageHeader
        title={boardName}
        description="게시글 상세"
        icon={MessageSquare}
      />

      <div className="pb-24">
      {/* 게시글 상세 */}
      <Card className="mb-6">
        <CardHeader>
          <div className="flex items-start justify-between">
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                {post.isNotice && (
                  <Badge variant="destructive">공지</Badge>
                )}
                <CardTitle className="text-xl">{post.title}</CardTitle>
              </div>
              <div className="flex items-center gap-4 text-sm text-muted-foreground">
                <span>{post.authorName}</span>
                <span>{format(new Date(post.createdAt), 'yyyy-MM-dd HH:mm')}</span>
                <span className="flex items-center gap-1">
                  <Eye className="h-4 w-4" />
                  {post.views}
                </span>
              </div>
            </div>
            {isAuthor && (
              <div className="hidden md:flex items-center gap-2">
                <Button variant="outline" size="sm" onClick={handleEdit}>
                  <Edit className="h-4 w-4 mr-1" />
                  수정
                </Button>
                <Button variant="destructive" size="sm" onClick={() => setShowDeleteDialog(true)}>
                  <Trash2 className="h-4 w-4 mr-1" />
                  삭제
                </Button>
              </div>
            )}
          </div>
        </CardHeader>
        <Separator />
        <CardContent className="pt-6">
          <div
            className="prose prose-sm max-w-none"
            dangerouslySetInnerHTML={{ __html: sanitizeHTML(post.content) }}
          />
        </CardContent>
      </Card>

      {/* 댓글 섹션 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <MessageSquare className="h-5 w-5" />
            댓글 ({comments.length})
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 댓글 목록 */}
          {comments.length > 0 ? (
            <div className="space-y-4">
              {comments.map((comment) => (
                <div key={comment.id} className="border rounded-lg p-4">
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-2">
                      <span className="font-medium">{comment.authorName}</span>
                      <span className="text-sm text-muted-foreground">
                        {format(new Date(comment.createdAt), 'yyyy-MM-dd HH:mm')}
                      </span>
                    </div>
                    {currentUserId === comment.authorId && (
                      <div className="flex items-center gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setEditingCommentId(comment.id);
                            setEditingContent(comment.content);
                          }}
                        >
                          수정
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="text-destructive"
                          onClick={() => handleDeleteComment(comment.id)}
                        >
                          삭제
                        </Button>
                      </div>
                    )}
                  </div>
                  {editingCommentId === comment.id ? (
                    <div className="mt-2 space-y-2">
                      <Textarea
                        value={editingContent}
                        onChange={(e) => setEditingContent(e.target.value)}
                        rows={3}
                      />
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            setEditingCommentId(null);
                            setEditingContent('');
                          }}
                        >
                          취소
                        </Button>
                        <Button size="sm" onClick={() => handleUpdateComment(comment.id)}>
                          저장
                        </Button>
                      </div>
                    </div>
                  ) : (
                    <p className="mt-2 text-sm">{comment.content}</p>
                  )}
                </div>
              ))}
            </div>
          ) : (
            <p className="text-center text-muted-foreground py-8">
              첫 번째 댓글을 작성해보세요.
            </p>
          )}

          {/* 댓글 입력 */}
          <Separator />
          <div className="space-y-2">
            <Textarea
              placeholder="댓글을 입력하세요..."
              value={newComment}
              onChange={(e) => setNewComment(e.target.value)}
              rows={3}
            />
            <div className="flex justify-end">
              <Button onClick={handleAddComment} disabled={!newComment.trim()}>
                댓글 등록
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
      </div>

      {/* 하단 액션 버튼 (sticky) */}
      <div
        className={`fixed bottom-4 left-4 right-4 px-4 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 md:bottom-6 md:px-6 md:right-[48px] ${sidebarCollapsed ? 'md:left-[156px]' : 'md:left-[316px]'} flex items-center justify-between`}
      >
        <Button variant="outline" onClick={handleBack} size="sm" className="md:size-default">
          <ArrowLeft className="w-4 h-4 md:mr-2" />
          <span className="hidden md:inline">목록으로</span>
        </Button>
        {isAuthor && (
          <div className="flex items-center gap-1 md:gap-2">
            <Button
              variant="outline"
              onClick={() => setShowDeleteDialog(true)}
              size="sm"
              className="text-destructive hover:bg-destructive hover:text-destructive-foreground md:size-default"
            >
              <Trash2 className="w-4 h-4 md:mr-2" />
              <span className="hidden md:inline">삭제</span>
            </Button>
            <Button onClick={handleEdit} size="sm" className="md:size-default">
              <Edit className="w-4 h-4 md:mr-2" />
              <span className="hidden md:inline">수정</span>
            </Button>
          </div>
        )}
      </div>

      {/* 게시글 삭제 확인 다이얼로그 */}
      <DeleteConfirmDialog
        open={showDeleteDialog}
        onOpenChange={setShowDeleteDialog}
        onConfirm={handleDeletePost}
        title="게시글 삭제"
        description="이 게시글을 삭제하시겠습니까? 삭제된 게시글은 복구할 수 없습니다."
      />
    </PageLayout>
  );
}