'use client';

import { useState, useMemo, useRef, ChangeEvent } from "react";
import AdminSidebar from "@/app/components/AdminSidebar";
import ChevronDownSvg from "@/app/svgs/chevrondownsvg";
import BackArrowSvg from "@/app/svgs/backarrow";
import { MOCK_NOTICES, type Notice } from "@/app/admin/notices/mockData";

export default function AdminNoticesPage() {
  const [notices, setNotices] = useState<Notice[]>(MOCK_NOTICES);
  const [currentPage, setCurrentPage] = useState(1);
  const [isWritingMode, setIsWritingMode] = useState(false);
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [attachedFile, setAttachedFile] = useState<File | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const totalCount = useMemo(() => notices.length, [notices]);
  
  const characterCount = useMemo(() => content.length, [content]);
  
  const handleBack = () => {
    setIsWritingMode(false);
    setTitle('');
    setContent('');
    setAttachedFile(null);
  };
  
  const handleFileAttach = () => {
    fileInputRef.current?.click();
  };
  
  const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 30 * 1024 * 1024) {
        alert('30MB 미만의 파일만 첨부할 수 있습니다.');
        return;
      }
      setAttachedFile(file);
    }
  };
  
  const handleSave = () => {
    if (!title.trim()) {
      alert('제목을 입력해주세요.');
      return;
    }
    if (!content.trim()) {
      alert('내용을 입력해주세요.');
      return;
    }
    
    // 새 공지사항 추가
    const newNotice: Notice = {
      id: notices.length > 0 ? Math.max(...notices.map(n => n.id)) + 1 : 1,
      title: title.trim(),
      date: new Date().toISOString().split('T')[0],
      views: 0,
      writer: '관리자', // TODO: 실제 작성자 정보 사용
      content: content.split('\n'),
      hasAttachment: attachedFile !== null,
    };
    
    setNotices([newNotice, ...notices]);
    handleBack();
  };
  
  const handleCancel = () => {
    if (title.trim() || content.trim() || attachedFile) {
      if (confirm('작성 중인 내용이 있습니다. 정말 취소하시겠습니까?')) {
        handleBack();
      }
    } else {
      handleBack();
    }
  };
  
  const ITEMS_PER_PAGE = 10;
  const sortedNotices = useMemo(() => {
    return [...notices].sort((a, b) => {
      // 생성일 내림차순 정렬 (최신 날짜가 먼저)
      return b.date.localeCompare(a.date);
    });
  }, [notices]);
  
  const totalPages = Math.ceil(sortedNotices.length / ITEMS_PER_PAGE);
  const paginatedNotices = useMemo(() => {
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    const endIndex = startIndex + ITEMS_PER_PAGE;
    return sortedNotices.slice(startIndex, endIndex);
  }, [sortedNotices, currentPage]);

  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 px-8">
              {isWritingMode ? (
                <>
                  {/* 작성 모드 헤더 */}
                  <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 ? 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}
                            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"
                          >
                            <span className="text-[13px] font-medium leading-[1.4] text-[#4c5561] whitespace-nowrap">
                              첨부
                            </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-center">
                          {attachedFile ? (
                            <p className="text-[14px] font-normal leading-[1.5] text-[#1b2027]">
                              {attachedFile.name}
                            </p>
                          ) : (
                            <p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] text-center">
                              파일을 첨부해주세요.
                            </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}
                        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"
                      >
                        저장하기
                      </button>
                    </div>
                  </div>
                </>
              ) : (
                <>
                  {/* 제목 영역 */}
                  <div className="h-[100px] flex items-center">
                    <h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">
                      공지사항
                    </h1>
                  </div>

                  {/* 헤더 영역 (제목과 콘텐츠 사이) */}
                  <div className="pt-2 pb-4 flex items-center justify-between">
                    <p className="text-[15px] font-medium leading-[1.5] text-[#333c47] whitespace-nowrap">
                      총 {totalCount}건
                    </p>
                    <button
                      type="button"
                      onClick={() => setIsWritingMode(true)}
                      className="h-[40px] px-4 rounded-[8px] bg-[#1f2b91] text-[16px] font-semibold leading-[1.5] text-white whitespace-nowrap hover:bg-[#1a2478] transition-colors cursor-pointer"
                    >
                      작성하기
                    </button>
                  </div>

                  {/* 콘텐츠 영역 */}
                  <div className="flex-1 pt-2 flex flex-col">
                {notices.length === 0 ? (
                  <div className="rounded-lg border border-[#dee1e6] bg-white min-h-[400px] flex items-center justify-center">
                    <p className="text-[16px] font-medium leading-[1.5] text-[#333c47]">
                      등록된 공지사항이 없습니다.
                      <br />
                      공지사항을 등록해주세요.
                    </p>
                  </div>
                ) : (
                  <>
                    <div className="rounded-[8px]">
                      <div className="w-full rounded-[8px] border border-[#dee1e6] overflow-visible">
                        <table className="min-w-full border-collapse">
                          <colgroup>
                            <col style={{ width: 80 }} />
                            <col />
                            <col style={{ width: 140 }} />
                            <col style={{ width: 120 }} />
                            <col style={{ width: 120 }} />
                          </colgroup>
                          <thead>
                            <tr className="h-12 bg-gray-50 text-left">
                              <th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">번호</th>
                              <th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">제목</th>
                              <th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">게시일</th>
                              <th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">조회수</th>
                              <th className="px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">작성자</th>
                            </tr>
                          </thead>
                          <tbody>
                            {paginatedNotices.map((notice, index) => {
                              // 번호는 전체 목록에서의 순서 (정렬된 목록 기준)
                              const noticeNumber = sortedNotices.length - (currentPage - 1) * ITEMS_PER_PAGE - index;
                              return (
                                <tr
                                  key={notice.id}
                                  className="h-12 hover:bg-[#F5F7FF] transition-colors"
                                >
                                  <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap text-center">
                                    {noticeNumber}
                                  </td>
                                  <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027]">
                                    {notice.title}
                                  </td>
                                  <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
                                    {notice.date}
                                  </td>
                                  <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
                                    {notice.views.toLocaleString()}
                                  </td>
                                  <td className="border-t border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
                                    {notice.writer}
                                  </td>
                                </tr>
                              );
                            })}
                          </tbody>
                        </table>
                      </div>
                    </div>
                    
                    {/* 페이지네이션 - 10개 초과일 때만 표시 */}
                    {notices.length > ITEMS_PER_PAGE && (() => {
                      // 페이지 번호를 10단위로 표시
                      const pageGroup = Math.floor((currentPage - 1) / 10);
                      const startPage = pageGroup * 10 + 1;
                      const endPage = Math.min(startPage + 9, totalPages);
                      const visiblePages = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i);

                      return (
                        <div className="pt-8 pb-[32px] flex items-center justify-center">
                          <div className="flex items-center justify-center gap-[8px]">
                            {/* First (맨 앞으로) */}
                            <button
                              type="button"
                              onClick={() => setCurrentPage(1)}
                              aria-label="맨 앞 페이지"
                              className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-[#333c47] disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
                              disabled={currentPage === 1}
                            >
                              <div className="relative flex items-center justify-center w-full h-full">
                                <ChevronDownSvg width={14.8} height={14.8} className="rotate-90 absolute left-[2px]" />
                                <ChevronDownSvg width={14.8} height={14.8} className="rotate-90 absolute right-[2px]" />
                              </div>
                            </button>

                            {/* Prev */}
                            <button
                              type="button"
                              onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                              aria-label="이전 페이지"
                              className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-[#333c47] disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
                              disabled={currentPage === 1}
                            >
                              <ChevronDownSvg width={14.8} height={14.8} className="rotate-90" />
                            </button>

                            {/* Numbers */}
                            {visiblePages.map((n) => {
                              const active = n === currentPage;
                              return (
                                <button
                                  key={n}
                                  type="button"
                                  onClick={() => setCurrentPage(n)}
                                  aria-current={active ? 'page' : undefined}
                                  className={[
                                    'flex items-center justify-center rounded-[1000px] size-[32px] cursor-pointer',
                                    active ? 'bg-[#ecf0ff]' : 'bg-white',
                                  ].join(' ')}
                                >
                                  <span className="text-[16px] leading-[1.4] text-[#333c47]">{n}</span>
                                </button>
                              );
                            })}

                            {/* Next */}
                            <button
                              type="button"
                              onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                              aria-label="다음 페이지"
                              className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-[#333c47] disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
                              disabled={currentPage === totalPages}
                            >
                              <ChevronDownSvg width={14.8} height={14.8} className="-rotate-90" />
                            </button>

                            {/* Last (맨 뒤로) */}
                            <button
                              type="button"
                              onClick={() => setCurrentPage(totalPages)}
                              aria-label="맨 뒤 페이지"
                              className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-[#333c47] disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
                              disabled={currentPage === totalPages}
                            >
                              <div className="relative flex items-center justify-center w-full h-full">
                                <ChevronDownSvg width={14.8} height={14.8} className="-rotate-90 absolute left-[2px]" />
                                <ChevronDownSvg width={14.8} height={14.8} className="-rotate-90 absolute right-[2px]" />
                              </div>
                            </button>
                          </div>
                        </div>
                      );
                    })()}
                  </>
                )}
                  </div>
                </>
              )}
            </div>
          </main>
        </div>
      </div>
    </div>
  );
}

