"use client";

import React, { useState, useMemo } 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 { InspectionReport, RouteItem, Document, DocumentItem } from './types';
import { MOCK_REPORTS, MOCK_ROUTES, MOCK_DOCUMENTS, DEFAULT_DOCUMENTS } from './mockData';

export default function QualityInspectionPage() {
  // 필터 상태
  const [selectedYear, setSelectedYear] = useState(2025);
  const [selectedQuarter, setSelectedQuarter] = useState<string>('전체');
  const [searchTerm, setSearchTerm] = useState('');

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

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

  // 필터링된 리포트 목록
  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 MOCK_ROUTES[selectedReport.id] || [];
  }, [selectedReport]);

  // 선택된 루트의 문서 목록
  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);
  };

  return (
    <div className="w-full h-[calc(100vh-64px)] p-6 bg-slate-100 flex flex-col overflow-hidden">
      <Header />

      <Filters
        selectedYear={selectedYear}
        selectedQuarter={selectedQuarter}
        searchTerm={searchTerm}
        onYearChange={handleYearChange}
        onQuarterChange={handleQuarterChange}
        onSearchChange={handleSearchChange}
      />

      <div className="flex-1 grid grid-cols-12 gap-6 min-h-0">
        {/* Left Panel: Report List */}
        <div className="col-span-12 lg:col-span-3 h-full overflow-hidden">
          <ReportList
            reports={filteredReports}
            selectedId={selectedReport?.id || null}
            onSelect={handleReportSelect}
          />
        </div>

        {/* Middle Panel: Route List */}
        <div className="col-span-12 lg:col-span-4 h-full overflow-hidden">
          <RouteList
            routes={currentRoutes}
            selectedId={selectedRoute?.id || null}
            onSelect={handleRouteSelect}
            reportCode={selectedReport?.code || null}
          />
        </div>

        {/* Right Panel: Documents */}
        <div className="col-span-12 lg:col-span-5 h-full overflow-hidden">
          <DocumentList
            documents={currentDocuments}
            routeCode={selectedRoute?.code || null}
            onViewDocument={handleViewDocument}
          />
        </div>
      </div>

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