'use client';

import { useMemo, useEffect, useState, useRef, useCallback } from 'react';
import type { CEODashboardData, DashboardSettings, SectionKey } from './types';
import { SECTION_LABELS, sectionRequiresModule } from './types';
import { useModules } from '@/hooks/useModules';

export type SummaryStatus = 'normal' | 'warning' | 'danger';

export interface SectionSummary {
  key: SectionKey;
  label: string;
  value: string;
  status: SummaryStatus;
}

/** 숫자를 간략하게 포맷 (억/만) — 칩 표시용 (간결 + 반올림) */
function formatCompact(n: number): string {
  if (n === 0) return '0원';
  const abs = Math.abs(n);
  const sign = n < 0 ? '-' : '';
  if (abs >= 100_000_000) {
    const v = Math.round(abs / 100_000_000 * 10) / 10;
    return `${sign}${v % 1 === 0 ? v.toFixed(0) : v.toFixed(1)}억`;
  }
  if (abs >= 10_000) {
    const v = Math.round(abs / 10_000);
    return `${sign}${v.toLocaleString()}만`;
  }
  if (abs > 0) return `${sign}${abs.toLocaleString()}원`;
  return '0원';
}

/** 카드 배열에서 합계 카드(마지막) 금액 추출 — "합계" 라벨이 있으면 그것, 없으면 첫 번째 */
function getTotalCardAmount(cards?: { label: string; amount: number }[]): number {
  if (!cards?.length) return 0;
  const totalCard = cards.find((c) => c.label.includes('합계'));
  return totalCard ? totalCard.amount : cards[0].amount;
}

/** 체크포인트 배열에서 가장 심각한 상태 추출 */
function checkPointStatus(
  checkPoints?: { type: string }[],
): SummaryStatus {
  if (!checkPoints?.length) return 'normal';
  if (checkPoints.some((c) => c.type === 'error')) return 'danger';
  if (checkPoints.some((c) => c.type === 'warning')) return 'warning';
  return 'normal';
}

/** 섹션 활성화 여부 확인 */
function isSectionEnabled(key: SectionKey, settings: DashboardSettings): boolean {
  switch (key) {
    case 'todayIssueList': return !!settings.todayIssueList;
    case 'dailyReport': return !!settings.dailyReport;
    case 'statusBoard': return !!(settings.statusBoard?.enabled ?? settings.todayIssue.enabled);
    case 'monthlyExpense': return !!settings.monthlyExpense;
    case 'cardManagement': return !!settings.cardManagement;
    case 'entertainment': return !!settings.entertainment.enabled;
    case 'welfare': return !!settings.welfare.enabled;
    case 'receivable': return !!settings.receivable;
    case 'debtCollection': return !!settings.debtCollection;
    case 'vat': return !!settings.vat;
    case 'calendar': return !!settings.calendar;
    case 'salesStatus': return !!(settings.salesStatus ?? true);
    case 'purchaseStatus': return !!(settings.purchaseStatus ?? true);
    case 'production': return !!(settings.production ?? true);
    case 'shipment': return !!(settings.shipment ?? true);
    case 'unshipped': return !!(settings.unshipped ?? true);
    case 'construction': return !!(settings.construction ?? true);
    case 'attendance': return !!(settings.attendance ?? true);
    default: return false;
  }
}

/** 섹션별 요약값 + 상태 추출 */
function extractSummary(
  key: SectionKey,
  data: CEODashboardData,
): { value: string; status: SummaryStatus } {
  switch (key) {
    case 'todayIssueList': {
      const count = data.todayIssueList?.length ?? 0;
      return { value: `${count}건`, status: count > 0 ? 'warning' : 'normal' };
    }
    case 'dailyReport': {
      const firstCard = data.dailyReport?.cards?.[0];
      return {
        value: firstCard ? formatCompact(firstCard.amount) : '-',
        status: 'normal',
      };
    }
    case 'statusBoard': {
      const count = data.todayIssue?.length ?? 0;
      const hasHighlight = data.todayIssue?.some((i) => i.isHighlighted);
      return {
        value: `${count}항목`,
        status: hasHighlight ? 'danger' : 'normal',
      };
    }
    case 'monthlyExpense': {
      const total = getTotalCardAmount(data.monthlyExpense?.cards);
      return {
        value: formatCompact(total),
        status: checkPointStatus(data.monthlyExpense?.checkPoints),
      };
    }
    case 'cardManagement': {
      const total = getTotalCardAmount(data.cardManagement?.cards);
      const hasHighlight = data.cardManagement?.cards?.some((c) => c.isHighlighted);
      const hasWarning = !!data.cardManagement?.warningBanner;
      return {
        value: formatCompact(total),
        status: hasHighlight ? 'danger' : hasWarning ? 'warning' : 'normal',
      };
    }
    case 'entertainment': {
      const total = data.entertainment?.cards?.reduce((s, c) => s + c.amount, 0) ?? 0;
      return {
        value: formatCompact(total),
        status: checkPointStatus(data.entertainment?.checkPoints),
      };
    }
    case 'welfare': {
      const total = data.welfare?.cards?.reduce((s, c) => s + c.amount, 0) ?? 0;
      return {
        value: formatCompact(total),
        status: checkPointStatus(data.welfare?.checkPoints),
      };
    }
    case 'receivable': {
      // 누적 미수금 = 첫 번째 카드
      const first = data.receivable?.cards?.[0];
      return {
        value: first ? formatCompact(first.amount) : '-',
        status: checkPointStatus(data.receivable?.checkPoints),
      };
    }
    case 'debtCollection': {
      const first = data.debtCollection?.cards?.[0];
      return {
        value: first ? formatCompact(first.amount) : '-',
        status: checkPointStatus(data.debtCollection?.checkPoints),
      };
    }
    case 'vat': {
      const first = data.vat?.cards?.[0];
      return {
        value: first ? formatCompact(first.amount) : '-',
        status: 'normal',
      };
    }
    case 'calendar': {
      const count = data.calendarSchedules?.length ?? 0;
      return { value: `${count}일정`, status: 'normal' };
    }
    case 'salesStatus': {
      return {
        value: formatCompact(data.salesStatus?.cumulativeSales ?? 0),
        status: 'normal',
      };
    }
    case 'purchaseStatus': {
      return {
        value: formatCompact(data.purchaseStatus?.cumulativePurchase ?? 0),
        status: 'normal',
      };
    }
    case 'production': {
      const count = data.dailyProduction?.processes?.length ?? 0;
      return { value: `${count}공정`, status: 'normal' };
    }
    case 'shipment': {
      const count = data.dailyProduction?.shipment?.actualCount ?? 0;
      return { value: `${count}건`, status: 'normal' };
    }
    case 'unshipped': {
      const count = data.unshipped?.items?.length ?? 0;
      return {
        value: `${count}건`,
        status: count > 0 ? 'danger' : 'normal',
      };
    }
    case 'construction': {
      return {
        value: `${data.constructionData?.thisMonth ?? 0}건`,
        status: 'normal',
      };
    }
    case 'attendance': {
      return {
        value: `${data.dailyAttendance?.present ?? 0}명`,
        status: 'normal',
      };
    }
    default:
      return { value: '-', status: 'normal' };
  }
}

