'use client'
import { Crepe } from "@milkdown/crepe";
import { MilkdownProvider } from "@milkdown/react";
import { useCallback, useState,useRef } from "react";
import { MilkdownEditor } from "@/app/components/editor";

export default function Page() {
  const titleRef = useRef<HTMLInputElement>(null!);
  const tagRef = useRef<HTMLSelectElement>(null!);

  const crepeRef = useRef<Crepe>(null!);

  const [isLoading, setIsLoading] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  const handlePost = async () => {
    setIsLoading(true);
    try {
      const response = await fetch('/api/notice', {
        method: 'POST',
        body: JSON.stringify({
          title: titleRef.current?.value,
          content: crepeRef.current?.getMarkdown(),
          tag: tagRef.current?.value,
        }),
      });

      if (response.ok) {
        setToastMessage('Post successful!');
        setTimeout(() => {
          setToastMessage('');
          window.location.href = '/usr/4_noticeboard'; // Redirect after success
        }, 1000); // 3 seconds delay
      } else {
        setToastMessage('Failed to post.');
      }
    } catch (error) {
      setToastMessage('An error occurred.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className=" bg-white h-full min-h-[760px]">
      <div className="h-full grid grid-rows-[20px_74px_minmax(300px,auto)_240px] grid-cols-[minmax(500px,880px)] justify-center py-8 gap-5
      2xl:grid-cols-[minmax(500px,880px)_auto] 2xl:grid-rows-[20px_74px_minmax(300px,1fr)_auto]
      ">
        <div className="ml-1 text-xl leading-8 font-extrabold 2xl:col-[1/3] 2xl:row-[1/2]">게시글작성</div>
        <div className="flex flex-col justify-between  2xl:col-[1/2] 2xl:row-[2/3]">
          <div className="h-[14px] text-sm leading-4 text-[#3f2929] ml-1">
            제목
          </div>
          <input 
            type="text" 
            className="h-[48px] border-1 border-[#d5d5d5] rounded-lg px-2 mx-1" 
            placeholder="제목을 입력하세요" 
            ref={titleRef}
          />
        </div>
        <div className="flex flex-col justify-between 2xl:col-[1/2] 2xl:row-[3/4]">
          <div className="h-[14px] text-sm leading-4 text-[#3f2929] ml-1"> 내용 </div>
          <div className="h-[13px]"></div>

        <div className="grow-1 border-1 border-[#d5d5d5] rounded-lg px-2 mx-1 overflow-y-auto">
          <MilkdownProvider>
            <MilkdownEditor editorRef={crepeRef} />
          </MilkdownProvider>
        </div>
        </div>
        <div className="flex flex-col justify-center 2xl:col-[2/3] 2xl:row-[2/4] 2xl:justify-start">
          <div className="flex flex-col ">
            <div className="h-[14px] text-sm  leading-4 text-[#3f2929] ml-1">
              작업 태그 설정
            </div>
            <div className="h-[13px]"></div>
            <select
              className="h-[48px] mx-1 border-1 border-[#d5d5d5] rounded-lg px-2" 
              ref={tagRef}
            >
              <option value="중요">중요</option>
              <option value="0">없음</option>
            </select>
          </div>
          <div className="h-[48px]"></div>

          <div className="flex flex-col justify-between h-[116px] items-center">
            <button onClick={handlePost} disabled={isLoading} className="w-[324px] h-[48px] border-1 border-[#D73B29] rounded-lg flex items-center justify-center text-white bg-[#F94B37] font-extrabold text-xl cursor-pointer hover:bg-[#D73B29]">
              {isLoading ? 'Posting...' : '게시'}
            </button>
            <div 
              className="w-[324px] h-[48px] border-1 border-[#D5D5D5] rounded-lg flex items-center justify-center font-medium text-xl cursor-pointer hover:bg-[#E5E5E5]" 
              onClick={() => window.location.href = '/usr/4_noticeboard'}
            >
              취소
            </div>
          </div>
          {toastMessage && (
            <div className="fixed bottom-4 right-4 bg-gray-800 text-white p-4 rounded shadow-lg">
              {toastMessage}
            </div>
          )}

        </div>
      </div>
      
    </div>
  )
}



