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

export function Note() {
  const [noteList, setNoteList] = useState<NoteItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [processing, setProcessing] = useState(false);

  // 검색 조건
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  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 = 10;

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

  // 초기화 완료 플래그
  const [initialized, setInitialized] = useState(false);

  // 날짜 초기화
  useEffect(() => {
    const now = new Date();
    // 2000년부터 현재까지 데이터 조회
    const startOfPeriod = new Date(2000, 0, 1);
    
    const sd = formatDateLocal(startOfPeriod);
    const ed = formatDateLocal(now);

    setStartDate(sd);
    setEndDate(ed);

    // 초기화 완료 표시
    setInitialized(true);
  }, []);

  // 초기화 완료 후 조회 실행 (최초 1회만)
  useEffect(() => {
    if (initialized && startDate && endDate) {
      handleSearch();
    }
  }, [initialized]);

  // 데이터 로드
  const loadData = useCallback(async () => {
    if (!startDate || !endDate) return;

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

  // 검색
  const handleSearch = async () => {
    if (new Date(startDate) > new Date(endDate)) {
      alert('시작일은 종료일보다 늦을 수 없습니다.');
      return;
    }
    await 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
  );

  // 검색 시 페이지 초기화
  const handleSearchWithReset = () => {
    setCurrentPage(1);
    handleSearch();
  };

  return (
    <div className="space-y-6 animate-fade-in">
      {/* 검색 필터 */}
      <div className="glass-effect rounded-2xl p-6">
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <label className="text-white/70 text-sm font-medium whitespace-nowrap">기간</label>
            <input
              type="date"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
              className="w-36 h-10 bg-white/20 border border-white/30 rounded-lg px-3 text-white focus:outline-none focus:ring-2 focus:ring-primary-400"
            />
            <span className="text-white/70">~</span>
            <input
              type="date"
              value={endDate}
              onChange={(e) => setEndDate(e.target.value)}
              className="w-36 h-10 bg-white/20 border border-white/30 rounded-lg px-3 text-white focus:outline-none focus:ring-2 focus:ring-primary-400"
            />
          </div>

          <div className="flex items-center gap-2">
            <label className="text-white/70 text-sm font-medium whitespace-nowrap">검색어</label>
            <input
              type="text"
              value={searchKey}
              onChange={(e) => setSearchKey(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleSearchWithReset()}
              placeholder="제목, 내용, 작성자 등"
              className="w-60 h-10 bg-white/20 border border-white/30 rounded-lg px-3 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400"
            />
          </div>

          <button
            onClick={handleSearchWithReset}
            disabled={loading}
            className="h-10 bg-primary-500 hover:bg-primary-600 text-white px-6 rounded-lg transition-colors flex items-center justify-center disabled:opacity-50"
          >
            {loading ? (
              <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
            ) : (
              <Search className="w-4 h-4 mr-2" />
            )}
            조회
          </button>

          <button
            onClick={openAddModal}
            className="h-10 bg-success-500 hover:bg-success-600 text-white px-6 rounded-lg transition-colors flex items-center justify-center"
          >
            <Plus className="w-4 h-4 mr-2" />
            새 메모
          </button>
        </div>
      </div>

      {/* 메모 리스트 */}
      <div className="glass-effect rounded-2xl overflow-hidden">
        <div className="px-6 py-4 border-b border-white/10 flex items-center justify-between">
          <h3 className="text-lg font-semibold text-white flex items-center">
            <FileText className="w-5 h-5 mr-2" />
            메모장 목록
          </h3>
          <span className="text-white/60 text-sm">{filteredList.length}건</span>
        </div>

        <div className="divide-y divide-white/10 max-h-[calc(100vh-300px)] overflow-y-auto">
          {loading ? (
            <div className="px-6 py-8 text-center">
              <div className="flex items-center justify-center">
                <RefreshCw className="w-5 h-5 mr-2 animate-spin text-white/50" />
                <span className="text-white/50">데이터를 불러오는 중...</span>
              </div>
            </div>
          ) : filteredList.length === 0 ? (
            <div className="px-6 py-8 text-center">
              <FileText className="w-12 h-12 mx-auto mb-3 text-white/30" />
              <p className="text-white/50">조회된 데이터가 없습니다.</p>
            </div>
          ) : (
            paginatedList.map((item) => (
              <div
                key={item.idx}
                className="px-6 py-3 hover:bg-white/5 transition-colors cursor-pointer group"
                onClick={() => handleNoteClick(item)}
              >
                <div className="flex items-center justify-between gap-4">
                  <div className="flex items-center gap-3 flex-1 min-w-0">
                    {item.share ? (
                      <Share2 className="w-4 h-4 text-green-400 flex-shrink-0" />
                    ) : (
                      <Lock className="w-4 h-4 text-blue-400 flex-shrink-0" />
                    )}
                    <p className="text-white text-sm font-medium truncate flex-1">
                      {(item.title || '제목 없음').length > 15 ? `${(item.title || '제목 없음').substring(0, 15)}...` : (item.title || '제목 없음')}
                    </p>
                  </div>
                  <div className="flex items-center gap-4 flex-shrink-0">
                    <span className="text-white/60 text-xs">{item.uid || '-'}</span>
                    <span className="text-white/60 text-xs">{formatDate(item.pdate)}</span>
                    <span className="text-white/50 text-xs">조회 {item.viewcount || 0}</span>
                    <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          openEditModal(item);
                        }}
                        className="text-white/40 hover:text-primary-400 transition-colors"
                        title="편집"
                      >
                        <Edit className="w-4 h-4" />
                      </button>
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDelete(item.idx);
                        }}
                        className="text-white/40 hover:text-red-400 transition-colors"
                        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">
            <div className="text-white/50 text-sm">
              총 {filteredList.length}건 중 {(currentPage - 1) * pageSize + 1}-{Math.min(currentPage * pageSize, filteredList.length)}건
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => setCurrentPage(1)}
                disabled={currentPage === 1}
                className="px-3 py-1 rounded bg-white/10 text-white/70 hover:bg-white/20 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
              >
                «
              </button>
              <button
                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                className="px-3 py-1 rounded bg-white/10 text-white/70 hover:bg-white/20 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
              >
                ‹
              </button>
              <span className="text-white/70 px-3">
                {currentPage} / {totalPages}
              </span>
              <button
                onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages}
                className="px-3 py-1 rounded bg-white/10 text-white/70 hover:bg-white/20 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
              >
                ›
              </button>
              <button
                onClick={() => setCurrentPage(totalPages)}
                disabled={currentPage === totalPages}
                className="px-3 py-1 rounded bg-white/10 text-white/70 hover:bg-white/20 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
              >
                »
              </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>
  );
}
