'use client';

/**
 * 개별 댓글 컴포넌트
 *
 * 디자인 스펙 기준:
 * - 프로필 이미지, 부서명 이름 직책, 등록일시, 댓글 내용
 * - 수정/삭제 버튼 (본인 댓글만)
 * - 수정 클릭 시 인풋박스에 기존 댓글 내용 입력 상태로 변경
 * - 삭제 클릭 시 "정말 삭제하시겠습니까?" 확인 Alert
 */

import { useState, useCallback, memo } from 'react';
import { format } from 'date-fns';
import { User, Edit, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import type { Comment } from '../types';

interface CommentItemProps {
  comment: Comment;
  currentUserId: string;
  onUpdate: (id: string, content: string) => void;
  onDelete: (id: string) => void;
}

export const CommentItem = memo(function CommentItem({
  comment,
  currentUserId,
  onUpdate,
  onDelete,
}: CommentItemProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [editContent, setEditContent] = useState(comment.content);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  const isMyComment = comment.authorId === currentUserId;

  // 수정 모드 토글
  const handleEditClick = useCallback(() => {
    setIsEditing(true);
    setEditContent(comment.content);
  }, [comment.content]);

  // 수정 취소
  const handleCancelEdit = useCallback(() => {
    setIsEditing(false);
    setEditContent(comment.content);
  }, [comment.content]);

  // 수정 저장
  const handleSaveEdit = useCallback(() => {
    if (editContent.trim()) {
      onUpdate(comment.id, editContent.trim());
      setIsEditing(false);
    }
  }, [comment.id, editContent, onUpdate]);

  // 삭제 확인
  const handleConfirmDelete = useCallback(() => {
    onDelete(comment.id);
    setShowDeleteDialog(false);
  }, [comment.id, onDelete]);

  // 작성자 정보 포맷
  const authorInfo = [
    comment.authorDepartment,
    comment.authorName,
    comment.authorPosition,
  ].filter(Boolean).join(' ');

  return (
    <div className="flex gap-3 py-4 border-b border-gray-100 last:border-0">
      {/* 프로필 이미지 */}
      <div className="flex-shrink-0">
        {comment.authorProfileImage ? (
          <img
            src={comment.authorProfileImage}
            alt={comment.authorName}
            className="w-10 h-10 rounded-full object-cover"
          />
        ) : (
          <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
            <User className="w-5 h-5 text-gray-500" />
          </div>
        )}
      </div>

      {/* 댓글 내용 */}
      <div className="flex-1 min-w-0">
        {/* 작성자 정보 + 날짜 + 버튼 */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-2 mb-1">
          <div className="flex items-center gap-2 text-sm">
            <span className="font-medium text-gray-900">{authorInfo}</span>
            <span className="text-gray-400">
              {format(new Date(comment.createdAt), 'yyyy-MM-dd HH:mm')}
            </span>
          </div>

          {/* 본인 댓글만 수정/삭제 버튼 표시 */}
          {isMyComment && !isEditing && (
            <div className="flex items-center gap-1">
              <Button
                variant="ghost"
                size="sm"
                className="h-7 px-2 text-gray-500 hover:text-gray-700"
                onClick={handleEditClick}
              >
                <Edit className="h-3 w-3 mr-1" />
                수정
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className="h-7 px-2 text-red-500 hover:text-red-600"
                onClick={() => setShowDeleteDialog(true)}
              >
                <Trash2 className="h-3 w-3 mr-1" />
                삭제
              </Button>
            </div>
          )}
        </div>

        {/* 댓글 본문 또는 수정 폼 */}
        {isEditing ? (
          <div className="space-y-2">
            <Textarea
              value={editContent}
              onChange={(e) => setEditContent(e.target.value)}
              placeholder="댓글을 입력해주세요"
              className="min-h-[80px]"
            />
            <div className="flex gap-2">
              <Button size="sm" onClick={handleSaveEdit}>
                저장
              </Button>
              <Button size="sm" variant="outline" onClick={handleCancelEdit}>
                취소
              </Button>
            </div>
          </div>
        ) : (
          <p className="text-gray-700 whitespace-pre-wrap">{comment.content}</p>
        )}
      </div>

      {/* 삭제 확인 다이얼로그 */}
      <DeleteConfirmDialog
        open={showDeleteDialog}
        onOpenChange={setShowDeleteDialog}
        onConfirm={handleConfirmDelete}
        title="댓글 삭제"
        description="정말 삭제하시겠습니까?"
      />
    </div>
  );
});

export default CommentItem;