'use client';

import React from 'react';
import { FileText, Download, Printer, ZoomIn, ZoomOut, Maximize2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { StandardDocument, TemplateDocument } from '../types';

interface Day1DocumentViewerProps {
  document: StandardDocument | null;
  uploadedFile?: TemplateDocument | null;
  isMock?: boolean;
}

export function Day1DocumentViewer({ document, uploadedFile, isMock }: Day1DocumentViewerProps) {
  // 업로드된 파일이 선택된 경우
  if (uploadedFile) {
    const isPdf = uploadedFile.mimeType === 'application/pdf';
    const viewUrl = `/api/proxy/files/${uploadedFile.id}/view`;
    const downloadUrl = `/api/proxy/files/${uploadedFile.id}/download`;

    // Google Docs Viewer용 공개 URL 생성 (개발/운영 서버에서만 동작)
    const isLocalhost = typeof window !== 'undefined' && (
      window.location.hostname === 'localhost' ||
      window.location.hostname.endsWith('.sam.kr')
    );
    const publicFileUrl = typeof window !== 'undefined'
      ? `${window.location.origin}${viewUrl}`
      : '';
    const googleViewerUrl = `https://docs.google.com/gview?url=${encodeURIComponent(publicFileUrl)}&embedded=true`;

    const isOfficeDoc = [
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    ].includes(uploadedFile.mimeType);

    return (
      <div className="bg-white rounded-lg border border-gray-200 overflow-hidden h-full flex flex-col">
        {/* 헤더 */}
        <div className="bg-gray-100 px-2 sm:px-4 py-2 sm:py-3 border-b border-gray-200 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <div className={`w-6 h-6 sm:w-8 sm:h-8 rounded flex items-center justify-center ${
              isPdf ? 'bg-red-100 text-red-600' : 'bg-green-100 text-green-600'
            }`}>
              <FileText className="h-3 w-3 sm:h-4 sm:w-4" />
            </div>
            <div>
              <h3 className="font-medium text-gray-900 text-xs sm:text-sm truncate max-w-[200px]">
                {uploadedFile.displayName}
              </h3>
              <p className="text-[10px] sm:text-xs text-gray-500">
                {(uploadedFile.fileSize / (1024 * 1024)).toFixed(1)} MB
              </p>
            </div>
          </div>
          <div className="flex items-center gap-1">
            <a
              href={viewUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="p-1.5 sm:p-2 rounded hover:bg-gray-200 text-gray-500 hover:text-gray-700 transition-colors"
              title="새 탭에서 보기"
            >
              <Maximize2 className="h-3.5 w-3.5 sm:h-4 sm:w-4" />
            </a>
            <a
              href={downloadUrl}
              className="p-1.5 sm:p-2 rounded hover:bg-gray-200 text-gray-500 hover:text-gray-700 transition-colors"
              title="다운로드"
            >
              <Download className="h-3.5 w-3.5 sm:h-4 sm:w-4" />
            </a>
          </div>
        </div>

        {/* 문서 미리보기 */}
        <div className="flex-1 bg-gray-200 overflow-auto">
          {isPdf ? (
            <iframe
              src={viewUrl}
              className="w-full h-full border-0"
              title={uploadedFile.displayName}
            />
          ) : isOfficeDoc && !isLocalhost ? (
            <iframe
              src={googleViewerUrl}
              className="w-full h-full border-0"
              title={uploadedFile.displayName}
            />
          ) : (
            <div className="flex items-center justify-center h-full text-gray-400">
              <div className="text-center">
                <FileText className="h-12 w-12 mx-auto mb-3 opacity-50" />
                <p className="text-sm">
                  {isOfficeDoc && isLocalhost
                    ? '로컬 환경에서는 Office 문서 미리보기가 지원되지 않습니다'
                    : '미리보기를 지원하지 않는 파일 형식입니다'}
                </p>
                <a
                  href={downloadUrl}
                  className="inline-block mt-2 text-xs text-blue-600 hover:text-blue-800 underline"
                >
                  다운로드하여 확인
                </a>
              </div>
            </div>
          )}
        </div>

        {/* 푸터 */}
        <div className="bg-gray-100 px-2 sm:px-4 py-1.5 sm:py-2 border-t border-gray-200">
          <span className="text-[10px] sm:text-xs text-gray-500 truncate">
            {uploadedFile.displayName}
          </span>
        </div>
      </div>
    );
  }
  if (!document) {
    return (
      <div className="bg-white rounded-lg border border-gray-200 h-full flex items-center justify-center">
        <div className="text-center text-gray-400 py-12">
          <FileText className="h-12 w-12 mx-auto mb-3 opacity-50" />
          <p className="text-sm">문서를 선택하면 미리보기가 표시됩니다</p>
        </div>
      </div>
    );
  }

  const isPdf = document.fileName?.endsWith('.pdf');
  const isExcel = document.fileName?.endsWith('.xlsx') || document.fileName?.endsWith('.xls');

  return (
    <div className="bg-white rounded-lg border border-gray-200 overflow-hidden h-full flex flex-col">
      {/* 헤더 */}
      <div className="bg-gray-100 px-2 sm:px-4 py-2 sm:py-3 border-b border-gray-200 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <div className={cn(
            'w-6 h-6 sm:w-8 sm:h-8 rounded flex items-center justify-center',
            isPdf ? 'bg-red-100 text-red-600' :
            isExcel ? 'bg-green-100 text-green-600' :
            'bg-gray-200 text-gray-600'
          )}>
            <FileText className="h-3 w-3 sm:h-4 sm:w-4" />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <h3 className="font-medium text-gray-900 text-xs sm:text-sm">{document.title}</h3>
              {isMock && (
                <span className="bg-amber-100 text-amber-700 text-[9px] font-semibold px-1.5 py-0.5 rounded border border-amber-200">
                  Mock
                </span>
              )}
            </div>
            <p className="text-[10px] sm:text-xs text-gray-500">
              {document.version !== '-' && <span className="mr-2">{document.version}</span>}
              {document.date}
            </p>
          </div>
        </div>

        {/* 툴바 */}
        <div className="flex items-center gap-0.5 sm:gap-1">
          <button
            type="button"
            className="p-1.5 sm:p-2 rounded hover:bg-gray-200 text-gray-500 hover:text-gray-700 transition-colors"
            title="축소"
          >
            <ZoomOut className="h-3.5 w-3.5 sm:h-4 sm:w-4" />
          </button>
          <button
            type="button"
            className="p-1.5 sm:p-2 rounded hover:bg-gray-200 text-gray-500 hover:text-gray-700 transition-colors"
            title="확대"
          >
            <ZoomIn className="h-3.5 w-3.5 sm:h-4 sm:w-4" />
          </button>
          <button
            type="button"
            className="hidden sm:block p-2 rounded hover:bg-gray-200 text-gray-500 hover:text-gray-700 transition-colors"
            title="전체화면"
          >
            <Maximize2 className="h-4 w-4" />
          </button>
          <div className="hidden sm:block w-px h-6 bg-gray-300 mx-1" />
          <button
            type="button"
            className="hidden sm:block p-2 rounded hover:bg-gray-200 text-gray-500 hover:text-gray-700 transition-colors"
            title="인쇄"
          >
            <Printer className="h-4 w-4" />
          </button>
          <button
            type="button"
            className="p-1.5 sm:p-2 rounded hover:bg-gray-200 text-gray-500 hover:text-gray-700 transition-colors"
            title="다운로드"
          >
            <Download className="h-3.5 w-3.5 sm:h-4 sm:w-4" />
          </button>
        </div>
      </div>

      {/* 문서 미리보기 영역 */}
      <div className="flex-1 bg-gray-200 p-2 sm:p-4 overflow-auto">
        <div className="bg-white rounded shadow-lg max-w-3xl mx-auto min-h-[400px] sm:min-h-[600px]">
          {/* Mock 문서 내용 */}
          <DocumentPreviewContent document={document} />
        </div>
      </div>

      {/* 푸터 */}
      <div className="bg-gray-100 px-2 sm:px-4 py-1.5 sm:py-2 border-t border-gray-200 flex items-center justify-between">
        <span className="text-[10px] sm:text-xs text-gray-500 truncate max-w-[60%]">
          파일명: {document.fileName || '-'}
        </span>
        <span className="text-[10px] sm:text-xs text-gray-500">
          1 / 1 페이지
        </span>
      </div>
    </div>
  );
}

// Mock 문서 미리보기 내용
function DocumentPreviewContent({ document }: { document: StandardDocument }) {
  return (
    <div className="p-8">
      {/* 문서 헤더 */}
      <div className="text-center border-b-2 border-gray-800 pb-4 mb-6">
        <h1 className="text-xl font-bold text-gray-900">{document.title}</h1>
        <div className="flex justify-center gap-6 mt-2 text-sm text-gray-600">
          <span>문서번호: QM-{document.id}</span>
          <span>개정: {document.version}</span>
          <span>시행일: {document.date}</span>
        </div>
      </div>

      {/* Mock 문서 내용 */}
      <div className="space-y-4 text-sm text-gray-700">
        <section>
          <h2 className="font-bold text-gray-900 mb-2">1. 목적</h2>
          <p className="pl-4">
            본 문서는 {document.title}의 업무 절차 및 기준을 규정함으로써
            품질관리 업무의 효율성과 일관성을 확보하는 것을 목적으로 한다.
          </p>
        </section>

        <section>
          <h2 className="font-bold text-gray-900 mb-2">2. 적용범위</h2>
          <p className="pl-4">
            본 기준서는 당사에서 생산하는 모든 제품의 품질관리 업무에 적용한다.
          </p>
        </section>

        <section>
          <h2 className="font-bold text-gray-900 mb-2">3. 용어의 정의</h2>
          <div className="pl-4 space-y-1">
            <p>3.1 검사: 품질특성을 측정, 시험하여 규정된 기준과 비교하는 활동</p>
            <p>3.2 적합: 규정된 요구사항이 충족된 상태</p>
            <p>3.3 부적합: 규정된 요구사항이 충족되지 않은 상태</p>
          </div>
        </section>

        <section>
          <h2 className="font-bold text-gray-900 mb-2">4. 업무 절차</h2>
          <div className="pl-4 space-y-2">
            <p>4.1 담당자는 본 기준서에 따라 업무를 수행한다.</p>
            <p>4.2 검사 결과는 해당 기록 양식에 기록하고 보관한다.</p>
            <p>4.3 부적합 발생 시 부적합품 관리 절차에 따라 처리한다.</p>
          </div>
        </section>

        {/* 문서 서명란 */}
        <div className="mt-12 pt-6 border-t border-gray-300">
          <div className="grid grid-cols-3 gap-4 text-center text-sm">
            <div className="border border-gray-300 p-3">
              <div className="text-gray-500 mb-2">작성</div>
              <div className="h-12 flex items-center justify-center text-gray-400">
                (서명)
              </div>
            </div>
            <div className="border border-gray-300 p-3">
              <div className="text-gray-500 mb-2">검토</div>
              <div className="h-12 flex items-center justify-center text-gray-400">
                (서명)
              </div>
            </div>
            <div className="border border-gray-300 p-3">
              <div className="text-gray-500 mb-2">승인</div>
              <div className="h-12 flex items-center justify-center text-gray-400">
                (서명)
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}