'use client';

import { useState, useMemo, useRef, ChangeEvent, useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import AdminSidebar from "@/app/components/AdminSidebar";
import BackArrowSvg from "@/app/svgs/backarrow";
import CloseXOSvg from "@/app/svgs/closexo";
import apiService from "@/app/lib/apiService";
import NoticeValidationModal from "@/app/admin/notices/NoticeValidationModal";
import NoticeCancelModal from "@/app/admin/notices/NoticeCancelModal";
import NoChangesModal from "@/app/admin/notices/NoChangesModal";

type Attachment = {
  name: string;
  size: string;
  url?: string;
  fileKey?: string;
};

export default function AdminNoticeEditPage() {
  const params = useParams();
  const router = useRouter();
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [attachedFile, setAttachedFile] = useState<File | null>(null);
  const [fileKey, setFileKey] = useState<string | null>(null);
  const [existingAttachment, setExistingAttachment] = useState<Attachment | null>(null);
  const [originalTitle, setOriginalTitle] = useState<string>('');
  const [originalContent, setOriginalContent] = useState<string>('');
  const [originalFileKey, setOriginalFileKey] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingData, setIsLoadingData] = useState(true);
  const [isValidationModalOpen, setIsValidationModalOpen] = useState(false);
  const [isCancelModalOpen, setIsCancelModalOpen] = useState(false);
  const [isNoChangesModalOpen, setIsNoChangesModalOpen] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const characterCount = useMemo(() => content.length, [content]);

  // 공지사항 데이터 로드
  useEffect(() => {
    async function fetchNotice() {
      if (!params?.id) {
        setIsLoadingData(false);
        return;
      }

      try {
        setIsLoadingData(true);
        const response = await apiService.getNotice(params.id);
        const data = response.data;

        // 제목 설정
        const loadedTitle = data.title || '';
        setTitle(loadedTitle);
        setOriginalTitle(loadedTitle);

        // 내용 설정 (배열이면 join, 문자열이면 그대로)
        let loadedContent = '';
        if (data.content) {
          if (Array.isArray(data.content)) {
            loadedContent = data.content.join('\n');
          } else if (typeof data.content === 'string') {
            loadedContent = data.content;
          } else {
            loadedContent = String(data.content);
          }
        }
        setContent(loadedContent);
        setOriginalContent(loadedContent);

        // 기존 첨부파일 정보 설정
        if (data.attachments && Array.isArray(data.attachments) && data.attachments.length > 0) {
          const att = data.attachments[0];
          setExistingAttachment({
            name: att.name || att.fileName || att.filename || '첨부파일',
            size: att.size || att.fileSize || '',
            url: att.url || att.downloadUrl,
            fileKey: att.fileKey || att.key || att.fileId,
          });
          // 기존 파일이 있으면 fileKey도 설정
          const loadedFileKey = att.fileKey || att.key || att.fileId;
          if (loadedFileKey) {
            setFileKey(loadedFileKey);
            setOriginalFileKey(loadedFileKey);
          }
        } else if (data.attachment) {
          // 단일 첨부파일인 경우
          setExistingAttachment({
            name: data.attachment.name || data.attachment.fileName || data.attachment.filename || '첨부파일',
            size: data.attachment.size || data.attachment.fileSize || '',
            url: data.attachment.url || data.attachment.downloadUrl,
            fileKey: data.attachment.fileKey || data.attachment.key || data.attachment.fileId,
          });
          const loadedFileKey = data.attachment.fileKey || data.attachment.key || data.attachment.fileId;
          if (loadedFileKey) {
            setFileKey(loadedFileKey);
            setOriginalFileKey(loadedFileKey);
          }
        }
      } catch (error) {
        console.error('공지사항 조회 오류:', error);
        alert('공지사항을 불러오는 중 오류가 발생했습니다.');
        router.push('/admin/notices');
      } finally {
        setIsLoadingData(false);
      }
    }

    fetchNotice();
  }, [params?.id, router]);

  const handleBack = () => {
    router.push(`/admin/notices/${params.id}`);
  };

  const handleFileAttach = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = async (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 30 * 1024 * 1024) {
        alert('30MB 미만의 파일만 첨부할 수 있습니다.');
        return;
      }
      try {
        setIsLoading(true);
        // 단일 파일 업로드
        const uploadResponse = await apiService.uploadFile(file);
        
        // 응답에서 fileKey 추출
        let extractedFileKey: string | null = null;
        if (uploadResponse.data?.fileKey) {
          extractedFileKey = uploadResponse.data.fileKey;
        } else if (uploadResponse.data?.key) {
          extractedFileKey = uploadResponse.data.key;
        } else if (uploadResponse.data?.id) {
          extractedFileKey = uploadResponse.data.id;
        } else if (uploadResponse.data?.imageKey) {
          extractedFileKey = uploadResponse.data.imageKey;
        } else if (uploadResponse.data?.fileId) {
          extractedFileKey = uploadResponse.data.fileId;
        } else if (uploadResponse.data?.data && (uploadResponse.data.data.key || uploadResponse.data.data.fileKey)) {
          extractedFileKey = uploadResponse.data.data.key || uploadResponse.data.data.fileKey;
        } else if (uploadResponse.data?.results && Array.isArray(uploadResponse.data.results) && uploadResponse.data.results.length > 0) {
          const result = uploadResponse.data.results[0];
          if (result.ok && result.fileKey) {
            extractedFileKey = result.fileKey;
          }
        }
        
        if (extractedFileKey) {
          setFileKey(extractedFileKey);
          setAttachedFile(file);
          // 새 파일을 업로드하면 기존 파일 정보 제거
          setExistingAttachment(null);
        } else {
          throw new Error('파일 키를 받아오지 못했습니다.');
        }
      } catch (error) {
        console.error('파일 업로드 실패:', error);
        alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
        setAttachedFile(null);
        setFileKey(null);
      } finally {
        setIsLoading(false);
        // 파일 입력 초기화
        if (fileInputRef.current) {
          fileInputRef.current.value = '';
        }
      }
    }
  };

  const handleFileRemove = () => {
    setAttachedFile(null);
    setExistingAttachment(null);
    setFileKey(null);
    // 파일 입력 초기화
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleSave = async () => {
    if (!title.trim() || !content.trim()) {
      setIsValidationModalOpen(true);
      return;
    }
    
    if (!params?.id) {
      alert('공지사항 ID를 찾을 수 없습니다.');
      return;
    }

    try {
      setIsLoading(true);
      
      // 변경된 필드만 포함하는 request body 생성
      const noticeData: any = {};
      
      // 제목이 변경되었는지 확인
      const trimmedTitle = title.trim();
      if (trimmedTitle !== originalTitle) {
        noticeData.title = trimmedTitle;
      }
      
      // 내용이 변경되었는지 확인
      const trimmedContent = content.trim();
      if (trimmedContent !== originalContent) {
        noticeData.content = trimmedContent;
      }
      
      // 파일 변경사항 확인
      const currentFileKey = fileKey;
      const hasFileChanged = currentFileKey !== originalFileKey;
      
      // 파일이 삭제된 경우 (기존에 파일이 있었는데 지금 없음)
      if (originalFileKey && !currentFileKey) {
        noticeData.attachments = [];
      }
      // 파일이 변경되었거나 새로 추가된 경우
      else if (hasFileChanged && currentFileKey) {
        if (attachedFile) {
          // 새로 업로드한 파일
          noticeData.attachments = [
            {
              fileKey: currentFileKey,
              filename: attachedFile.name,
              mimeType: attachedFile.type || 'application/octet-stream',
              size: attachedFile.size,
            },
          ];
        } else if (existingAttachment && existingAttachment.fileKey) {
          // 기존 파일 유지
          noticeData.attachments = [
            {
              fileKey: existingAttachment.fileKey,
              filename: existingAttachment.name,
            },
          ];
        }
      }
      
      // 변경사항이 없으면 알림 후 리턴
      if (Object.keys(noticeData).length === 0) {
        setIsNoChangesModalOpen(true);
        setIsLoading(false);
        return;
      }
      
      await apiService.updateNotice(params.id, noticeData);
      
      // 성공 시 공지사항 리스트로 이동 (토스트는 리스트 페이지에서 표시)
      router.push('/admin/notices?updated=true');
    } catch (error) {
      console.error('공지사항 수정 실패:', error);
      alert('공지사항 수정에 실패했습니다. 다시 시도해주세요.');
    } finally {
      setIsLoading(false);
    }
  };

  const handleCancel = () => {
    if (title.trim() || content.trim() || attachedFile || fileKey) {
      setIsCancelModalOpen(true);
    } else {
      handleBack();
    }
  };

  const handleCancelConfirm = () => {
    setIsCancelModalOpen(false);
    handleBack();
  };

  if (isLoadingData) {
    return (
      <div className="min-h-screen flex flex-col bg-white">
        <div className="flex flex-1 min-h-0 justify-center">
          <div className="w-[1440px] flex min-h-0">
            <div className="flex">
              <AdminSidebar />
            </div>
            <main className="w-[1120px] bg-white">
              <div className="h-full flex flex-col">
                <div className="h-[100px] flex items-center justify-center px-[32px]">
                  <p className="text-[16px] font-medium text-[#333c47]">로딩 중...</p>
                </div>
              </div>
            </main>
          </div>
        </div>
      </div>
    );
  }

  return (
    <>
      <NoticeValidationModal
        open={isValidationModalOpen}
        onClose={() => setIsValidationModalOpen(false)}
      />
      <NoticeCancelModal
        open={isCancelModalOpen}
        onClose={() => setIsCancelModalOpen(false)}
        onConfirm={handleCancelConfirm}
      />
      <NoChangesModal
        open={isNoChangesModalOpen}
        onClose={() => setIsNoChangesModalOpen(false)}
      />
      <div className="min-h-screen flex flex-col bg-white">
        {/* 메인 레이아웃 */}
        <div className="flex flex-1 min-h-0 justify-center">
          <div className="w-[1440px] flex min-h-0">
            {/* 사이드바 */}
            <div className="flex">
              <AdminSidebar />
            </div>

            {/* 메인 콘텐츠 */}
            <main className="w-[1120px] bg-white">
              <div className="h-full flex flex-col px-8">
                {/* 작성 모드 헤더 */}
                <div className="h-[100px] flex items-center">
                  <div className="flex gap-3 items-center">
                    <button
                      type="button"
                      onClick={handleBack}
                      className="flex items-center justify-center w-8 h-8 cursor-pointer"
                      aria-label="뒤로가기"
                    >
                      <BackArrowSvg width={32} height={32} />
                    </button>
                    <h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">
                      공지사항 수정
                    </h1>
                  </div>
                </div>

                {/* 작성 폼 */}
                <div className="flex-1 flex flex-col gap-10 pb-20 pt-8 w-full">
                  <div className="flex flex-col gap-6 w-full">
                    {/* 제목 입력 */}
                    <div className="flex flex-col gap-2 items-start justify-center w-full">
                      <label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682] w-[100px]">
                        제목
                      </label>
                      <input
                        type="text"
                        value={title}
                        onChange={(e) => setTitle(e.target.value)}
                        placeholder="제목을 입력해 주세요."
                        className="w-full h-[40px] px-3 py-2 rounded-[8px] border border-[#dee1e6] bg-white text-[16px] font-normal leading-[1.5] text-[#1b2027] placeholder:text-[#b1b8c0] focus:outline-none focus:ring-2 focus:ring-[#1f2b91] focus:border-transparent"
                      />
                    </div>

                    {/* 내용 입력 */}
                    <div className="flex flex-col gap-2 items-start justify-center w-full">
                      <label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682] w-[100px]">
                        내용
                      </label>
                      <div className="relative w-full">
                        <textarea
                          value={content}
                          onChange={(e) => {
                            const newContent = e.target.value;
                            if (newContent.length <= 1000) {
                              setContent(newContent);
                            }
                          }}
                          placeholder="내용을 입력해 주세요. (최대 1,000자 이내)"
                          className="w-full h-[320px] px-3 py-2 rounded-[8px] border border-[#dee1e6] bg-white text-[16px] font-normal leading-[1.5] text-[#1b2027] placeholder:text-[#b1b8c0] resize-none focus:outline-none focus:ring-2 focus:ring-[#1f2b91] focus:border-transparent"
                        />
                        <div className="absolute bottom-3 right-3">
                          <p className="text-[13px] font-normal leading-[1.4] text-[#6c7682] text-right">
                            {characterCount}/1000
                          </p>
                        </div>
                      </div>
                    </div>

                    {/* 첨부 파일 */}
                    <div className="flex flex-col gap-2 items-start justify-center w-full">
                      <div className="flex items-center justify-between h-8 w-full">
                        <div className="flex items-center gap-3 flex-1 min-w-0">
                          <label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682] whitespace-nowrap">
                            첨부 파일{' '}
                            <span className="font-normal">
                              {(attachedFile || existingAttachment) ? 1 : 0}/1
                            </span>
                          </label>
                          <p className="text-[13px] font-normal leading-[1.4] text-[#8c95a1] whitespace-nowrap">
                            30MB 미만 파일
                          </p>
                        </div>
                        <button
                          type="button"
                          onClick={handleFileAttach}
                          disabled={isLoading}
                          className="h-[32px] w-[62px] px-[4px] py-[3px] rounded-[6px] border border-[#8c95a1] bg-white flex items-center justify-center cursor-pointer hover:bg-gray-50 transition-colors shrink-0 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          <span className="text-[13px] font-medium leading-[1.4] text-[#4c5561] whitespace-nowrap">
                            {isLoading ? '업로드 중...' : '첨부'}
                          </span>
                        </button>
                        <input
                          ref={fileInputRef}
                          type="file"
                          onChange={handleFileChange}
                          className="hidden"
                          accept="*/*"
                        />
                      </div>
                      <div className="h-16 w-full rounded-[8px] border border-[#dee1e6] bg-gray-50 flex items-center justify-between px-4">
                        {attachedFile ? (
                          <>
                            <p className="text-[14px] font-normal leading-[1.5] text-[#1b2027] flex-1 min-w-0 truncate">
                              {attachedFile.name}
                            </p>
                            <button
                              type="button"
                              onClick={handleFileRemove}
                              className="flex items-center justify-center w-6 h-6 cursor-pointer hover:opacity-70 transition-opacity shrink-0 ml-2"
                              aria-label="파일 삭제"
                            >
                              <CloseXOSvg />
                            </button>
                          </>
                        ) : existingAttachment ? (
                          <>
                            <p className="text-[14px] font-normal leading-[1.5] text-[#1b2027] flex-1 min-w-0 truncate">
                              {existingAttachment.name}
                            </p>
                            <button
                              type="button"
                              onClick={handleFileRemove}
                              className="flex items-center justify-center w-6 h-6 cursor-pointer hover:opacity-70 transition-opacity shrink-0 ml-2"
                              aria-label="파일 삭제"
                            >
                              <CloseXOSvg />
                            </button>
                          </>
                        ) : (
                          <p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] text-center w-full">
                            파일을 첨부해주세요.
                          </p>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* 액션 버튼 */}
                  <div className="flex gap-3 items-center justify-end shrink-0 w-full">
                    <button
                      type="button"
                      onClick={handleCancel}
                      className="h-12 px-8 rounded-[10px] bg-[#f1f3f5] text-[16px] font-semibold leading-[1.5] text-[#4c5561] whitespace-nowrap hover:bg-[#e5e8eb] transition-colors cursor-pointer"
                    >
                      취소
                    </button>
                    <button
                      type="button"
                      onClick={handleSave}
                      disabled={isLoading}
                      className="h-12 px-4 rounded-[10px] bg-[#1f2b91] text-[16px] font-semibold leading-[1.5] text-white whitespace-nowrap hover:bg-[#1a2478] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {isLoading ? '저장 중...' : '저장하기'}
                    </button>
                  </div>
                </div>
              </div>
            </main>
          </div>
        </div>
      </div>
    </>
  );
}

