import { useState, useEffect } from 'react';
import {
  X,
  FolderOpen,
  Save,
  ExternalLink,
} from 'lucide-react';
import { comms } from '@/communication';
import { ProjectListItem, ProjectHistory, ProjectDailyMemo } from '@/types';

interface ProjectDetailDialogProps {
  project: ProjectListItem;
  onClose: () => void;
}

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

const statusOptions = ['검토', '진행', '대기', '보류', '완료', '완료(보고)', '취소'];

export function ProjectDetailDialog({ project, onClose }: ProjectDetailDialogProps) {
  const [history, setHistory] = useState<ProjectHistory[]>([]);
  const [dailyMemos, setDailyMemos] = useState<ProjectDailyMemo[]>([]);
  const [activeTab, setActiveTab] = useState<'history' | 'memo' | 'complete'>('history');

  // 편집 가능한 필드들
  const [formData, setFormData] = useState({
    name: project.name || '',
    status: project.status || '',
    process: project.process || '',
    part: project.part || '',
    asset: project.asset || '',
    model: project.model || '',
    serial: project.serial || '',
    orderno: project.orderno || '',
    userManager: project.userManager || '',
    usermain: project.usermain || '',
    usersub: project.usersub || '',
    userhw2: project.userhw2 || '',
    ReqLine: project.ReqLine || '',
    reqstaff: project.reqstaff || '',
    ReqSite: project.ReqSite || '',
    ReqPlant: project.ReqPlant || '',
    ReqPackage: project.ReqPackage || '',
    remark_req: project.remark_req || '',
    sdate: project.sdate?.substring(0, 10) || '',
    ddate: project.ddate?.substring(0, 10) || '',
    edate: project.edate?.substring(0, 10) || '',
    odate: project.odate?.substring(0, 10) || '',
    costo: project.costo?.toString() || '',
    costn: project.costn?.toString() || '',
    cnt: project.cnt?.toString() || '',
    path: project.path || '',
    memo: project.memo || '',
    progress: project.progress?.toString() || '0',
  });

  useEffect(() => {
    loadDetails();
  }, [project.idx]);

  const loadDetails = async () => {
    try {
      const [historyRes, memoRes] = await Promise.all([
        comms.getProjectHistory(project.idx),
        comms.getProjectDailyMemo(project.idx),
      ]);

      if (historyRes.Success && historyRes.Data) {
        setHistory(historyRes.Data as ProjectHistory[]);
      }
      if (memoRes.Success && memoRes.Data) {
        setDailyMemos(memoRes.Data as ProjectDailyMemo[]);
      }
    } catch (error) {
      console.error('상세 정보 로드 오류:', error);
    }
  };

  const formatDate = (dateStr?: string) => {
    if (!dateStr) return '-';
    return dateStr.substring(0, 10);
  };

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

  const handleChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const statusColor = statusColors[formData.status] || { text: 'text-white', bg: 'bg-white/10', border: 'border-white/20' };

  // 입력 필드 스타일
  const inputClass = "w-full px-2 py-1.5 text-sm bg-white/5 border border-white/20 rounded text-white focus:outline-none focus:border-primary-500";
  const labelClass = "text-xs text-white/60 mb-1 block";

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
      <div className="bg-gray-900/95 border border-white/10 rounded-2xl shadow-2xl w-[1200px] h-[90vh] flex flex-col">
        {/* 헤더 */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-white/10 shrink-0">
          <div className="flex items-center gap-4">
            <select
              value={formData.status}
              onChange={(e) => handleChange('status', e.target.value)}
              className={`px-3 py-1.5 rounded-lg text-sm font-medium border ${statusColor.bg} ${statusColor.text} ${statusColor.border}`}
            >
              {statusOptions.map(opt => (
                <option key={opt} value={opt} className="bg-gray-800 text-white">{opt}</option>
              ))}
            </select>
            <div>
              <h2 className="text-lg font-semibold text-white">{project.name}</h2>
              <p className="text-sm text-white/50">IDX: {project.idx} | PNO: {project.pno || '-'} | Order: {project.orderno || '-'}</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button className="flex items-center gap-2 px-4 py-2 bg-primary-500 hover:bg-primary-600 text-white rounded-lg transition-colors text-sm">
              <Save className="w-4 h-4" />
              저장
            </button>
            {project.path && (
              <button className="flex items-center gap-2 px-3 py-2 bg-white/10 hover:bg-white/20 text-white/80 rounded-lg transition-colors text-sm">
                <FolderOpen className="w-4 h-4" />
                폴더
              </button>
            )}
            {project.jasmin && project.jasmin > 0 && (
              <button
                onClick={() => openJasmin(project.jasmin)}
                className="flex items-center gap-2 px-3 py-2 bg-white/10 hover:bg-white/20 text-white/80 rounded-lg transition-colors text-sm"
              >
                <ExternalLink className="w-4 h-4" />
                Jasmin
              </button>
            )}
            <button onClick={onClose} className="p-2 rounded-lg hover:bg-white/10 transition-colors ml-2">
              <X className="w-5 h-5 text-white/70" />
            </button>
          </div>
        </div>

        {/* 메인 콘텐츠 - 스크롤 가능 */}
        <div className="flex-1 overflow-y-auto p-6">
          <div className="flex gap-6">
            {/* 왼쪽 영역 */}
            <div className="w-[400px] shrink-0 space-y-4">
              {/* 기본 정보 */}
              <div className="glass-effect rounded-xl p-4">
                <h3 className="text-white font-medium mb-3 pb-2 border-b border-white/10">기본 정보</h3>
                <div className="space-y-3">
                  <div>
                    <label className={labelClass}>프로젝트명</label>
                    <input type="text" value={formData.name} onChange={(e) => handleChange('name', e.target.value)} className={inputClass} />
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className={labelClass}>공정</label>
                      <input type="text" value={formData.process} onChange={(e) => handleChange('process', e.target.value)} className={inputClass} />
                    </div>
                    <div>
                      <label className={labelClass}>파트</label>
                      <input type="text" value={formData.part} onChange={(e) => handleChange('part', e.target.value)} className={inputClass} />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className={labelClass}>Asset</label>
                      <input type="text" value={formData.asset} onChange={(e) => handleChange('asset', e.target.value)} className={inputClass} />
                    </div>
                    <div>
                      <label className={labelClass}>Order#</label>
                      <input type="text" value={formData.orderno} onChange={(e) => handleChange('orderno', e.target.value)} className={inputClass} />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className={labelClass}>Model#</label>
                      <input type="text" value={formData.model} onChange={(e) => handleChange('model', e.target.value)} className={inputClass} />
                    </div>
                    <div>
                      <label className={labelClass}>Serial#</label>
                      <input type="text" value={formData.serial} onChange={(e) => handleChange('serial', e.target.value)} className={inputClass} />
                    </div>
                  </div>
                </div>
              </div>

              {/* 담당자 */}
              <div className="glass-effect rounded-xl p-4">
                <h3 className="text-white font-medium mb-3 pb-2 border-b border-white/10">담당자</h3>
                <div className="space-y-3">
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className={labelClass}>Champion</label>
                      <input type="text" value={formData.userManager} onChange={(e) => handleChange('userManager', e.target.value)} className={inputClass} />
                    </div>
                    <div>
                      <label className={labelClass}>Design</label>
                      <input type="text" value={formData.usermain} onChange={(e) => handleChange('usermain', e.target.value)} className={inputClass} />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className={labelClass}>S/W</label>
                      <input type="text" value={formData.usersub} onChange={(e) => handleChange('usersub', e.target.value)} className={inputClass} />
                    </div>
                    <div>
                      <label className={labelClass}>ePanel</label>
                      <input type="text" value={formData.userhw2} onChange={(e) => handleChange('userhw2', e.target.value)} className={inputClass} />
                    </div>
                  </div>
                </div>
              </div>

              {/* 요청 정보 */}
              <div className="glass-effect rounded-xl p-4">
                <h3 className="text-white font-medium mb-3 pb-2 border-b border-white/10">요청 정보</h3>
                <div className="space-y-3">
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className={labelClass}>Line</label>
                      <input type="text" value={formData.ReqLine} onChange={(e) => handleChange('ReqLine', e.target.value)} className={inputClass} />
                    </div>
                    <div>
                      <label className={labelClass}>요청자</label>
                      <input type="text" value={formData.reqstaff} onChange={(e) => handleChange('reqstaff', e.target.value)} className={inputClass} />
                    </div>
                  </div>
                  <div className="grid grid-cols-3 gap-3">
                    <div>
                      <label className={labelClass}>Site</label>
                      <input type="text" value={formData.ReqSite} onChange={(e) => handleChange('ReqSite', e.target.value)} className={inputClass} />
                    </div>
                    <div>
                      <label className={labelClass}>Plant</label>
                      <input type="text" value={formData.ReqPlant} onChange={(e) => handleChange('ReqPlant', e.target.value)} className={inputClass} />
                    </div>
                    <div>
                      <label className={labelClass}>Package</label>
                      <input type="text" value={formData.ReqPackage} onChange={(e) => handleChange('ReqPackage', e.target.value)} className={inputClass} />
                    </div>
                  </div>
                  <div>
                    <label className={labelClass}>요청내용</label>
                    <textarea
                      value={formData.remark_req}
                      onChange={(e) => handleChange('remark_req', e.target.value)}
                      rows={2}
                      className={`${inputClass} resize-none`}
                    />
                  </div>
                </div>
              </div>
            </div>

            {/* 중앙 영역 */}
            <div className="w-[280px] shrink-0 space-y-4">
              {/* 일정 */}
              <div className="glass-effect rounded-xl p-4">
                <h3 className="text-white font-medium mb-3 pb-2 border-b border-white/10">일정</h3>
                <div className="space-y-3">
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className={labelClass}>시작일</label>
                      <input type="date" value={formData.sdate} onChange={(e) => handleChange('sdate', e.target.value)} className={inputClass} />
                    </div>
                    <div>
                      <label className={labelClass}>만료일</label>
                      <input type="date" value={formData.ddate} onChange={(e) => handleChange('ddate', e.target.value)} className={inputClass} />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className={labelClass}>완료일</label>
                      <input type="date" value={formData.edate} onChange={(e) => handleChange('edate', e.target.value)} className={inputClass} />
                    </div>
                    <div>
                      <label className={labelClass}>출고일</label>
                      <input type="date" value={formData.odate} onChange={(e) => handleChange('odate', e.target.value)} className={inputClass} />
                    </div>
                  </div>
                </div>
              </div>

              {/* 진행률 */}
              <div className="glass-effect rounded-xl p-4">
                <h3 className="text-white font-medium mb-3 pb-2 border-b border-white/10">진행률</h3>
                <div className="flex items-center gap-3">
                  <input
                    type="range"
                    min="0"
                    max="100"
                    value={formData.progress}
                    onChange={(e) => handleChange('progress', e.target.value)}
                    className="flex-1 h-2 bg-white/10 rounded-lg appearance-none cursor-pointer"
                  />
                  <input
                    type="number"
                    min="0"
                    max="100"
                    value={formData.progress}
                    onChange={(e) => handleChange('progress', e.target.value)}
                    className="w-16 px-2 py-1.5 text-sm bg-white/5 border border-white/20 rounded text-white text-center"
                  />
                  <span className="text-sm text-white/60">%</span>
                </div>
                <div className="mt-3 h-3 bg-white/10 rounded-full overflow-hidden">
                  <div
                    className="h-full bg-primary-500 transition-all"
                    style={{ width: `${formData.progress}%` }}
                  />
                </div>
              </div>

              {/* 비용 */}
              <div className="glass-effect rounded-xl p-4">
                <h3 className="text-white font-medium mb-3 pb-2 border-b border-white/10">비용</h3>
                <div className="space-y-3">
                  <div>
                    <label className={labelClass}>예상비용</label>
                    <input type="number" value={formData.costo} onChange={(e) => handleChange('costo', e.target.value)} className={inputClass} />
                  </div>
                  <div>
                    <label className={labelClass}>실비용</label>
                    <input type="number" value={formData.costn} onChange={(e) => handleChange('costn', e.target.value)} className={inputClass} />
                  </div>
                  <div>
                    <label className={labelClass}>수량</label>
                    <input type="number" value={formData.cnt} onChange={(e) => handleChange('cnt', e.target.value)} className={inputClass} />
                  </div>
                </div>
              </div>

              {/* 저장경로 */}
              <div className="glass-effect rounded-xl p-4">
                <h3 className="text-white font-medium mb-3 pb-2 border-b border-white/10">저장경로</h3>
                <input
                  type="text"
                  value={formData.path}
                  onChange={(e) => handleChange('path', e.target.value)}
                  className={inputClass}
                  placeholder="\\server\path..."
                />
              </div>
            </div>

            {/* 오른쪽 영역 - 탭 */}
            <div className="flex-1 min-w-0 flex flex-col glass-effect rounded-xl overflow-hidden">
              {/* 탭 헤더 */}
              <div className="flex border-b border-white/10 shrink-0">
                <button
                  onClick={() => setActiveTab('history')}
                  className={`px-4 py-3 text-sm transition-colors ${activeTab === 'history'
                    ? 'bg-white/10 text-white border-b-2 border-primary-500'
                    : 'text-white/60 hover:text-white hover:bg-white/5'}`}
                >
                  주간업무현황 ({history.length})
                </button>
                <button
                  onClick={() => setActiveTab('memo')}
                  className={`px-4 py-3 text-sm transition-colors ${activeTab === 'memo'
                    ? 'bg-white/10 text-white border-b-2 border-primary-500'
                    : 'text-white/60 hover:text-white hover:bg-white/5'}`}
                >
                  일업무현황 ({dailyMemos.length})
                </button>
                <button
                  onClick={() => setActiveTab('complete')}
                  className={`px-4 py-3 text-sm transition-colors ${activeTab === 'complete'
                    ? 'bg-white/10 text-white border-b-2 border-primary-500'
                    : 'text-white/60 hover:text-white hover:bg-white/5'}`}
                >
                  완료정보
                </button>
              </div>

              {/* 탭 콘텐츠 */}
              <div className="flex-1 overflow-y-auto">
                {activeTab === 'history' && (
                  <div className="h-full flex flex-col">
                    <div className="flex bg-white/5 text-xs text-white/60 border-b border-white/10 shrink-0">
                      <div className="w-24 px-3 py-2 border-r border-white/10">날짜</div>
                      <div className="flex-1 px-3 py-2 border-r border-white/10">내용</div>
                      <div className="w-20 px-3 py-2">작성자</div>
                    </div>
                    <div className="flex-1 overflow-y-auto">
                      {history.length === 0 ? (
                        <div className="p-8 text-center text-white/40 text-sm">등록된 내용이 없습니다.</div>
                      ) : (
                        history.map((h, idx) => (
                          <div key={h.idx} className={`flex text-sm border-b border-white/5 ${idx % 2 === 0 ? 'bg-white/[0.02]' : ''} hover:bg-white/5`}>
                            <div className="w-24 px-3 py-2 border-r border-white/10 text-white/50">{formatDate(h.pdate)}</div>
                            <div className="flex-1 px-3 py-2 border-r border-white/10 text-white">{h.remark}</div>
                            <div className="w-20 px-3 py-2 text-white/50">{h.wname}</div>
                          </div>
                        ))
                      )}
                    </div>
                  </div>
                )}

                {activeTab === 'memo' && (
                  <div className="h-full flex flex-col">
                    <div className="flex bg-white/5 text-xs text-white/60 border-b border-white/10 shrink-0">
                      <div className="w-24 px-3 py-2 border-r border-white/10">날짜</div>
                      <div className="flex-1 px-3 py-2 border-r border-white/10">내용</div>
                      <div className="w-20 px-3 py-2">작성자</div>
                    </div>
                    <div className="flex-1 overflow-y-auto">
                      {dailyMemos.length === 0 ? (
                        <div className="p-8 text-center text-white/40 text-sm">등록된 메모가 없습니다.</div>
                      ) : (
                        dailyMemos.map((m, idx) => (
                          <div key={m.idx} className={`flex text-sm border-b border-white/5 ${idx % 2 === 0 ? 'bg-white/[0.02]' : ''} hover:bg-white/5`}>
                            <div className="w-24 px-3 py-2 border-r border-white/10 text-white/50">{formatDate(m.pdate)}</div>
                            <div className="flex-1 px-3 py-2 border-r border-white/10 text-white">{m.remark}</div>
                            <div className="w-20 px-3 py-2 text-white/50">{m.wname}</div>
                          </div>
                        ))
                      )}
                    </div>
                  </div>
                )}

                {activeTab === 'complete' && (
                  <div className="p-4 space-y-4 overflow-y-auto">
                    <div>
                      <label className={labelClass}>배경</label>
                      <textarea rows={3} className={`${inputClass} resize-none`} placeholder="프로젝트 배경..." />
                    </div>
                    <div>
                      <label className={labelClass}>설명</label>
                      <textarea rows={3} className={`${inputClass} resize-none`} placeholder="프로젝트 설명..." />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className={labelClass}>개선 전</label>
                        <textarea rows={3} className={`${inputClass} resize-none`} placeholder="개선 전 상태..." />
                      </div>
                      <div>
                        <label className={labelClass}>개선 후</label>
                        <textarea rows={3} className={`${inputClass} resize-none`} placeholder="개선 후 상태..." />
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className={labelClass}>유형효과</label>
                        <textarea rows={2} className={`${inputClass} resize-none`} placeholder="유형 효과..." />
                      </div>
                      <div>
                        <label className={labelClass}>무형효과</label>
                        <textarea rows={2} className={`${inputClass} resize-none`} placeholder="무형 효과..." />
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* 푸터 */}
        <div className="flex items-center justify-between px-6 py-3 border-t border-white/10 shrink-0 bg-white/5">
          <span className="text-sm text-white/50">PNO: {project.pno || '-'} | Jasmin: {project.jasmin || '-'} | 진행률: {formData.progress}%</span>
          <button
            onClick={onClose}
            className="px-6 py-2 bg-white/10 text-white rounded-lg hover:bg-white/20 transition-colors"
          >
            닫기
          </button>
        </div>
      </div>
    </div>
  );
}
