'use client';

import { useState, useMemo, useRef, ChangeEvent, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import AdminSidebar from "@/app/components/AdminSidebar";
import ChevronDownSvg from "@/app/svgs/chevrondownsvg";
import BackArrowSvg from "@/app/svgs/backarrow";
import { type Resource } from "@/app/admin/resources/mockData";
import apiService from "@/app/lib/apiService";

export default function AdminResourcesPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [resources, setResources] = useState<Resource[]>([]);
  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 [fileKey, setFileKey] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  // 날짜를 yyyy-mm-dd 형식으로 포맷팅
  const formatDate = (dateString: string): string => {
    if (!dateString) return '';
    
    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        // 이미 yyyy-mm-dd 형식인 경우 그대로 반환
        if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
          return dateString;
        }
        return dateString;
      }
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    } catch {
      return dateString;
    }
  };
  
  // API에서 학습 자료 목록 가져오기
  useEffect(() => {
    async function fetchResources() {
      try {
        setIsLoading(true);
        const response = await apiService.getLibrary();
        const data = response.data;
        
        // API 응답이 배열이 아닌 경우 처리 (예: { items: [...] } 형태)
        let resourcesArray: any[] = [];
        if (Array.isArray(data)) {
          resourcesArray = data;
        } else if (data && typeof data === 'object') {
          resourcesArray = data.items || data.resources || data.data || data.list || [];
        }
        
        // API 응답 데이터를 Resource 형식으로 변환
        const transformedResources: Resource[] = resourcesArray.map((resource: any) => ({
          id: resource.id || resource.resourceId || 0,
          title: resource.title || '',
          date: resource.date || resource.createdAt || resource.createdDate || new Date().toISOString().split('T')[0],
          views: resource.views || resource.viewCount || 0,
          writer: resource.writer || resource.author || resource.createdBy || '관리자',
          content: resource.content ? (Array.isArray(resource.content) ? resource.content : [resource.content]) : undefined,
          hasAttachment: resource.hasAttachment || resource.attachment || false,
        }));
        
        setResources(transformedResources);
      } catch (error) {
        console.error('학습 자료 목록 조회 오류:', error);
        // 에러 발생 시 빈 배열로 설정
        setResources([]);
      } finally {
        setIsLoading(false);
      }
    }
    
    fetchResources();
  }, []);

  // 수정 완료 쿼리 파라미터 확인 및 토스트 표시
  useEffect(() => {
    if (searchParams.get('updated') === 'true') {
      setShowToast(true);
      // URL에서 쿼리 파라미터 제거
      router.replace('/admin/resources');
      // 토스트 자동 닫기
      const timer = setTimeout(() => {
        setShowToast(false);
      }, 3000);
      return () => clearTimeout(timer);
    }
  }, [searchParams, router]);
  
  const totalCount = useMemo(() => resources.length, [resources]);
  
  const characterCount = useMemo(() => content.length, [content]);
  
  const handleBack = () => {
    setIsWritingMode(false);
    setTitle('');
    setContent('');
    setAttachedFile(null);
    setFileKey(null);
    // 파일 입력 초기화
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };
  
  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);
        } else {
          throw new Error('파일 키를 받아오지 못했습니다.');
        }
      } catch (error) {
        console.error('파일 업로드 실패:', error);
        alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
        setAttachedFile(null);
        setFileKey(null);
      } finally {
        setIsLoading(false);
        // 파일 입력 초기화
        if (fileInputRef.current) {
          fileInputRef.current.value = '';
        }
      }
    }
  };
  
  const handleSave = async () => {
    if (!title.trim() || !content.trim()) {
      alert('제목과 내용을 입력해주세요.');
      return;
    }
    
    try {
      setIsLoading(true);
      
      // 학습 자료 생성 API 호출
      const resourceData: any = {
        title: title.trim(),
        content: content.trim(),
      };
      
      // fileKey와 파일 정보가 있으면 attachments 배열로 포함
      if (fileKey && attachedFile) {
        resourceData.attachments = [
          {
            fileKey: fileKey,
            filename: attachedFile.name,
            mimeType: attachedFile.type || 'application/octet-stream',
            size: attachedFile.size,
          },
        ];
      }
      
      const response = await apiService.createLibraryItem(resourceData);
      
      // API 응답 후 목록 새로고침
      const fetchResponse = await apiService.getLibrary();
      const data = fetchResponse.data;
      
      // API 응답이 배열이 아닌 경우 처리
      let resourcesArray: any[] = [];
      if (Array.isArray(data)) {
        resourcesArray = data;
      } else if (data && typeof data === 'object') {
        resourcesArray = data.items || data.resources || data.data || data.list || [];
      }
      
      // API 응답 데이터를 Resource 형식으로 변환
      const transformedResources: Resource[] = resourcesArray.map((resource: any) => ({
        id: resource.id || resource.resourceId || 0,
        title: resource.title || '',
        date: resource.date || resource.createdAt || resource.createdDate || new Date().toISOString().split('T')[0],
        views: resource.views || resource.viewCount || 0,
        writer: resource.writer || resource.author || resource.createdBy || '관리자',
        content: resource.content ? (Array.isArray(resource.content) ? resource.content : [resource.content]) : undefined,
        hasAttachment: resource.hasAttachment || resource.attachment || !!resource.fileKey || false,
      }));
      
      setResources(transformedResources);
      handleBack();
    } catch (error) {
      console.error('학습 자료 저장 실패:', error);
      alert('학습 자료 저장에 실패했습니다. 다시 시도해주세요.');
    } finally {
      setIsLoading(false);
    }
  };
  
  const handleCancel = () => {
    if (title.trim() || content.trim() || attachedFile || fileKey) {
      if (confirm('작성 중인 내용이 있습니다. 정말 취소하시겠습니까?')) {
        handleBack();
      }
    } else {
      handleBack();
    }
  };
  
  const ITEMS_PER_PAGE = 10;
  const sortedResources = useMemo(() => {
    return [...resources].sort((a, b) => {
      // 생성일 내림차순 정렬 (최신 날짜가 먼저)
      return b.date.localeCompare(a.date);
    });
  }, [resources]);
  
  const totalPages = Math.ceil(sortedResources.length / ITEMS_PER_PAGE);
  const paginatedResources = useMemo(() => {
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    const endIndex = startIndex + ITEMS_PER_PAGE;
    return sortedResources.slice(startIndex, endIndex);
  }, [sortedResources, 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}
                            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 px-4">
                          {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 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 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">
                {resources.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] text-center">
                      등록된 학습 자료가 없습니다.
                      <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>
                            {paginatedResources.map((resource, index) => {
                              // 번호는 전체 목록에서의 순서 (정렬된 목록 기준)
                              const resourceNumber = sortedResources.length - (currentPage - 1) * ITEMS_PER_PAGE - index;
                              return (
                                <tr
                                  key={resource.id}
                                  onClick={() => router.push(`/admin/resources/${resource.id}`)}
                                  className="h-12 hover:bg-[#F5F7FF] transition-colors cursor-pointer"
                                >
                                  <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap text-center">
                                    {resourceNumber}
                                  </td>
                                  <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027]">
                                    {resource.title}
                                  </td>
                                  <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
                                    {formatDate(resource.date)}
                                  </td>
                                  <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
                                    {resource.views.toLocaleString()}
                                  </td>
                                  <td className="border-t border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
                                    {resource.writer}
                                  </td>
                                </tr>
                              );
                            })}
                          </tbody>
                        </table>
                      </div>
                    </div>
                    
                    {/* 페이지네이션 - 10개 초과일 때만 표시 */}
                    {resources.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>

      {/* 수정 완료 토스트 */}
      {showToast && (
        <div className="fixed right-[60px] bottom-[60px] z-50">
          <div className="bg-white border border-[#dee1e6] rounded-[8px] p-4 min-w-[360px] flex gap-[10px] items-center">
            <div className="relative shrink-0 w-[16.667px] h-[16.667px]">
              <svg width="17" height="17" viewBox="0 0 17 17" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="8.5" cy="8.5" r="8.5" fill="#384FBF"/>
                <path d="M5.5 8.5L7.5 10.5L11.5 6.5" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <p className="text-[15px] font-medium leading-[1.5] text-[#1b2027] text-nowrap">
              수정이 완료되었습니다.
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

