'use client';

import { useState, useCallback, useMemo, useEffect } from 'react';
import { toast } from 'sonner';
import type { InspectionReport, RouteItem, Document, DocumentItem } from '../types';
import {
  getQualityReports,
  getReportRoutes,
  getRouteDocuments,
  confirmUnitInspection,
} from '../actions';

const USE_MOCK = false;

export function useDay2LotAudit() {
  // 필터 상태
  const [selectedYear, setSelectedYear] = useState(2026);
  const [selectedQuarter, setSelectedQuarter] = useState<'Q1' | 'Q2' | 'Q3' | 'Q4' | '전체'>('전체');
  const [searchTerm, setSearchTerm] = useState('');

  // 데이터 상태
  const [reports, setReports] = useState<InspectionReport[]>([]);
  const [routesData, setRoutesData] = useState<Record<string, RouteItem[]>>({});
  const [documents, setDocuments] = useState<Document[]>([]);

  // 선택 상태
  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 [loadingReports, setLoadingReports] = useState(false);
  const [loadingRoutes, setLoadingRoutes] = useState(false);
  const [loadingDocuments, setLoadingDocuments] = useState(false);
  const [pendingConfirmIds, setPendingConfirmIds] = useState<Set<string>>(new Set());

  // 마운트 시 + 필터 변경 시 보고서 자동 로드
  useEffect(() => {
    if (USE_MOCK) return;

    const loadReports = async () => {
      setLoadingReports(true);
      try {
        const quarterNum = selectedQuarter !== '전체'
          ? parseInt(selectedQuarter.replace('Q', ''))
          : undefined;
        const result = await getQualityReports({
          year: selectedYear,
          quarter: quarterNum,
          q: searchTerm || undefined,
        });
        if (result.success && result.data) {
          setReports(result.data);
        }
      } finally {
        setLoadingReports(false);
      }
    };

    loadReports();
  }, [selectedYear, selectedQuarter, searchTerm]);

  // 진행률 계산
  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]);

  // 필터링된 보고서 (API에서 이미 필터링되므로 그대로 반환)
  const filteredReports = useMemo(() => {
    return reports;
  }, [reports]);

  // 현재 루트/문서
  const currentRoutes = useMemo(() => {
    if (!selectedReport) return [];
    return routesData[selectedReport.id] || [];
  }, [selectedReport, routesData]);

  const currentDocuments = useMemo(() => {
    return documents;
  }, [documents]);

  // === API 호출 핸들러 ===

  const handleReportSelect = useCallback(async (report: InspectionReport) => {
    setSelectedReport(report);
    setSelectedRoute(null);
    setDocuments([]);

    setLoadingRoutes(true);
    try {
      const result = await getReportRoutes(report.id);
      if (result.success && result.data) {
        setRoutesData((prev) => ({ ...prev, [report.id]: result.data! }));
      }
    } finally {
      setLoadingRoutes(false);
    }
  }, []);

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

    setLoadingDocuments(true);
    try {
      const result = await getRouteDocuments(route.id);
      if (result.success && result.data) {
        setDocuments(result.data);
      }
    } finally {
      setLoadingDocuments(false);
    }
  }, []);

  const handleViewDocument = useCallback((doc: Document, item?: DocumentItem) => {
    // 품질관리서는 파일 다운로드로 처리 (DocumentList에서 직접 처리하므로 모달 열지 않음)
    if (doc.type === 'quality') return;

    setSelectedDoc(doc);
    setSelectedDocItem(item || null);
    setModalOpen(true);
  }, []);

  const handleToggleItem = useCallback(async (routeId: string, itemId: string, isCompleted: boolean) => {
    // API: 비관적 업데이트
    if (pendingConfirmIds.has(itemId)) return;
    setPendingConfirmIds((prev) => new Set(prev).add(itemId));

    try {
      const result = await confirmUnitInspection(itemId, isCompleted);
      if (result.success && result.data) {
        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: result.data!.isCompleted };
                }),
              };
            });
          }
          return newData;
        });
      } else {
        toast.error(result.error || '확인 상태 변경에 실패했습니다.');
      }
    } finally {
      setPendingConfirmIds((prev) => {
        const next = new Set(prev);
        next.delete(itemId);
        return next;
      });
    }
  }, [pendingConfirmIds]);

  // 품질관리서 파일 정보 업데이트 (업로드 성공 후 documents 상태 반영)
  // 품질관리서는 doc.id가 'quality' 문자열이므로 type으로 매칭
  const updateQualityDocumentFile = useCallback((_docId: string, fileInfo: { fileId: number; fileName: string; fileSize: number }) => {
    setDocuments((prev) =>
      prev.map((doc) =>
        doc.type === 'quality'
          ? { ...doc, fileId: fileInfo.fileId, fileName: fileInfo.fileName, fileSize: fileInfo.fileSize }
          : doc
      )
    );
  }, []);

  const handleYearChange = useCallback((year: number) => {
    setSelectedYear(year);
    setSelectedReport(null);
    setSelectedRoute(null);
    setDocuments([]);
  }, []);

  const handleQuarterChange = useCallback((quarter: 'Q1' | 'Q2' | 'Q3' | 'Q4' | '전체') => {
    setSelectedQuarter(quarter);
    setSelectedReport(null);
    setSelectedRoute(null);
    setDocuments([]);
  }, []);

  const handleSearchChange = useCallback((term: string) => {
    setSearchTerm(term);
  }, []);

  return {
    // 필터
    selectedYear,
    selectedQuarter,
    searchTerm,
    handleYearChange,
    handleQuarterChange,
    handleSearchChange,

    // 데이터
    filteredReports,
    currentRoutes,
    currentDocuments,
    day2Progress,

    // 선택
    selectedReport,
    selectedRoute,
    handleReportSelect,
    handleRouteSelect,

    // 모달
    modalOpen,
    selectedDoc,
    selectedDocItem,
    handleViewDocument,
    setModalOpen,

    // 토글
    handleToggleItem,
    pendingConfirmIds,

    // 품질관리서 파일
    updateQualityDocumentFile,

    // 로딩
    loadingReports,
    loadingRoutes,
    loadingDocuments,

    // Mock 여부
    isMock: USE_MOCK,
  };
}
