import { useState, useEffect, useCallback } from 'react';
import {
  FileText,
  Search,
  RefreshCw,
  Plus,
  Edit,
  Trash2,
  Share2,
  Lock,
  XCircle,
} from 'lucide-react';
import { comms } from '@/communication';
import { NoteItem } from '@/types';
import { NoteEditModal } from '@/components/note/NoteEditModal';
import { NoteViewModal } from '@/components/note/NoteViewModal';
import { clsx } from 'clsx';

export function Note() {
  const [noteList, setNoteList] = useState<NoteItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [processing, setProcessing] = useState(false);
  const [searchKey, setSearchKey] = useState('');
  // 모달 상태
  const [showModal, setShowModal] = useState(false);
  const [showViewModal, setShowViewModal] = useState(false);
  const [editingItem, setEditingItem] = useState<NoteItem | null>(null);
  const [selectedNote, setSelectedNote] = useState<NoteItem | null>(null);

  // 페이징 상태
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 100;

  // 날짜 포맷 헬퍼 함수 (로컬 시간 기준)
  const formatDateLocal = (date: Date) => {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  };

  // 데이터 로드
  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const startOfPeriod = '2000-01-01';
      const today = formatDateLocal(new Date());

      console.log('메모장 전수 조회 요청');
      const response = await comms.getNoteList(startOfPeriod, today, '');
      console.log('메모장 조회 응답:', response);
      if (response.Success && response.Data) {
        setNoteList(response.Data);
      } else {
        setNoteList([]);
      }
    } catch (error) {
      console.error('메모장 목록 로드 오류:', error);
      alert('데이터를 불러오는 중 오류가 발생했습니다.');
    } finally {
      setLoading(false);
    }
  }, []);

  // 초기화 완료 후 조회 실행 (최초 1회만)
  useEffect(() => {
    loadData();
  }, [loadData]);

  // 새 메모 추가 모달
  const openAddModal = () => {
    setEditingItem(null);
    setShowModal(true);
  };

  // 메모 클릭 (보기 모달)
  const handleNoteClick = async (item: NoteItem) => {
    try {
      const response = await comms.getNoteDetail(item.idx);
      if (response.Success && response.Data) {
        setSelectedNote(response.Data);
        setShowViewModal(true);
      }
    } catch (error) {
      console.error('메모 조회 오류:', error);
      alert('데이터를 불러오는 중 오류가 발생했습니다.');
    }
  };

  // 편집 모달
  const openEditModal = async (item: NoteItem) => {
    try {
      const response = await comms.getNoteDetail(item.idx);
      if (response.Success && response.Data) {
        setEditingItem(response.Data);
        setShowModal(true);
      }
    } catch (error) {
      console.error('메모 조회 오류:', error);
      alert('데이터를 불러오는 중 오류가 발생했습니다.');
    }
  };

  // 저장
  const handleSave = async (formData: {
    pdate: string;
    title: string;
    uid: string;
    description: string;
    share: boolean;
    guid: string;
  }) => {
    if (!formData.pdate) {
      alert('날짜를 입력해주세요.');
      return;
    }
    if (!formData.title.trim()) {
      alert('제목을 입력해주세요.');
      return;
    }

    setProcessing(true);
    try {
      let response;
      if (editingItem) {
        response = await comms.editNote(
          editingItem.idx,
          formData.pdate,
          formData.title,
          formData.uid,
          formData.description,
          '',
          formData.share,
          formData.guid
        );
      } else {
        response = await comms.addNote(
          formData.pdate,
          formData.title,
          formData.uid,
          formData.description,
          '',
          formData.share,
          formData.guid
        );
      }

      if (response.Success) {
        setShowModal(false);
        loadData();
      } else {
        alert(response.Message || '저장에 실패했습니다.');
      }
    } catch (error) {
      console.error('저장 오류:', error);
      alert('서버 연결에 실패했습니다: ' + (error instanceof Error ? error.message : String(error)));
    } finally {
      setProcessing(false);
    }
  };

  // 삭제
  const handleDelete = async (idx: number) => {
    if (!confirm('정말로 이 메모를 삭제하시겠습니까?')) return;

    setProcessing(true);
    try {
      const response = await comms.deleteNote(idx);
      if (response.Success) {
        alert('삭제되었습니다.');
        loadData();
      } else {
        alert(response.Message || '삭제에 실패했습니다.');
      }
    } catch (error) {
      console.error('삭제 오류:', error);
      alert('서버 연결에 실패했습니다.');
    } finally {
      setProcessing(false);
    }
  };

  // 날짜 포맷 (YY.MM.DD)
  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return '-';
    try {
      const date = new Date(dateStr);
      const yy = String(date.getFullYear()).slice(-2);
      const mm = String(date.getMonth() + 1).padStart(2, '0');
      const dd = String(date.getDate()).padStart(2, '0');
      return `${yy}.${mm}.${dd}`;
    } catch {
      return dateStr;
    }
  };


  // 필터링된 목록 (검색어 적용)
  const filteredList = noteList.filter(item => {
    if (!searchKey.trim()) return true;
    const search = searchKey.toLowerCase();
    return (
      item.title?.toLowerCase().includes(search) ||
      item.description?.toLowerCase().includes(search) ||
      item.uid?.toLowerCase().includes(search)
    );
  });

  // 페이징 계산
  const totalPages = Math.ceil(filteredList.length / pageSize);
  const paginatedList = filteredList.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );


  return (
    <div className="space-y-6 animate-fade-in pb-4">



      {/* 메모 리스트 */}
      <div className="glass-effect rounded-3xl overflow-hidden shadow-2xl border border-white/10">
        <div className="px-6 py-4 border-b border-white/10 flex flex-col md:flex-row items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-primary-500/20 rounded-lg">
              <FileText className="w-5 h-5 text-primary-400" />
            </div>
            <h3 className="text-lg font-bold text-white tracking-tight">메모장 목록</h3>
          </div>

          <div className="flex items-center gap-3">
            {/* 검색창 */}
            <div className="relative group w-48 md:w-64">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-white/40 group-focus-within:text-primary-400 transition-colors" />
              <input
                type="text"
                value={searchKey}
                onChange={(e) => {
                  setSearchKey(e.target.value);
                  setCurrentPage(1); // 검색 시 1페이지로 이동
                }}
                placeholder="검색..."
                className="w-full bg-white/5 border border-white/10 rounded-xl pl-9 pr-8 py-1.5 text-xs text-white placeholder-white/20 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all backdrop-blur-sm"
              />
              {searchKey && (
                <button
                  onClick={() => setSearchKey('')}
                  className="absolute right-2.5 top-1/2 -translate-y-1/2 text-white/20 hover:text-white transition-colors"
                >
                  <XCircle className="w-3.5 h-3.5" />
                </button>
              )}
            </div>

            {/* 개수 */}
            <div className="flex items-center gap-2 bg-white/5 px-3 py-1.5 rounded-xl border border-white/10 h-[38px]">
              <span className="text-primary-400 font-bold text-sm">{filteredList.length}</span>
              <span className="text-white/40 text-[10px] uppercase">건</span>
            </div>

            {/* 새로고침 */}
            <button
              onClick={loadData}
              disabled={loading}
              className="p-2 bg-white/5 hover:bg-white/10 border border-white/10 rounded-xl text-white/70 hover:text-white transition-all disabled:opacity-50"
              title="새로고침"
            >
              <RefreshCw className={clsx("w-4 h-4", loading && "animate-spin")} />
            </button>

            {/* 새 메모 작성 */}
            <button
              onClick={openAddModal}
              className="p-2 bg-success-500 hover:bg-success-600 border border-white/20 rounded-xl text-white transition-all shadow-lg shadow-success-500/20 active:scale-95"
              title="새 메모 작성"
            >
              <Plus className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* 컬럼 헤더 (업무일지 디자인 통일) */}
        <div className="bg-white/10 px-6 py-3 border-b border-white/5 flex items-center gap-4">
          <div className="w-8 text-center text-xs font-medium text-white/70 uppercase">상태</div>
          <div className="flex-1 text-xs font-medium text-white/70 uppercase">제목</div>
          <div className="flex items-center gap-6 shrink-0">
            <div className="flex items-center gap-4">
              <div className="w-20 text-right text-xs font-medium text-white/70 uppercase">작성자</div>
              <div className="w-24 text-center text-xs font-medium text-white/70 uppercase">작성일</div>
              <div className="w-16 text-right text-xs font-medium text-white/70 uppercase">조회수</div>
            </div>
            <div className="w-[88px]"></div> {/* 액션 버튼 공간 */}
          </div>
        </div>

        <div className="divide-y divide-white/5 max-h-[calc(100vh-280px)] overflow-y-auto custom-scrollbar">
          {loading ? (
            <div className="px-6 py-12 text-center">
              <RefreshCw className="w-10 h-10 mx-auto mb-4 animate-spin text-primary-500/50" />
              <p className="text-white/50 font-medium text-sm">데이터를 실시간으로 동기화 중...</p>
            </div>
          ) : filteredList.length === 0 ? (
            <div className="px-6 py-20 text-center">
              <div className="relative inline-block mb-4">
                <FileText className="w-16 h-16 mx-auto text-white/10" />
                <div className="absolute inset-0 flex items-center justify-center">
                  <Search className="w-6 h-6 text-primary-500/20" />
                </div>
              </div>
              <p className="text-white/30 text-base">조회된 메모가 없습니다</p>
              <button
                onClick={openAddModal}
                className="mt-4 text-primary-400 hover:text-primary-300 text-sm font-medium underline underline-offset-4"
              >
                첫 번째 메모를 작성해보세요
              </button>
            </div>
          ) : (
            paginatedList.map((item) => (
              <div
                key={item.idx}
                className="px-6 py-2.5 hover:bg-white/[0.03] transition-all cursor-pointer group relative"
                onClick={() => handleNoteClick(item)}
              >
                <div className="flex items-center gap-4">
                  {/* 공유/잠금 아이콘 - 컬럼 너비 8에 맞춤 */}
                  <div className={clsx(
                    "w-8 h-8 rounded-lg flex items-center justify-center shrink-0 transition-all group-hover:scale-110",
                    item.share ? "bg-success-500/20 text-success-400 shadow-[0_0_10px_rgba(34,197,94,0.1)]" : "bg-blue-500/20 text-blue-400 shadow-[0_0_10px_rgba(59,130,246,0.1)]"
                  )}>
                    {item.share ? (
                      <Share2 className="w-4 h-4" />
                    ) : (
                      <Lock className="w-4 h-4" />
                    )}
                  </div>

                  {/* 제목 - flex-1 로 확장 */}
                  <div className="flex-1 min-w-0">
                    <h4 className="text-[var(--text-primary)] font-medium group-hover:text-primary-300 transition-colors truncate text-sm">
                      {item.title || '제목 없음'}
                    </h4>
                  </div>

                  {/* 작성자, 일자, 조회수 - 헤더 컬럼과 동일 간격 배치 */}
                  <div className="flex items-center gap-6 shrink-0">
                    <div className="flex items-center gap-4">
                      <span className="text-white/60 text-sm w-20 truncate text-right">
                        {item.uid || 'ADMIN'}
                      </span>
                      <span className="text-white/50 text-sm w-24 text-center">
                        {formatDate(item.pdate)}
                      </span>
                      <span className="text-white/30 text-xs w-16 text-right font-medium">
                        {item.viewcount || 0}
                      </span>
                    </div>

                    <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-all translate-x-2 group-hover:translate-x-0 w-[88px] justify-end">
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          openEditModal(item);
                        }}
                        className="p-1.5 rounded-lg bg-white/5 hover:bg-white/10 text-primary-400 transition-all border border-white/10"
                        title="편집"
                      >
                        <Edit className="w-4 h-4" />
                      </button>
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDelete(item.idx);
                        }}
                        className="p-1.5 rounded-lg bg-white/5 hover:bg-white/10 text-danger-400 transition-all border border-white/10"
                        title="삭제"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            ))
          )}
        </div>

        {/* 페이징 */}
        {totalPages > 1 && (
          <div className="px-6 py-4 border-t border-white/10 flex items-center justify-between bg-white/[0.02]">
            <div className="text-white/40 text-xs font-medium">
              총 <span className="text-white">{filteredList.length}</span>건 중
              <span className="text-white ml-2">{(currentPage - 1) * pageSize + 1}-{Math.min(currentPage * pageSize, filteredList.length)}</span>건 표시
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => setCurrentPage(1)}
                disabled={currentPage === 1}
                className="w-8 h-8 flex items-center justify-center rounded-lg bg-white/5 text-white/70 hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed transition-all border border-white/10 text-xs"
              >
                «
              </button>
              <button
                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                className="w-8 h-8 flex items-center justify-center rounded-lg bg-white/5 text-white/70 hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed transition-all border border-white/10 text-xs"
              >
                ‹
              </button>
              <div className="flex items-center bg-white/5 px-3 h-8 rounded-lg border border-white/10 text-xs font-bold">
                <span className="text-primary-400">{currentPage}</span>
                <span className="text-white/30 mx-1.5">/</span>
                <span className="text-white/70">{totalPages}</span>
              </div>
              <button
                onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages}
                className="w-8 h-8 flex items-center justify-center rounded-lg bg-white/5 text-white/70 hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed transition-all border border-white/10 text-xs"
              >
                ›
              </button>
              <button
                onClick={() => setCurrentPage(totalPages)}
                disabled={currentPage === totalPages}
                className="w-8 h-8 flex items-center justify-center rounded-lg bg-white/5 text-white/70 hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed transition-all border border-white/10 text-xs"
              >
                »
              </button>
            </div>
          </div>
        )}
      </div>

      {/* 메모 보기 모달 */}
      <NoteViewModal
        isOpen={showViewModal}
        note={selectedNote}
        onClose={() => setShowViewModal(false)}
        onEdit={(note) => {
          setShowViewModal(false);
          setEditingItem(note);
          setShowModal(true);
        }}
        onDelete={(note) => {
          setShowViewModal(false);
          handleDelete(note.idx);
        }}
      />

      {/* 추가/수정 모달 */}
      <NoteEditModal
        isOpen={showModal}
        editingItem={editingItem}
        processing={processing}
        onClose={() => setShowModal(false)}
        onSave={handleSave}
      />
    </div>
  );
}
