import { useState, useEffect } from 'react';
import { Mail, Search, RefreshCw, Calendar, ChevronLeft, ChevronRight } from 'lucide-react';
import { comms } from '@/communication';
import { MailItem, UserInfo } from '@/types';
import { MailTestDialog } from '@/components/mail/MailTestDialog';

export function MailList() {
  const [mailList, setMailList] = useState<MailItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [searchKey, setSearchKey] = useState('');
  const [selectedItem, setSelectedItem] = useState<MailItem | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [showTestDialog, setShowTestDialog] = useState(false);
  const [currentUser, setCurrentUser] = useState<UserInfo | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 25;

  const formatDateLocal = (date: Date) => {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  };

  useEffect(() => {
    // 로그인 정보 로드
    const loadLoginInfo = async () => {
      try {
        const response = await comms.checkLoginStatus();
        if (response.Success && response.IsLoggedIn && response.User) {
          setCurrentUser(response.User);
        }
      } catch (error) {
        console.error('로그인 정보 로드 오류:', error);
      }
    };

    loadLoginInfo();

    const now = new Date();
    const tenDaysAgo = new Date();
    tenDaysAgo.setDate(now.getDate() - 10);

    const start = formatDateLocal(tenDaysAgo);
    const end = formatDateLocal(now);
    
    setStartDate(start);
    setEndDate(end);
    
    // 날짜 설정 후 바로 데이터 로드
    setTimeout(() => {
      loadDataWithDates(start, end);
    }, 100);
  }, []);

  const loadDataWithDates = async (start: string, end: string) => {
    setLoading(true);
    try {
      console.log('메일내역 조회:', { start, end, searchKey });
      const response = await comms.getMailList(start, end, searchKey);
      console.log('메일내역 응답:', response);
      if (response.Success && response.Data) {
        setMailList(response.Data);
      } else {
        console.warn('메일내역 없음:', response.Message);
        setMailList([]);
      }
    } catch (error) {
      console.error('메일내역 로드 오류:', error);
      alert('데이터를 불러오는 중 오류가 발생했습니다.');
    } finally {
      setLoading(false);
    }
  };

  const loadData = async () => {
    if (!startDate || !endDate) return;
    await loadDataWithDates(startDate, endDate);
  };

  const handleSearch = () => {
    if (new Date(startDate) > new Date(endDate)) {
      alert('시작일은 종료일보다 늦을 수 없습니다.');
      return;
    }
    setCurrentPage(1);
    loadData();
  };

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

  const handleRowClick = (item: MailItem) => {
    // 레벨 9 이상(개발자)만 상세보기 가능
    if (!currentUser || currentUser.Level < 9) {
      return;
    }
    setSelectedItem(item);
    setShowModal(true);
  };

  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');
      const hh = String(date.getHours()).padStart(2, '0');
      const mi = String(date.getMinutes()).padStart(2, '0');
      return `${yy}.${mm}.${dd} ${hh}:${mi}`;
    } catch {
      return dateStr;
    }
  };

  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 flex-1">
            <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' && handleSearch()}
              placeholder="제목, 발신자, 수신자 등"
              className="flex-1 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={handleSearch}
            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>

          {currentUser && currentUser.Level >= 9 && (
            <button
              onClick={() => setShowTestDialog(true)}
              className="h-10 bg-green-500 hover:bg-green-600 text-white px-6 rounded-lg transition-colors flex items-center justify-center"
            >
              <Mail 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">
            <Mail className="w-5 h-5 mr-2" />
            메일 발신 내역
          </h3>
          <span className="text-white/60 text-sm">{mailList.length}건</span>
        </div>

        <div className="divide-y divide-white/10 max-h-[calc(100vh-380px)] 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>
          ) : mailList.length === 0 ? (
            <div className="px-6 py-8 text-center">
              <Mail 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-4 transition-colors ${currentUser && currentUser.Level >= 9 ? 'hover:bg-white/5 cursor-pointer' : 'cursor-default'}`}
                onClick={() => handleRowClick(item)}
              >
                <div className="flex items-center justify-between gap-4">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      {item.cate && (
                        <span className="px-2 py-0.5 bg-primary-500/20 text-primary-400 text-xs rounded">
                          {item.cate}
                        </span>
                      )}
                      {item.project && (
                        <span className="px-2 py-0.5 bg-white/10 text-white/70 text-xs rounded">
                          {item.project}
                        </span>
                      )}
                    </div>
                    <h4 className="text-white font-medium mb-1">{item.subject}</h4>
                    <div className="flex items-center gap-4 text-white/60 text-sm">
                      <div>발신: {item.fromlist}</div>
                      <div>수신: {item.tolist}</div>
                    </div>
                  </div>
                  <div className="flex flex-col items-end gap-1 flex-shrink-0">
                    <div className="flex items-center text-white/60 text-xs">
                      <Calendar className="w-3 h-3 mr-1" />
                      {formatDate(item.wdate)}
                    </div>
                  </div>
                </div>
              </div>
            ))
          )}
        </div>

        {/* 페이징 */}
        {totalPages > 1 && (
          <div className="flex items-center justify-center gap-2 px-6 py-3 border-t border-white/10">
            <button
              onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
              disabled={currentPage === 1}
              className="p-1 rounded hover:bg-white/10 disabled:opacity-30 text-white/70"
            >
              <ChevronLeft className="w-5 h-5" />
            </button>
            <span className="text-white/70 text-sm">
              {currentPage} / {totalPages}
            </span>
            <button
              onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
              disabled={currentPage === totalPages}
              className="p-1 rounded hover:bg-white/10 disabled:opacity-30 text-white/70"
            >
              <ChevronRight className="w-5 h-5" />
            </button>
          </div>
        )}
      </div>

      {/* 상세 모달 */}
      {showModal && selectedItem && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
          <div className="bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden border border-white/10">
            <div className="flex items-center justify-between px-6 py-4 border-b border-white/10">
              <div className="flex items-center gap-2">
                {selectedItem.cate && (
                  <span className="px-2 py-1 bg-primary-500/20 text-primary-400 text-sm rounded">
                    {selectedItem.cate}
                  </span>
                )}
                <h2 className="text-xl font-bold text-white ml-2">{selectedItem.subject}</h2>
              </div>
              <button
                onClick={() => setShowModal(false)}
                className="text-white/50 hover:text-white transition-colors"
              >
                <span className="text-2xl">×</span>
              </button>
            </div>

            <div className="px-6 py-4 border-b border-white/10 space-y-2 text-sm">
              <div className="flex items-start gap-2 text-white/70">
                <span className="font-medium w-16">발신:</span>
                <span className="text-white">{selectedItem.fromlist}</span>
              </div>
              <div className="flex items-start gap-2 text-white/70">
                <span className="font-medium w-16">수신:</span>
                <span className="text-white">{selectedItem.tolist}</span>
              </div>
              {selectedItem.cclist && (
                <div className="flex items-start gap-2 text-white/70">
                  <span className="font-medium w-16">참조:</span>
                  <span className="text-white">{selectedItem.cclist}</span>
                </div>
              )}
              {selectedItem.bcclist && (
                <div className="flex items-start gap-2 text-white/70">
                  <span className="font-medium w-16">숨은참조:</span>
                  <span className="text-white">{selectedItem.bcclist}</span>
                </div>
              )}
              <div className="flex items-center gap-2 text-white/60">
                <Calendar className="w-4 h-4" />
                {formatDate(selectedItem.wdate)}
              </div>
            </div>

            <div className="overflow-y-auto max-h-[calc(90vh-280px)] p-6">
              <div 
                className="prose prose-invert max-w-none"
                dangerouslySetInnerHTML={{ __html: selectedItem.htmlbody }}
              />
            </div>

            <div className="flex items-center justify-end px-6 py-4 border-t border-white/10 bg-white/5">
              <button
                onClick={() => setShowModal(false)}
                className="px-4 py-2 rounded-lg bg-white/10 hover:bg-white/20 text-white transition-colors"
              >
                닫기
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 메일 테스트 다이얼로그 */}
      <MailTestDialog
        isOpen={showTestDialog}
        onClose={() => {
          setShowTestDialog(false);
          loadData(); // 목록 새로고침
        }}
      />
    </div>
  );
}
