'use client';

/**
 * 1:1 문의 상세 컴포넌트
 *
 * 디자인 스펙:
 * - 페이지 타이틀: 1:1 문의 상세
 * - 페이지 설명: 1:1 문의를 조회합니다.
 * - 삭제/수정 버튼 (답변완료 후에는 수정 버튼 비활성화)
 * - 문의 영역 (제목, 작성자|날짜, 내용, 첨부파일)
 * - 답변 영역 (작성자|날짜, 내용, 첨부파일)
 * - 댓글 등록 입력창 + 등록 버튼
 * - 댓글 목록 (프로필, 이름, 내용, 날짜, 수정/삭제)
 */

import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { format } from 'date-fns';
import { MessageSquare, Download, ArrowLeft, Edit, Trash2, User } from 'lucide-react';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import {
  Card,
  CardContent,
} from '@/components/ui/card';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import type { Inquiry, Reply, Comment, Attachment } from './types';

interface InquiryDetailProps {
  inquiry: Inquiry;
  reply?: Reply;
  comments: Comment[];
  currentUserId: string;
}

export function InquiryDetail({
  inquiry,
  reply,
  comments: initialComments,
  currentUserId,
}: InquiryDetailProps) {
  const router = useRouter();
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [comments, setComments] = useState<Comment[]>(initialComments);
  const [newComment, setNewComment] = useState('');
  const [editingCommentId, setEditingCommentId] = useState<string | null>(null);
  const [editingContent, setEditingContent] = useState('');

  const isMyInquiry = inquiry.authorId === currentUserId;
  const canEdit = isMyInquiry && inquiry.status !== 'completed';

  // ===== 액션 핸들러 =====
  const handleBack = useCallback(() => {
    router.push('/ko/customer-center/inquiries');
  }, [router]);

  const handleEdit = useCallback(() => {
    router.push(`/ko/customer-center/inquiries/${inquiry.id}/edit`);
  }, [router, inquiry.id]);

  const handleConfirmDelete = useCallback(() => {
    // TODO: API 호출
    console.log('Delete inquiry:', inquiry.id);
    setShowDeleteDialog(false);
    router.push('/ko/customer-center/inquiries');
  }, [inquiry.id, router]);

  // ===== 댓글 핸들러 =====
  const handleAddComment = useCallback(() => {
    if (!newComment.trim()) return;

    const comment: Comment = {
      id: `comment-${Date.now()}`,
      inquiryId: inquiry.id,
      authorId: currentUserId,
      authorName: '홍길동', // 실제로는 사용자 정보에서 가져옴
      content: newComment.trim(),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    setComments((prev) => [...prev, comment]);
    setNewComment('');
    // TODO: API 호출
  }, [newComment, inquiry.id, currentUserId]);

  const handleStartEdit = useCallback((comment: Comment) => {
    setEditingCommentId(comment.id);
    setEditingContent(comment.content);
  }, []);

  const handleCancelEdit = useCallback(() => {
    setEditingCommentId(null);
    setEditingContent('');
  }, []);

  const handleSaveEdit = useCallback((id: string) => {
    if (!editingContent.trim()) return;

    setComments((prev) =>
      prev.map((c) =>
        c.id === id ? { ...c, content: editingContent.trim(), updatedAt: new Date().toISOString() } : c
      )
    );
    setEditingCommentId(null);
    setEditingContent('');
    // TODO: API 호출
  }, [editingContent]);

  const handleDeleteComment = useCallback((id: string) => {
    setComments((prev) => prev.filter((c) => c.id !== id));
    // TODO: API 호출
  }, []);

  // 파일 크기 포맷
  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  // 첨부파일 렌더링
  const renderAttachments = (attachments: Attachment[]) => {
    if (attachments.length === 0) return null;

    return (
      <div className="space-y-2 pt-4 border-t border-gray-100">
        {attachments.map((file) => (
          <a
            key={file.id}
            href={file.fileUrl}
            download={file.fileName}
            className="flex items-center gap-2 p-2 bg-gray-50 rounded-md hover:bg-gray-100 transition-colors"
          >
            <Download className="h-4 w-4 text-gray-500" />
            <span className="text-sm text-blue-600 hover:underline">
              {file.fileName}
            </span>
            <span className="text-xs text-gray-400">
              ({formatFileSize(file.fileSize)})
            </span>
          </a>
        ))}
      </div>
    );
  };

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader
        title="1:1 문의 상세"
        description="1:1 문의를 조회합니다."
        icon={MessageSquare}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={handleBack}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              목록
            </Button>
            {isMyInquiry && (
              <>
                <Button
                  variant="outline"
                  className="text-red-500 border-red-200 hover:bg-red-50 hover:text-red-600"
                  onClick={() => setShowDeleteDialog(true)}
                >
                  삭제
                </Button>
                <Button onClick={handleEdit} disabled={!canEdit}>
                  수정
                </Button>
              </>
            )}
          </div>
        }
      />

      {/* 문의 카드 */}
      <Card className="mb-6">
        <CardContent className="pt-6 space-y-4">
          {/* 섹션 타이틀 */}
          <div className="flex items-center gap-2">
            <span className="w-2 h-2 bg-red-500 rounded-full" />
            <h3 className="text-lg font-semibold">문의</h3>
          </div>

          {/* 제목 */}
          <h2 className="text-xl font-bold text-gray-900">{inquiry.title}</h2>

          {/* 메타 정보 */}
          <div className="flex items-center gap-2 text-sm text-gray-500">
            <span>{inquiry.authorName}</span>
            <span className="text-gray-300">|</span>
            <span>{format(new Date(inquiry.createdAt), 'yyyy-MM-dd HH:mm')}</span>
          </div>

          {/* 내용 (HTML 렌더링) */}
          <div
            className="prose prose-sm max-w-none min-h-[200px] p-4 bg-gray-50 rounded-lg"
            dangerouslySetInnerHTML={{ __html: inquiry.content }}
          />

          {/* 첨부파일 */}
          {renderAttachments(inquiry.attachments)}
        </CardContent>
      </Card>

      {/* 답변 카드 */}
      {reply && (
        <Card className="mb-6">
          <CardContent className="pt-6 space-y-4">
            {/* 섹션 타이틀 */}
            <div className="flex items-center gap-2">
              <span className="w-2 h-2 bg-red-500 rounded-full" />
              <h3 className="text-lg font-semibold">답변</h3>
            </div>

            {/* 메타 정보 */}
            <div className="flex items-center gap-2 text-sm text-gray-500">
              <span>{reply.authorName}</span>
              <span className="text-gray-300">|</span>
              <span>{format(new Date(reply.createdAt), 'yyyy-MM-dd HH:mm')}</span>
            </div>

            {/* 내용 (HTML 렌더링) */}
            <div
              className="prose prose-sm max-w-none min-h-[200px] p-4 bg-gray-50 rounded-lg"
              dangerouslySetInnerHTML={{ __html: reply.content }}
            />

            {/* 첨부파일 */}
            {renderAttachments(reply.attachments)}
          </CardContent>
        </Card>
      )}

      {/* 댓글 등록 */}
      <Card className="mb-6">
        <CardContent className="pt-6 space-y-4">
          <div className="flex items-center gap-2">
            <span className="w-2 h-2 bg-red-500 rounded-full" />
            <h3 className="text-lg font-semibold">댓글 등록</h3>
          </div>
          <Textarea
            value={newComment}
            onChange={(e) => setNewComment(e.target.value)}
            placeholder="댓글을 입력해주세요"
            className="min-h-[80px]"
          />
          <div className="flex justify-end">
            <Button onClick={handleAddComment}>등록</Button>
          </div>
        </CardContent>
      </Card>

      {/* 댓글 목록 */}
      {comments.length > 0 && (
        <Card>
          <CardContent className="pt-6 space-y-4">
            <div className="flex items-center gap-2">
              <span className="w-2 h-2 bg-red-500 rounded-full" />
              <h3 className="text-lg font-semibold">댓글 {comments.length}</h3>
            </div>

            <div className="space-y-4">
              {comments.map((comment) => (
                <div key={comment.id} className="flex gap-3 p-4 bg-gray-50 rounded-lg">
                  {/* 프로필 아바타 */}
                  <div className="h-10 w-10 rounded-full bg-gray-200 flex items-center justify-center shrink-0 overflow-hidden">
                    {comment.authorProfileImage ? (
                      <img
                        src={comment.authorProfileImage}
                        alt={comment.authorName}
                        className="h-full w-full object-cover"
                      />
                    ) : (
                      <User className="h-5 w-5 text-gray-500" />
                    )}
                  </div>

                  <div className="flex-1">
                    <div className="flex items-center justify-between mb-2">
                      <span className="font-medium">{comment.authorName}</span>
                      <div className="flex items-center gap-2">
                        {comment.authorId === currentUserId && editingCommentId !== comment.id && (
                          <>
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-8 w-8 p-0"
                              onClick={() => handleStartEdit(comment)}
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-8 w-8 p-0 text-red-500 hover:text-red-600"
                              onClick={() => handleDeleteComment(comment.id)}
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </>
                        )}
                        <span className="text-sm text-gray-500">
                          {format(new Date(comment.createdAt), 'yyyy-MM-dd HH:mm')}
                        </span>
                      </div>
                    </div>

                    {editingCommentId === comment.id ? (
                      <div className="space-y-2">
                        <Textarea
                          value={editingContent}
                          onChange={(e) => setEditingContent(e.target.value)}
                          className="min-h-[60px]"
                        />
                        <div className="flex justify-end gap-2">
                          <Button variant="outline" size="sm" onClick={handleCancelEdit}>
                            취소
                          </Button>
                          <Button size="sm" onClick={() => handleSaveEdit(comment.id)}>
                            저장
                          </Button>
                        </div>
                      </div>
                    ) : (
                      <p className="text-gray-700">{comment.content}</p>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>문의 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              정말 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}

export default InquiryDetail;