import { useState, useEffect, useCallback } from 'react';
import {
  FolderKanban,
  Search,
  RefreshCw,
  ChevronLeft,
  ChevronRight,
  User,
  Calendar,
  ExternalLink,
  ClipboardList,
  Mail,
  Edit2,
  XCircle,
} from 'lucide-react';
import { comms } from '@/communication';
import { ProjectListItem, ProjectListResponse } from '@/types';
import { ProjectDetailDialog } from '@/components/project';
import { DevelopmentNotice } from '@/components/DevelopmentNotice';
import clsx from 'clsx';

// 상태별 색상 매핑
const statusColors: Record<string, { text: string; bg: string }> = {
  검토: { text: 'text-blue-400', bg: 'bg-blue-500/20' },
  진행: { text: 'text-green-400', bg: 'bg-green-500/20' },
  대기: { text: 'text-yellow-400', bg: 'bg-yellow-500/20' },
  보류: { text: 'text-orange-400', bg: 'bg-orange-500/20' },
  완료: { text: 'text-purple-400', bg: 'bg-purple-500/20' },
  '완료(보고)': { text: 'text-gray-400', bg: 'bg-gray-500/20' },
  취소: { text: 'text-red-400', bg: 'bg-red-500/20' },
};

export function Project() {
  const [projects, setProjects] = useState<ProjectListItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedProject, setSelectedProject] = useState<ProjectListItem | null>(null);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [expandedProject, setExpandedProject] = useState<number | null>(null);
  const [projectHistory, setProjectHistory] = useState<any[]>([]);
  const [loadingHistory, setLoadingHistory] = useState(false);
  const [editingHistory, setEditingHistory] = useState<any | null>(null);
  const [editRemark, setEditRemark] = useState('');

  // 필터 상태
  const [categories, setCategories] = useState<string[]>([]);
  const [processes, setProcesses] = useState<string[]>([]);
  const [selectedCategory, setSelectedCategory] = useState('--전체--');
  const [selectedProcess, setSelectedProcess] = useState('전체');
  const [userFilter, setUserFilter] = useState('');
  const [currentUserName, setCurrentUserName] = useState('');
  const [userLevel, setUserLevel] = useState<number>(0);
  const [userCode, setUserCode] = useState<string>('');

  // 상태 필터 체크박스
  const [statusChecks, setStatusChecks] = useState({
    검토: true,
    진행: true,
    대기: false,
    보류: true,
    완료: true,
    '완료(보고)': false,
    취소: false,
  });

  // 날짜 필터
  const [dateType, setDateType] = useState('0');
  const [yearStart, setYearStart] = useState(new Date().getFullYear().toString());

  // 검색
  const [searchKey, setSearchKey] = useState('');
  const [filteredProjects, setFilteredProjects] = useState<ProjectListItem[]>([]);

  // 상태별 건수
  const [statusCounts, setStatusCounts] = useState<Record<string, number>>({});

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

  // 연도 목록 생성
  const years = Array.from({ length: new Date().getFullYear() - 2009 }, (_, i) => (2010 + i).toString());

  // 날짜 포맷
  const formatDate = (dateStr?: string) => {
    if (!dateStr) return '-';
    const d = dateStr.substring(0, 10);
    if (d.length < 10) return d;
    return `${d.substring(2, 4)}-${d.substring(5, 7)}-${d.substring(8, 10)}`;
  };

  // 초기화
  useEffect(() => {
    const init = async () => {
      // 현재 사용자 로드
      try {
        const loginStatus = await comms.checkLoginStatus();
        if (loginStatus.Success && loginStatus.IsLoggedIn && loginStatus.User) {
          const user = loginStatus.User as { NameK?: string; Level?: number; Code?: string };
          const userName = user.NameK || loginStatus.User.Name || '';
          setCurrentUserName(userName);
          setUserFilter(userName);
          setUserLevel(user.Level || 0);
          setUserCode(user.Code || '');
        }
      } catch (error) {
        console.error('로그인 정보 로드 오류:', error);
      }

      // 분류/공정 목록 로드
      try {
        const [catRes, procRes] = await Promise.all([
          comms.getProjectCategories(),
          comms.getProjectProcesses(),
        ]);
        if (catRes.Success && catRes.Data) setCategories(catRes.Data as string[]);
        if (procRes.Success && procRes.Data) setProcesses(procRes.Data as string[]);
      } catch (error) {
        console.error('필터 목록 로드 오류:', error);
      }
    };
    init();
  }, []);

  // 데이터 로드
  const loadProjects = useCallback(async () => {
    setLoading(true);
    try {
      const checkedStatuses = Object.entries(statusChecks)
        .filter(([, checked]) => checked)
        .map(([status]) => status);

      const statusFilter = checkedStatuses.length === 7 ? 'all' : checkedStatuses.join(',');

      const response = await comms.getProjectList(
        statusFilter,
        selectedCategory,
        selectedProcess,
        userFilter,
        dateType !== '0' ? yearStart : '',
        dateType !== '0' ? yearStart : '',
        dateType
      ) as ProjectListResponse;

      if (response.Success && response.Data) {
        setProjects(response.Data);
        setFilteredProjects(response.Data);
        if (response.StatusCounts) {
          setStatusCounts(response.StatusCounts as Record<string, number>);
        }
      }
    } catch (error) {
      console.error('프로젝트 로드 오류:', error);
    } finally {
      setLoading(false);
    }
  }, [statusChecks, selectedCategory, selectedProcess, userFilter, dateType, yearStart]);

  // 필터 변경 시 자동 조회
  useEffect(() => {
    if (currentUserName) {
      loadProjects();
    }
  }, [loadProjects, currentUserName]);

  // 검색어 필터링
  useEffect(() => {
    if (!searchKey.trim()) {
      setFilteredProjects(projects);
    } else {
      const key = searchKey.toLowerCase();
      const filtered = projects.filter(
        (p) =>
          p.name?.toLowerCase().includes(key) ||
          p.name_champion?.toLowerCase().includes(key) ||
          p.name_design?.toLowerCase().includes(key) ||
          p.name_epanel?.toLowerCase().includes(key) ||
          p.name_software?.toLowerCase().includes(key) ||
          p.reqstaff?.toLowerCase().includes(key) ||
          p.orderno?.toLowerCase().includes(key) ||
          p.memo?.toLowerCase().includes(key)
      );
      setFilteredProjects(filtered);
    }
    setCurrentPage(1);
  }, [searchKey, projects]);

  // 프로젝트 선택 시 다이얼로그 표시
  const handleSelectProject = (project: ProjectListItem) => {
    setSelectedProject(project);
    setShowDetailDialog(true);
  };

  // 다이얼로그 닫기
  const handleCloseDialog = () => {
    setShowDetailDialog(false);
  };

  // 담당자 필터 토글
  const toggleUserFilter = () => {
    setUserFilter(userFilter ? '' : currentUserName);
  };

  // 상태 체크박스 토글
  const toggleStatus = (status: string) => {
    setStatusChecks((prev) => ({ ...prev, [status]: !prev[status as keyof typeof prev] }));
  };

  // 히스토리 토글 (편집 아이콘 클릭)
  const toggleHistory = async (projectIdx: number) => {
    if (expandedProject === projectIdx) {
      setExpandedProject(null);
      setProjectHistory([]);
      setEditingHistory(null);
    } else {
      setExpandedProject(projectIdx);
      setLoadingHistory(true);
      try {
        const result = await comms.getProjectHistory(projectIdx);
        if (result.Success && result.Data) {
          setProjectHistory(result.Data as any[]);
        } else {
          setProjectHistory([]);
        }
      } catch (error) {
        console.error('히스토리 로드 오류:', error);
        setProjectHistory([]);
      } finally {
        setLoadingHistory(false);
      }
    }
  };

  // 히스토리 편집 시작
  const startEditHistory = (history: any) => {
    setEditingHistory(history);
    setEditRemark(history.remark || '');
  };

  // 새 히스토리 추가 시작
  const startAddHistory = (projectIdx: number) => {
    const today = new Date().toISOString().substring(0, 10);
    setEditingHistory({ pidx: projectIdx, pdate: today, progress: 0, remark: '', isNew: true });
    setEditRemark('');
  };

  // 히스토리 저장
  const saveHistory = async () => {
    if (!editingHistory) return;

    try {
      const historyData = {
        idx: editingHistory.idx || 0,
        pidx: editingHistory.pidx,
        pdate: editingHistory.pdate,
        progress: editingHistory.progress || 0,
        remark: editRemark,
      };

      const result = await comms.saveProjectHistory(historyData);

      if (result.Success) {
        // 저장 성공 후 히스토리 다시 로드
        const historyResult = await comms.getProjectHistory(editingHistory.pidx);
        if (historyResult.Success && historyResult.Data) {
          setProjectHistory(historyResult.Data as any[]);
        }
      } else {
        alert(result.Message || '저장에 실패했습니다.');
      }

      setEditingHistory(null);
      setEditRemark('');
    } catch (error) {
      console.error('히스토리 저장 오류:', error);
    }
  };

  // 편집 취소
  const cancelEdit = () => {
    setEditingHistory(null);
    setEditRemark('');
  };

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

  // 자스민 링크 열기
  const openJasmin = (jasminId?: number) => {
    if (jasminId && jasminId > 0) {
      window.open(`https://scwa.amkor.co.kr/jasmine/view/${jasminId}`, '_blank');
    }
  };

  return (
    <div className="p-4 space-y-4 relative">
      {/* 개발중 알림 */}
      <DevelopmentNotice />

      {/* 헤더 */}
      <div className="glass-effect rounded-xl p-4">
        <div className="flex items-center justify-between mb-4">
          <button
            onClick={loadProjects}
            disabled={loading}
            className="flex items-center gap-2 px-4 py-2 bg-primary-500/20 hover:bg-primary-500/30 text-primary-400 rounded-lg transition-colors"
          >
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
            <span>새로고침</span>
          </button>
        </div>

        {/* 필터 영역 */}
        <div className="space-y-3">
          {/* 상태 필터 */}
          <div className="flex flex-wrap items-center gap-2">
            {Object.entries(statusChecks).map(([status, checked]) => (
              <button
                key={status}
                onClick={() => toggleStatus(status)}
                className={`px-3 py-1 rounded-lg text-sm transition-all ${checked
                  ? `${statusColors[status]?.bg || 'bg-white/20'} ${statusColors[status]?.text || 'text-white'} font-semibold`
                  : 'bg-white/5 text-white/50'
                  }`}
              >
                {status}
                <span className="ml-1 text-xs">({statusCounts[status] || 0})</span>
              </button>
            ))}
          </div>

          {/* 추가 필터 */}
          <div className="flex flex-wrap items-center gap-3">
            <button
              onClick={toggleUserFilter}
              className={`flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm transition-all ${userFilter ? 'bg-primary-500/20 text-primary-400' : 'bg-white/5 text-white/50'
                }`}
            >
              <User className="w-4 h-4" />
              <span>{userFilter || '전체'}</span>
            </button>

            <select
              value={selectedCategory}
              onChange={(e) => setSelectedCategory(e.target.value)}
              className="px-3 py-1.5 bg-white/5 border border-white/10 rounded-lg text-white text-sm"
            >
              {categories.map((cat) => (
                <option key={cat} value={cat} className="bg-gray-800">
                  {cat}
                </option>
              ))}
            </select>

            <select
              value={selectedProcess}
              onChange={(e) => setSelectedProcess(e.target.value)}
              className="px-3 py-1.5 bg-white/5 border border-white/10 rounded-lg text-white text-sm"
            >
              {processes.map((proc) => (
                <option key={proc} value={proc} className="bg-gray-800">
                  {proc}
                </option>
              ))}
            </select>

            <div className="flex items-center gap-2">
              <Calendar className="w-4 h-4 text-white/50" />
              <select
                value={dateType}
                onChange={(e) => setDateType(e.target.value)}
                className="px-2 py-1.5 bg-white/5 border border-white/10 rounded-lg text-white text-sm"
              >
                <option value="0" className="bg-gray-800">전체기간</option>
                <option value="1" className="bg-gray-800">시작일</option>
                <option value="2" className="bg-gray-800">만료일</option>
                <option value="3" className="bg-gray-800">완료일</option>
                <option value="4" className="bg-gray-800">출고일</option>
              </select>
              {dateType !== '0' && (
                <select
                  value={yearStart}
                  onChange={(e) => setYearStart(e.target.value)}
                  className="px-2 py-1.5 bg-white/5 border border-white/10 rounded-lg text-white text-sm"
                >
                  {years.map((y) => (
                    <option key={y} value={y} className="bg-gray-800">
                      {y}
                    </option>
                  ))}
                </select>
              )}
            </div>

            <div className="flex items-center gap-2 ml-auto">
              <Search className="w-4 h-4 text-white/50" />
              <input
                type="text"
                value={searchKey}
                onChange={(e) => setSearchKey(e.target.value)}
                placeholder="프로젝트명, 담당자..."
                className="px-3 py-1.5 bg-white/5 border border-white/10 rounded-lg text-white text-sm w-48"
              />
            </div>
          </div>
        </div>
      </div>

      {/* 메인 콘텐츠 */}
      <div className="glass-effect rounded-2xl overflow-hidden shadow-2xl transition-all duration-300">
        <div className="px-6 py-4 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">
              <FolderKanban className="w-5 h-5 text-primary-400" />
            </div>
            <h3 className="text-lg font-bold text-[var(--text-primary)] tracking-tight">
              프로젝트 목록
            </h3>
          </div>

          <div className="flex items-center gap-4 w-full md:w-auto">
            {/* 검색 필터 */}
            <div className="relative flex-1 md:w-80 group">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-[var(--text-secondary)] group-focus-within:text-primary-400 transition-colors" />
              <input
                type="text"
                value={searchKey}
                onChange={(e) => setSearchKey(e.target.value)}
                placeholder="검색..."
                className="w-full bg-[var(--bg-paper)] border border-[var(--border-color)] rounded-xl pl-10 pr-10 py-2 text-[var(--text-primary)] focus:outline-none focus:ring-2 focus:ring-primary-500/50 transition-all text-sm placeholder-[var(--text-muted)]"
              />
              {searchKey && (
                <button
                  onClick={() => setSearchKey('')}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors"
                >
                  <XCircle className="w-4 h-4" />
                </button>
              )}
            </div>
            <div className="flex items-center gap-1 bg-[var(--bg-paper)] px-3 py-1.5 rounded-lg border border-[var(--border-color)]">
              <span className="text-[var(--text-primary)] font-bold text-sm">{filteredProjects.length}</span>
              <span className="text-[var(--text-secondary)] text-xs">건</span>
            </div>
          </div>
        </div>
        <table className="w-full text-sm">
          <thead className="bg-white/5 sticky top-0">
            <tr className="text-white/60 text-left">
              <th className="px-3 py-2 w-16">상태</th>
              <th className="px-3 py-2">프로젝트명</th>
              <th className="px-3 py-2 w-20">챔피언</th>
              <th className="px-3 py-2 w-28">요청자</th>
              <th className="px-3 py-2 w-20 text-center">진행률</th>
              <th className="px-3 py-2 w-24">시작</th>
              <th className="px-3 py-2 w-24">만료/완료</th>
              <th className="px-3 py-2 w-10"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-white/5">
            {loading ? (
              <tr>
                <td colSpan={8} className="px-3 py-8 text-center text-white/50">
                  <RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2" />
                  로딩중...
                </td>
              </tr>
            ) : paginatedProjects.length === 0 ? (
              <tr>
                <td colSpan={8} className="px-3 py-8 text-center text-white/50">
                  프로젝트가 없습니다.
                </td>
              </tr>
            ) : (
              paginatedProjects.map((project) => {
                const statusColor = statusColors[project.status] || { text: 'text-white', bg: 'bg-white/10' };
                const isExpanded = expandedProject === project.idx;

                return (
                  <>
                    <tr
                      key={project.idx}
                      className={clsx(
                        'border-b border-white/10 cursor-pointer hover:bg-white/5',
                        isExpanded && 'bg-primary-900/30'
                      )}
                      onClick={() => toggleHistory(project.idx)}
                    >
                      <td className="px-3 py-2">
                        <span className={`px-2 py-0.5 rounded text-xs ${statusColor.bg} ${statusColor.text}`}>
                          {project.status}
                        </span>
                      </td>
                      <td className={`px-3 py-2 ${statusColor.text}`}>
                        <div className="truncate max-w-xs" title={project.name}>
                          <div className="flex items-center gap-2">
                            <button
                              onClick={e => {
                                e.stopPropagation();
                                handleSelectProject(project);
                              }}
                              className="text-primary-300 hover:text-primary-200 transition-colors"
                              title="편집"
                            >
                              <Edit2 className="w-4 h-4" />
                            </button>
                            <span className="font-regular text-white/90">{project.name}</span>
                          </div>
                        </div>
                      </td>
                      <td className="px-3 py-2 text-white/70">{project.name_champion || project.userManager}</td>
                      <td className="px-3 py-2 text-white/70 text-xs">
                        <div>{project.ReqLine}</div>
                        <div className="text-white/50">{project.reqstaff}</div>
                      </td>
                      <td className="px-3 py-2">
                        <div className="flex items-center gap-2">
                          <div className="flex-1 h-2 bg-white/10 rounded-full overflow-hidden">
                            <div
                              className="h-full bg-primary-500 transition-all"
                              style={{ width: `${project.progress || 0}%` }}
                            />
                          </div>
                          <span className="text-xs text-white/50">{project.progress || 0}%</span>
                        </div>
                      </td>
                      <td className="px-3 py-2 text-white/50">{formatDate(project.sdate)}</td>
                      <td className="px-3 py-2 text-white/50 text-xs">
                        <div>{formatDate(project.ddate)}</div>
                        <div className="text-white/40">{formatDate(project.edate)}</div>
                      </td>
                      <td className="px-3 py-2">
                        <div className="flex items-center gap-2">
                          {project.jasmin && project.jasmin > 0 && (
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                openJasmin(project.jasmin);
                              }}
                              className="text-primary-400 hover:text-primary-300"
                              title="자스민 열기"
                            >
                              <ExternalLink className="w-4 h-4" />
                            </button>
                          )}
                          {(userLevel >= 9 || userCode === '395552') && (
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                const w = window as any;
                                if (w.CefSharp) {
                                  w.CefSharp.BindObjectAsync('bridge').then(() => {
                                    w.bridge?.OpenMailHistory();
                                  });
                                }
                              }}
                              className="text-cyan-400 hover:text-cyan-300"
                              title="메일내역"
                            >
                              <Mail className="w-4 h-4" />
                            </button>
                          )}
                          <a
                            href={`#/partlist?idx=${project.idx}&name=${encodeURIComponent(project.name)}`}
                            onClick={(e) => e.stopPropagation()}
                            className="text-amber-400 hover:text-amber-300"
                            title="파트리스트"
                          >
                            <ClipboardList className="w-4 h-4" />
                          </a>
                        </div>
                      </td>
                    </tr>
                    {isExpanded && (
                      <tr key={`history-${project.idx}`}>
                        <td colSpan={8} className="px-3 py-2 bg-primary-950/50">
                          <div className="p-4">
                            <div className="flex items-center justify-between mb-3">
                              <div className="text-sm font-semibold text-primary-300">주간 업무 내용</div>
                              <button
                                onClick={() => startAddHistory(project.idx)}
                                className="text-xs px-3 py-1 bg-primary-500/20 hover:bg-primary-500/30 text-primary-400 rounded transition-colors"
                              >
                                + 새 내용 등록
                              </button>
                            </div>
                            {loadingHistory ? (
                              <div className="text-white/50 text-sm">로딩 중...</div>
                            ) : editingHistory ? (
                              <div className="bg-white/10 rounded p-3 space-y-3">
                                <div className="flex gap-4 text-xs text-white/60">
                                  <span className="text-primary-400 font-semibold">{formatDate(editingHistory.pdate)}</span>
                                  <span>진행률: {editingHistory.progress || 0}%</span>
                                </div>
                                <textarea
                                  value={editRemark}
                                  onChange={(e) => setEditRemark(e.target.value)}
                                  className="w-full h-32 px-3 py-2 bg-white/5 border border-white/10 rounded text-white text-sm resize-none"
                                  placeholder="업무 내용을 입력하세요..."
                                />
                                <div className="flex gap-2 justify-end">
                                  <button
                                    onClick={cancelEdit}
                                    className="px-3 py-1 bg-white/5 hover:bg-white/10 text-white/70 rounded text-sm transition-colors"
                                  >
                                    취소
                                  </button>
                                  <button
                                    onClick={saveHistory}
                                    className="px-3 py-1 bg-primary-500/20 hover:bg-primary-500/30 text-primary-400 rounded text-sm transition-colors"
                                  >
                                    저장
                                  </button>
                                </div>
                              </div>
                            ) : projectHistory.length > 0 ? (
                              <div
                                className="bg-white/5 rounded p-3 border-l-2 border-primary-500 cursor-pointer hover:bg-white/10 transition-colors"
                                onClick={() => startEditHistory(projectHistory[0])}
                              >
                                <div className="flex gap-4 mb-2 text-xs">
                                  <span className="text-primary-400 font-semibold">{formatDate(projectHistory[0].pdate)}</span>
                                  <span className="text-white/60">진행률: {projectHistory[0].progress || 0}%</span>
                                  <span className="text-white/40">{projectHistory[0].wname || ''}</span>
                                </div>
                                {projectHistory[0].remark ? (
                                  <div className="text-sm text-white/80 whitespace-pre-wrap">{projectHistory[0].remark}</div>
                                ) : (
                                  <div className="text-sm text-white/40 italic">내용이 비어있습니다. 클릭하여 입력하세요.</div>
                                )}
                              </div>
                            ) : (
                              <div className="text-white/50 text-sm text-center py-4">
                                업무 내용이 없습니다. 새 내용을 등록하세요.
                              </div>
                            )}
                          </div>
                        </td>
                      </tr>
                    )}
                  </>
                );
              })
            )}
          </tbody>
        </table>
      </div>

      {/* 페이징 */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2 p-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"
          >
            <ChevronLeft className="w-5 h-5 text-white/70" />
          </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"
          >
            <ChevronRight className="w-5 h-5 text-white/70" />
          </button>
        </div>
      )}
      {/* 프로젝트 상세 다이얼로그 */}
      {showDetailDialog && selectedProject && (
        <ProjectDetailDialog
          project={selectedProject}
          onClose={handleCloseDialog}
        />
      )}
    </div>
  );
}
