"use client";

import React, { useState, useMemo, useCallback, useEffect } from 'react';
import { toast } from 'sonner';
import { Header } from './components/Header';
import { Filters } from './components/Filters';
import { ReportList } from './components/ReportList';
import { RouteList } from './components/RouteList';
import { DocumentList } from './components/DocumentList';
import { InspectionModal } from './components/InspectionModal';
import { InspectionReportModal, WorkLogModal } from '@/components/document-system/modals';
import { ProductInspectionViewModal } from '@/components/quality/InspectionManagement/ProductInspectionViewModal';
import { getDocumentDetail } from './actions';
import { DayTabs } from './components/DayTabs';
import { Day1ChecklistPanel } from './components/Day1ChecklistPanel';
import { Day1DocumentSection } from './components/Day1DocumentSection';
import { Day1DocumentViewer } from './components/Day1DocumentViewer';
import { AuditSettingsPanel, SettingsButton, type AuditDisplaySettings } from './components/AuditSettingsPanel';
import { useDay1Audit } from './hooks/useDay1Audit';
import { useDay2LotAudit } from './hooks/useDay2LotAudit';
import { useChecklistTemplate } from './hooks/useChecklistTemplate';
import { uploadTemplateDocument, getTemplateDocuments, deleteTemplateDocument, uploadQualityDocumentFile } from './actions';
import type { TemplateDocument } from './types';

// 기본 설정값
const DEFAULT_SETTINGS: AuditDisplaySettings = {
  showProgressBar: true,
  showDocumentViewer: true,
  showDocumentSection: true,
  showCompletedItems: true,
  expandAllCategories: true,
};