interface UseSectionSummaryParams {
  data: CEODashboardData;
  sectionOrder: SectionKey[];
  dashboardSettings: DashboardSettings;
}

interface UseSectionSummaryReturn {
  summaries: SectionSummary[];
  activeSectionKey: SectionKey | null;
  sectionRefs: React.MutableRefObject<Map<SectionKey, HTMLElement>>;
  scrollToSection: (key: SectionKey) => void;
}

export function useSectionSummary({
  data,
  sectionOrder,
  dashboardSettings,
}: UseSectionSummaryParams): UseSectionSummaryReturn {
  const sectionRefs = useRef<Map<SectionKey, HTMLElement>>(new Map());
  const [activeSectionKey, setActiveSectionKey] = useState<SectionKey | null>(null);
  // 칩 클릭으로 선택된 키 — 해당 섹션이 화면에 보이는 한 유지
  const pinnedKey = useRef<SectionKey | null>(null);

  // 모듈 활성화 정보 (tenantIndustry 미설정 시 전부 표시)
  const { isEnabled, tenantIndustry } = useModules();
  const moduleAware = !!tenantIndustry;

  // 활성화된 섹션만 필터 (설정 + 모듈)
  const enabledSections = useMemo(
    () => sectionOrder.filter((key) => {
      if (!isSectionEnabled(key, dashboardSettings)) return false;
      if (moduleAware) {
        const requiredModule = sectionRequiresModule(key);
        if (requiredModule && !isEnabled(requiredModule)) return false;
      }
      return true;
    }),
    [sectionOrder, dashboardSettings, moduleAware, isEnabled],
  );

  // 요약 데이터 계산
  const summaries = useMemo<SectionSummary[]>(
    () =>
      enabledSections.map((key) => {
        const { value, status } = extractSummary(key, data);
        return { key, label: SECTION_LABELS[key], value, status };
      }),
    [enabledSections, data],
  );

  // 스크롤 기반 현재 섹션 감지
  useEffect(() => {
    const handleScroll = () => {
      // pin이 걸려 있으면 스크롤 감지 무시 (칩 클릭 후 programmatic scroll 중)
      if (pinnedKey.current) return;

      const headerBottom = 156; // 헤더(~100px) + 요약바(~56px)
      let bestKey: SectionKey | null = null;
      let bestDistance = Infinity;

      for (const [key, el] of sectionRefs.current.entries()) {
        const rect = el.getBoundingClientRect();
        const distance = Math.abs(rect.top - headerBottom);
        if (rect.top < window.innerHeight * 0.6 && rect.bottom > headerBottom) {
          if (distance < bestDistance) {
            bestDistance = distance;
            bestKey = key;
          }
        }
      }
      if (bestKey) {
        setActiveSectionKey(bestKey);
      }
    };

    // 사용자가 직접 스크롤(마우스 휠/터치)하면 pin 해제
    const handleUserScroll = () => { pinnedKey.current = null; };

    window.addEventListener('scroll', handleScroll, { passive: true });
    window.addEventListener('wheel', handleUserScroll, { passive: true });
    window.addEventListener('touchstart', handleUserScroll, { passive: true });
    handleScroll(); // 초기 호출
    return () => {
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('wheel', handleUserScroll);
      window.removeEventListener('touchstart', handleUserScroll);
    };
  }, [enabledSections, summaries]);

  // 칩 클릭 → 즉시 활성 표시 + 섹션으로 스크롤
  const scrollToSection = useCallback((key: SectionKey) => {
    setActiveSectionKey(key);
    pinnedKey.current = key; // 해당 섹션이 화면에 보이는 한 유지

    const el = sectionRefs.current.get(key);
    if (!el) return;

    const elRect = el.getBoundingClientRect();
    const offset = window.scrollY + elRect.top - 160; // 헤더(~100) + 요약바(~56) + 여유

    window.scrollTo({ top: offset, behavior: 'smooth' });
  }, []);

  return { summaries, activeSectionKey, sectionRefs, scrollToSection };
}
