"use client";

import React, { useState, useMemo, useCallback } from 'react';
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 { InspectionModalV2 as InspectionModal } from './components/InspectionModalV2';
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 { InspectionReport, RouteItem, Document, DocumentItem, ChecklistCategory } from './types';
import {
  MOCK_REPORTS,
  MOCK_ROUTES_INITIAL,
  MOCK_DOCUMENTS,
  DEFAULT_DOCUMENTS,
  MOCK_DAY1_CATEGORIES,
  MOCK_DAY1_CHECK_ITEMS,
  MOCK_DAY1_STANDARD_DOCUMENTS,
} from './mockData';

// 기본 설정값
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 [day1Categories, setDay1Categories] = useState<ChecklistCategory[]>(MOCK_DAY1_CATEGORIES);
  const [selectedSubItemId, setSelectedSubItemId] = useState<string | null>(null);
  const [selectedCategoryId, setSelectedCategoryId] = useState<string | null>(null);
  const [selectedStandardDocId, setSelectedStandardDocId] = useState<string | null>(null);

  // 2일차(로트추적) 필터 상태
  const [selectedYear, setSelectedYear] = useState(2025);
  const [selectedQuarter, setSelectedQuarter] = useState<string>('전체');
  const [searchTerm, setSearchTerm] = useState('');

  // 2일차 선택 상태
  const [selectedReport, setSelectedReport] = useState<InspectionReport | null>(null);
  const [selectedRoute, setSelectedRoute] = useState<RouteItem | null>(null);

  // 2일차 루트 데이터 상태 (완료 토글용)
  const [routesData, setRoutesData] = useState<Record<string, RouteItem[]>>(MOCK_ROUTES_INITIAL);

  // 모달 상태
  const [modalOpen, setModalOpen] = useState(false);
  const [selectedDoc, setSelectedDoc] = useState<Document | null>(null);
  const [selectedDocItem, setSelectedDocItem] = useState<DocumentItem | null>(null);

  // ===== 1일차 진행률 계산 =====
  const day1Progress = useMemo(() => {
    const total = day1Categories.reduce((sum, cat) => sum + cat.subItems.length, 0);
    const completed = day1Categories.reduce(
      (sum, cat) => sum + cat.subItems.filter(item => item.isCompleted).length,
      0
    );
    return { completed, total };
  }, [day1Categories]);

  // ===== 2일차 진행률 계산 (개소별 완료 기준) =====
  const day2Progress = useMemo(() => {
    let completed = 0;
    let total = 0;
    Object.values(routesData).forEach(routes => {
      routes.forEach(route => {
        route.subItems.forEach(item => {
          total++;
          if (item.isCompleted) completed++;
        });
      });
    });
    return { completed, total };
  }, [routesData]);

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

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

  // ===== 1일차 핸들러 =====
  const handleSubItemSelect = useCallback((categoryId: string, subItemId: string) => {
    setSelectedCategoryId(categoryId);
    setSelectedSubItemId(subItemId);
    setSelectedStandardDocId(null);
  }, []);

  const handleSubItemToggle = useCallback((categoryId: string, subItemId: string, isCompleted: boolean) => {
    setDay1Categories(prev => prev.map(cat => {
      if (cat.id !== categoryId) return cat;
      return {
        ...cat,
        subItems: cat.subItems.map(item => {
          if (item.id !== subItemId) return item;
          return { ...item, isCompleted };
        }),
      };
    }));
  }, []);

  const handleConfirmComplete = useCallback(() => {
    if (selectedCategoryId && selectedSubItemId) {
      handleSubItemToggle(selectedCategoryId, selectedSubItemId, true);
    }
  }, [selectedCategoryId, selectedSubItemId, handleSubItemToggle]);

  // 선택된 1일차 점검 항목
  const selectedCheckItem = useMemo(() => {
    if (!selectedSubItemId) return null;
    return MOCK_DAY1_CHECK_ITEMS.find(item => item.subItemId === selectedSubItemId) || null;
  }, [selectedSubItemId]);

  // 선택된 표준 문서
  const selectedStandardDoc = useMemo(() => {
    if (!selectedStandardDocId || !selectedSubItemId) return null;
    const docs = MOCK_DAY1_STANDARD_DOCUMENTS[selectedSubItemId] || [];
    return docs.find(doc => doc.id === selectedStandardDocId) || null;
  }, [selectedStandardDocId, selectedSubItemId]);

  // 선택된 항목의 완료 여부
  const isSelectedItemCompleted = useMemo(() => {
    if (!selectedSubItemId) return false;
    for (const cat of day1Categories) {
      const item = cat.subItems.find(item => item.id === selectedSubItemId);
      if (item) return item.isCompleted;
    }
    return false;
  }, [day1Categories, selectedSubItemId]);

  // ===== 2일차(로트추적) 로직 =====
  const filteredReports = useMemo(() => {
    return MOCK_REPORTS.filter((report) => {
      if (report.year !== selectedYear) return false;
      if (selectedQuarter !== '전체') {
        const quarterNum = parseInt(selectedQuarter.replace('분기', ''));
        if (report.quarterNum !== quarterNum) return false;
      }
      if (searchTerm) {
        const term = searchTerm.toLowerCase();
        const matchesCode = report.code.toLowerCase().includes(term);
        const matchesSite = report.siteName.toLowerCase().includes(term);
        const matchesItem = report.item.toLowerCase().includes(term);
        if (!matchesCode && !matchesSite && !matchesItem) return false;
      }
      return true;
    });
  }, [selectedYear, selectedQuarter, searchTerm]);

  const currentRoutes = useMemo(() => {
    if (!selectedReport) return [];
    return routesData[selectedReport.id] || [];
  }, [selectedReport, routesData]);

  const currentDocuments = useMemo(() => {
    if (!selectedRoute) return DEFAULT_DOCUMENTS;
    return MOCK_DOCUMENTS[selectedRoute.id] || DEFAULT_DOCUMENTS;
  }, [selectedRoute]);

  const handleReportSelect = (report: InspectionReport) => {
    setSelectedReport(report);
    setSelectedRoute(null);
  };

  const handleRouteSelect = (route: RouteItem) => {
    setSelectedRoute(route);
  };

  const handleViewDocument = (doc: Document, item?: DocumentItem) => {
    setSelectedDoc(doc);
    setSelectedDocItem(item || null);
    setModalOpen(true);
  };

  const handleYearChange = (year: number) => {
    setSelectedYear(year);
    setSelectedReport(null);
    setSelectedRoute(null);
  };

  const handleQuarterChange = (quarter: string) => {
    setSelectedQuarter(quarter);
    setSelectedReport(null);
    setSelectedRoute(null);
  };

  const handleSearchChange = (term: string) => {
    setSearchTerm(term);
  };

  // ===== 2일차 개소별 완료 토글 =====
  const handleToggleItem = useCallback((routeId: string, itemId: string, isCompleted: boolean) => {
    setRoutesData(prev => {
      const newData = { ...prev };
      for (const reportId of Object.keys(newData)) {
        newData[reportId] = newData[reportId].map(route => {
          if (route.id !== routeId) return route;
          return {
            ...route,
            subItems: route.subItems.map(item => {
              if (item.id !== itemId) return item;
              return { ...item, isCompleted };
            }),
          };
        });
      }
      return newData;
    });
  }, []);

  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-hidden">
      {/* 헤더 (설정 버튼 포함) */}
      <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-3 px-4 rounded-lg border-2 font-medium transition-all ${
              activeDay === 1
                ? 'bg-blue-600 border-blue-600 text-white'
                : 'bg-white border-gray-200 text-gray-700 hover:border-blue-300'
            }`}
          >
            1일차: 기준/매뉴얼 심사
          </button>
          <button
            type="button"
            onClick={() => setActiveDay(2)}
            className={`flex-1 py-3 px-4 rounded-lg border-2 font-medium transition-all ${
              activeDay === 2
                ? 'bg-blue-600 border-blue-600 text-white'
                : 'bg-white border-gray-200 text-gray-700 hover:border-blue-300'
            }`}
          >
            2일차: 로트추적 심사
          </button>
        </div>
      )}

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

      {activeDay === 1 ? (
        // ===== 1일차: 기준/매뉴얼 심사 =====
        <div className="flex-1 grid grid-cols-12 gap-3 sm:gap-4 lg:min-h-0">
          {/* 좌측: 점검표 항목 */}
          <div className={`col-span-12 min-h-[250px] sm:min-h-[300px] lg:min-h-0 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}
            />
          </div>

          {/* 중앙: 기준 문서화 */}
          {displaySettings.showDocumentSection && (
            <div className={`col-span-12 min-h-[200px] sm:min-h-[250px] lg:min-h-0 lg:h-full overflow-auto ${
              displaySettings.showDocumentViewer ? 'lg:col-span-4' : 'lg:col-span-8'
            }`}>
              <Day1DocumentSection
                checkItem={selectedCheckItem}
                selectedDocumentId={selectedStandardDocId}
                onDocumentSelect={setSelectedStandardDocId}
                onConfirmComplete={handleConfirmComplete}
                isCompleted={isSelectedItemCompleted}
              />
            </div>
          )}

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

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

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

      {/* 설정 패널 */}
      <AuditSettingsPanel
        isOpen={settingsOpen}
        onClose={() => setSettingsOpen(false)}
        settings={displaySettings}
        onSettingsChange={setDisplaySettings}
      />

      <InspectionModal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        document={selectedDoc}
        documentItem={selectedDocItem}
      />
    </div>
  );
}