export default function QualityInspectionPage() {
  // 탭 상태
  const [activeDay, setActiveDay] = useState<1 | 2>(1);

  // 설정 상태
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [displaySettings, setDisplaySettings] = useState<AuditDisplaySettings>(DEFAULT_SETTINGS);

  // 1일차 커스텀 훅
  const {
    templateId,
    categories,
    day1Progress,
    selectedCheckItem,
    isSelectedItemCompleted,
    selectedSubItemId,
    handleSubItemSelect,
    handleSubItemToggle,
    handleConfirmComplete,
    isMock: day1IsMock,
  } = useDay1Audit();

  // 점검표 템플릿 관리 훅 (설정 모달용)
  const checklistTemplate = useChecklistTemplate();

  // 업로드된 파일 상태 (subItemId별)
  const [uploadedFiles, setUploadedFiles] = useState<Record<string, TemplateDocument[]>>({});
  const [selectedUploadedFile, setSelectedUploadedFile] = useState<TemplateDocument | null>(null);

  // 선택된 항목 변경 시 파일 목록 로드 + 업로드 파일 선택 초기화
  useEffect(() => {
    setSelectedUploadedFile(null);
    if (!selectedSubItemId || !templateId) return;
    if (uploadedFiles[selectedSubItemId]) return; // 이미 로드됨

    getTemplateDocuments(templateId, selectedSubItemId).then((result) => {
      if (result.success && result.data) {
        setUploadedFiles((prev) => ({ ...prev, [selectedSubItemId]: result.data! }));
      }
    });
  }, [selectedSubItemId, templateId]);

  // 파일 업로드 핸들러
  const handleFileUpload = useCallback(async (subItemId: string, file: File): Promise<boolean> => {
    if (!templateId) {
      toast.error('점검표 템플릿이 로드되지 않았습니다.');
      return false;
    }
    const result = await uploadTemplateDocument(templateId, subItemId, file);
    if (!result.success) {
      toast.error(result.error || '파일 업로드에 실패했습니다.');
      return false;
    }
    // 업로드 성공 시 파일 목록에 추가
    if (result.data) {
      setUploadedFiles((prev) => ({
        ...prev,
        [subItemId]: [result.data!, ...(prev[subItemId] || [])],
      }));
    }
    return true;
  }, [templateId]);

  // 파일 삭제 핸들러
  const handleFileDelete = useCallback(async (fileId: number, subItemId: string) => {
    const result = await deleteTemplateDocument(fileId);
    if (result.success) {
      setUploadedFiles((prev) => ({
        ...prev,
        [subItemId]: (prev[subItemId] || []).filter((f) => f.id !== fileId),
      }));
      toast.success('파일이 삭제되었습니다.');
    } else {
      toast.error(result.error || '파일 삭제에 실패했습니다.');
    }
  }, []);

  // 2일차 커스텀 훅
  const {
    selectedYear,
    selectedQuarter,
    searchTerm,
    handleYearChange,
    handleQuarterChange,
    handleSearchChange,
    filteredReports,
    currentRoutes,
    currentDocuments,
    day2Progress,
    selectedReport,
    selectedRoute,
    handleReportSelect,
    handleRouteSelect,
    modalOpen,
    selectedDoc,
    selectedDocItem,
    handleViewDocument,
    setModalOpen,
    handleToggleItem,
    updateQualityDocumentFile,
    isMock: day2IsMock,
  } = useDay2LotAudit();

  // 품질관리서 파일 업로드 핸들러 (2일차 DocumentList용)
  const handleQualityFileUpload = useCallback(async (qualityDocumentId: string, file: File): Promise<boolean> => {
    const result = await uploadQualityDocumentFile(qualityDocumentId, file);
    if (!result.success) {
      toast.error(result.error || '품질관리서 파일 업로드에 실패했습니다.');
      return false;
    }
    // 업로드 성공 시 documents 상태에서 해당 문서의 파일 정보 업데이트
    if (result.data) {
      updateQualityDocumentFile(qualityDocumentId, result.data);
    }
    return true;
  }, [updateQualityDocumentFile]);

  // 1일차 필터링된 카테고리 (완료 항목 숨기기 옵션)
  const filteredDay1Categories = useMemo(() => {
    if (displaySettings.showCompletedItems) return categories;

    return categories.map(category => ({
      ...category,
      subItems: category.subItems.filter(item => !item.isCompleted),
    })).filter(category => category.subItems.length > 0);
  }, [categories, displaySettings.showCompletedItems]);

  return (
    <div className="w-full min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] p-3 sm:p-4 md:p-5 lg:p-6 bg-slate-100 flex flex-col lg:overflow-auto">
      {/* 헤더 (설정 버튼 포함) */}
      <Header
        rightContent={<SettingsButton onClick={() => setSettingsOpen(true)} />}
      />

      {/* 1일차/2일차 탭 + 진행률 */}
      {displaySettings.showProgressBar ? (
        <DayTabs
          activeDay={activeDay}
          onDayChange={setActiveDay}
          day1Progress={day1Progress}
          day2Progress={day2Progress}
        />
      ) : (
        // 진행률 숨김 시 탭만 표시
        <div className="flex gap-3 mb-4">
          <button
            type="button"
            onClick={() => setActiveDay(1)}
            className={`flex-1 py-1.5 sm:py-2 px-2 sm:px-3 rounded-lg border-2 font-medium text-xs sm:text-sm transition-all ${
              activeDay === 1
                ? 'bg-blue-600 border-blue-600 text-white'
                : 'bg-white border-gray-200 text-gray-700 hover:border-blue-300'
            }`}
          >
            기준/매뉴얼 심사 심사
          </button>
          <button
            type="button"
            onClick={() => setActiveDay(2)}
            className={`flex-1 py-1.5 sm:py-2 px-2 sm:px-3 rounded-lg border-2 font-medium text-xs sm:text-sm transition-all ${
              activeDay === 2
                ? 'bg-blue-600 border-blue-600 text-white'
                : 'bg-white border-gray-200 text-gray-700 hover:border-blue-300'
            }`}
          >
            로트 추적 심사 심사
          </button>
        </div>
      )}

      {/* 공통 필터 (1일차/2일차 모두 사용) */}
      <Filters
        selectedYear={selectedYear}
        selectedQuarter={selectedQuarter}
        searchTerm={searchTerm}
        onYearChange={handleYearChange}
        onQuarterChange={handleQuarterChange}
        onSearchChange={handleSearchChange}
      />

      {activeDay === 1 ? (
        // ===== 기준/매뉴얼 심사 심사 =====
        <div className="flex-1 grid grid-cols-12 gap-3 sm:gap-4 lg:min-h-[500px]">
          {/* 좌측: 점검표 항목 */}
          <div className={`col-span-12 min-h-[250px] sm:min-h-[300px] lg:min-h-[500px] lg:h-full overflow-auto ${
            displaySettings.showDocumentSection && displaySettings.showDocumentViewer
              ? 'lg:col-span-3'
              : displaySettings.showDocumentSection || displaySettings.showDocumentViewer
                ? 'lg:col-span-4'
                : 'lg:col-span-12'
          }`}>
            <Day1ChecklistPanel
              categories={filteredDay1Categories}
              selectedSubItemId={selectedSubItemId}
              searchTerm={searchTerm}
              onSubItemSelect={handleSubItemSelect}
              onSubItemToggle={handleSubItemToggle}
              isMock={day1IsMock}
            />
          </div>

          {/* 중앙: 기준 문서화 */}
          {displaySettings.showDocumentSection && (
            <div className={`col-span-12 min-h-[200px] sm:min-h-[250px] lg:min-h-[500px] lg:h-full overflow-auto ${
              displaySettings.showDocumentViewer ? 'lg:col-span-4' : 'lg:col-span-8'
            }`}>
              <Day1DocumentSection
                checkItem={selectedCheckItem}
                onConfirmComplete={handleConfirmComplete}
                isCompleted={isSelectedItemCompleted}
                isMock={day1IsMock}
                onFileUpload={handleFileUpload}
                uploadedFiles={selectedSubItemId ? uploadedFiles[selectedSubItemId] || [] : []}
                onFileDelete={selectedSubItemId ? (fileId) => handleFileDelete(fileId, selectedSubItemId) : undefined}
                onFileSelect={(file) => {
                  setSelectedUploadedFile(file);
                }}
                selectedFileId={selectedUploadedFile?.id ?? null}
              />
            </div>
          )}

          {/* 우측: 문서 뷰어 */}
          {displaySettings.showDocumentViewer && (
            <div className={`col-span-12 min-h-[200px] sm:min-h-[250px] lg:min-h-[500px] lg:h-full overflow-auto ${
              displaySettings.showDocumentSection ? 'lg:col-span-5' : 'lg:col-span-8'
            }`}>
              <Day1DocumentViewer document={null} uploadedFile={selectedUploadedFile} isMock={day1IsMock} />
            </div>
          )}
        </div>
      ) : (
        // ===== 로트 추적 심사 =====
        <div className="flex-1 grid grid-cols-12 gap-3 sm:gap-4 lg:gap-6 lg:min-h-[500px]">
            <div className="col-span-12 lg:col-span-4 min-h-[250px] sm:min-h-[300px] lg:min-h-[500px] lg:h-full overflow-auto">
              <ReportList
                reports={filteredReports}
                selectedId={selectedReport?.id || null}
                onSelect={handleReportSelect}
                isMock={day2IsMock}
              />
            </div>

            <div className="col-span-12 lg:col-span-4 min-h-[200px] sm:min-h-[250px] lg:min-h-[500px] lg:h-full overflow-auto">
              <RouteList
                routes={currentRoutes}
                selectedId={selectedRoute?.id || null}
                onSelect={handleRouteSelect}
                onToggleItem={handleToggleItem}
                reportCode={selectedReport?.code || null}
                isMock={day2IsMock}
              />
            </div>

            <div className="col-span-12 lg:col-span-4 min-h-[200px] sm:min-h-[250px] lg:min-h-[500px] lg:h-full overflow-auto">
              <DocumentList
                documents={currentDocuments}
                routeCode={selectedRoute?.code || null}
                onViewDocument={handleViewDocument}
                onQualityFileUpload={handleQualityFileUpload}
                isMock={day2IsMock}
              />
            </div>
          </div>
      )}

      {/* 설정 패널 */}
      <AuditSettingsPanel
        isOpen={settingsOpen}
        onClose={() => setSettingsOpen(false)}
        settings={displaySettings}
        onSettingsChange={setDisplaySettings}
        checklistManagement={{
          categories: checklistTemplate.editCategories,
          hasChanges: checklistTemplate.hasChanges,
          saving: checklistTemplate.saving,
          loading: checklistTemplate.loading,
          error: checklistTemplate.error,
          onAddCategory: checklistTemplate.addCategory,
          onUpdateCategoryTitle: checklistTemplate.updateCategoryTitle,
          onDeleteCategory: checklistTemplate.deleteCategory,
          onMoveCategoryUp: checklistTemplate.moveCategoryUp,
          onMoveCategoryDown: checklistTemplate.moveCategoryDown,
          onAddSubItem: checklistTemplate.addSubItem,
          onUpdateSubItemName: checklistTemplate.updateSubItemName,
          onDeleteSubItem: checklistTemplate.deleteSubItem,
          onMoveSubItemUp: checklistTemplate.moveSubItemUp,
          onMoveSubItemDown: checklistTemplate.moveSubItemDown,
          onSave: checklistTemplate.saveTemplate,
          onReset: checklistTemplate.resetToSaved,
        }}
      />

      {/* 중간검사 성적서 → 기존 독립 모달 재사용 */}
      {selectedDoc?.type === 'report' && (
        <InspectionReportModal
          open={modalOpen}
          onOpenChange={(open) => !open && setModalOpen(false)}
          workOrderId={selectedDocItem?.workOrderId ? String(selectedDocItem.workOrderId) : selectedDocItem?.id || null}
          processType={
            selectedDocItem?.subType === 'jointbar' ? 'slat'
              : (selectedDocItem?.subType as 'screen' | 'slat' | 'bending') || 'screen'
          }
          readOnly
          isJointBar={selectedDocItem?.subType === 'jointbar'}
        />
      )}

      {/* 작업일지 → 독립 WorkLogModal */}
      {selectedDoc?.type === 'log' && (
        <WorkLogModal
          open={modalOpen}
          onOpenChange={(open) => !open && setModalOpen(false)}
          workOrderId={selectedDocItem?.workOrderId ? String(selectedDocItem.workOrderId) : selectedDocItem?.id || null}
          processType={(selectedDocItem?.subType as 'screen' | 'slat' | 'bending') || 'screen'}
        />
      )}

      {/* 제품검사 성적서 → 독립 ProductInspectionViewModal */}
      {selectedDoc?.type === 'product' && (
        <ProductInspectionViewModal
          open={modalOpen}
          onOpenChange={(open) => !open && setModalOpen(false)}
          locationId={selectedDocItem?.id || null}
          fetchDetail={getDocumentDetail}
        />
      )}

      {/* 나머지 문서 타입 (수입검사, 수주서, 납품확인서, 출고증) → 기존 InspectionModal */}
      {selectedDoc && !['report', 'log', 'product', 'quality'].includes(selectedDoc.type) && (
        <InspectionModal
          isOpen={modalOpen}
          onClose={() => setModalOpen(false)}
          document={selectedDoc}
          documentItem={selectedDocItem}
          readOnly
        />
      )}
    </div>
  );
}
