'use client';

/**
 * Dashboard Type2 통합 데이터 Hook
 * 기존 CEO Dashboard API 훅들을 재사용하여 탭별 데이터 제공
 * API 실패 시 mockData fallback
 */

import { useCallback, useMemo } from 'react';
import {
  useDailyReport,
  useReceivable,
  useDebtCollection,
  useMonthlyExpense,
  useCardManagement,
  useEntertainment,
  useWelfare,
  useTodayIssue,
} from '@/hooks/useCEODashboard';

import type { StatCard, TableRow } from '../mockData';
import type { TodayIssueListItem } from '@/components/business/CEODashboard/types';

import {
  transformOverviewStats,
  transformSalesStats,
  transformFinanceStats,
  transformExpenseManagementStats,
  transformScheduleStats,
  transformExpenseChartData,
  transformReceivableChartData,
  transformOverviewChartData,
  transformExpenseTable,
  transformCardTable,
  transformDebtTable,
  transformEntertainmentTable,
  transformWelfareTable,
  statsToRollingItems,
  type ExpenseChartItem,
  type ReceivableChartItem,
  type OverviewChartItem,
} from './transformers';

import * as mock from '../mockData';

// ============================================
// 타입 정의
// ============================================

export interface OverviewTabData {
  stats: StatCard[];
  recentOrders: TableRow[];
  chartData: OverviewChartItem[];
  loading: boolean;
  error: string | null;
}

export interface FinanceTabData {
  stats: StatCard[];
  expenseData: TableRow[];
  cardData: TableRow[];
  expenseChartData: ExpenseChartItem[];
  loading: boolean;
  error: string | null;
}

export interface SalesTabData {
  stats: StatCard[];
  receivableData: TableRow[];
  debtData: TableRow[];
  receivableChartData: ReceivableChartItem[];
  loading: boolean;
  error: string | null;
}

export interface ExpenseTabData {
  stats: StatCard[];
  entertainmentData: TableRow[];
  welfareData: TableRow[];
  loading: boolean;
  error: string | null;
}

export interface ScheduleTabData {
  stats: StatCard[];
  todayItems: TodayIssueListItem[];
  issueItems: TodayIssueListItem[];
  loading: boolean;
  error: string | null;
}

export interface DashboardType2Data {
  overview: OverviewTabData;
  finance: FinanceTabData;
  sales: SalesTabData;
  expense: ExpenseTabData;
  schedule: ScheduleTabData;
  refetchAll: () => void;
}

// ============================================
// Hook 구현
// ============================================

export function useDashboardType2(): DashboardType2Data {
  // 기존 API 훅 호출
  const dailyReport = useDailyReport();
  const receivable = useReceivable();
  const debtCollection = useDebtCollection();
  const monthlyExpense = useMonthlyExpense();
  const cardManagement = useCardManagement();
  const entertainment = useEntertainment();
  const welfare = useWelfare();
  const todayIssue = useTodayIssue();

  // 전체요약 탭
  const overview = useMemo<OverviewTabData>(() => {
    const loading = dailyReport.loading;
    const error = dailyReport.error;

    if (error && !dailyReport.data) {
      return {
        stats: mock.overviewStats,
        recentOrders: mock.overviewRecentOrders,
        chartData: [],
        loading: false,
        error,
      };
    }

    return {
      stats: dailyReport.data ? transformOverviewStats(dailyReport.data) : mock.overviewStats,
      recentOrders: mock.overviewRecentOrders, // 최근 수주는 별도 API 없으므로 mock 유지
      chartData: dailyReport.data ? transformOverviewChartData(dailyReport.data) : [],
      loading,
      error,
    };
  }, [dailyReport.data, dailyReport.loading, dailyReport.error]);

  // 재무관리 탭
  const finance = useMemo<FinanceTabData>(() => {
    const loading = dailyReport.loading || monthlyExpense.loading || cardManagement.loading;
    const error = dailyReport.error || monthlyExpense.error || cardManagement.error;

    if (error && !dailyReport.data && !monthlyExpense.data && !cardManagement.data) {
      return {
        stats: mock.financeStats,
        expenseData: mock.financeExpenseData,
        cardData: mock.financeCardData,
        expenseChartData: mock.financeExpenseChartData,
        loading: false,
        error,
      };
    }

    return {
      stats: dailyReport.data ? transformFinanceStats(dailyReport.data) : mock.financeStats,
      expenseData: monthlyExpense.data ? transformExpenseTable(monthlyExpense.data) : mock.financeExpenseData,
      cardData: cardManagement.data ? transformCardTable(cardManagement.data) : mock.financeCardData,
      expenseChartData: monthlyExpense.data ? transformExpenseChartData(monthlyExpense.data) : mock.financeExpenseChartData,
      loading,
      error,
    };
  }, [
    dailyReport.data, dailyReport.loading, dailyReport.error,
    monthlyExpense.data, monthlyExpense.loading, monthlyExpense.error,
    cardManagement.data, cardManagement.loading, cardManagement.error,
  ]);

  // 영업/매출 탭
  const sales = useMemo<SalesTabData>(() => {
    const loading = receivable.loading || debtCollection.loading;
    const error = receivable.error || debtCollection.error;

    if (error && !receivable.data && !debtCollection.data) {
      return {
        stats: mock.salesStats,
        receivableData: mock.salesReceivableData,
        debtData: mock.salesDebtData,
        receivableChartData: [],
        loading: false,
        error,
      };
    }

    return {
      stats: transformSalesStats(receivable.data, debtCollection.data).length > 0
        ? transformSalesStats(receivable.data, debtCollection.data)
        : mock.salesStats,
      receivableData: mock.salesReceivableData, // 상세 미수금 목록은 별도 API 없으므로 mock 유지
      debtData: debtCollection.data ? transformDebtTable(debtCollection.data) : mock.salesDebtData,
      receivableChartData: receivable.data ? transformReceivableChartData(receivable.data) : [],
      loading,
      error,
    };
  }, [
    receivable.data, receivable.loading, receivable.error,
    debtCollection.data, debtCollection.loading, debtCollection.error,
  ]);

  // 경비관리 탭
  const expense = useMemo<ExpenseTabData>(() => {
    const loading = entertainment.loading || welfare.loading;
    const error = entertainment.error || welfare.error;

    if (error && !entertainment.data && !welfare.data) {
      return {
        stats: mock.expenseStats,
        entertainmentData: mock.expenseEntertainmentData,
        welfareData: mock.expenseWelfareData,
        loading: false,
        error,
      };
    }

    return {
      stats: transformExpenseManagementStats(entertainment.data, welfare.data).length > 0
        ? transformExpenseManagementStats(entertainment.data, welfare.data)
        : mock.expenseStats,
      entertainmentData: entertainment.data
        ? transformEntertainmentTable(entertainment.data)
        : mock.expenseEntertainmentData,
      welfareData: welfare.data
        ? transformWelfareTable(welfare.data)
        : mock.expenseWelfareData,
      loading,
      error,
    };
  }, [
    entertainment.data, entertainment.loading, entertainment.error,
    welfare.data, welfare.loading, welfare.error,
  ]);

  // 일정/이슈 탭
  const schedule = useMemo<ScheduleTabData>(() => {
    const loading = todayIssue.loading;
    const error = todayIssue.error;

    if (error && !todayIssue.data) {
      return {
        stats: mock.scheduleStats,
        todayItems: [],
        issueItems: [],
        loading: false,
        error,
      };
    }

    const items = todayIssue.data?.items ?? [];
    const approvalItems = items.filter((i) => i.needsApproval);
    const regularItems = items.filter((i) => !i.needsApproval);

    return {
      stats: todayIssue.data
        ? transformScheduleStats(todayIssue.data).length > 0
          ? transformScheduleStats(todayIssue.data)
          : mock.scheduleStats
        : mock.scheduleStats,
      todayItems: regularItems,
      issueItems: approvalItems,
      loading,
      error,
    };
  }, [todayIssue.data, todayIssue.loading, todayIssue.error]);

  // 전체 refetch
  const refetchAll = useCallback(() => {
    dailyReport.refetch();
    receivable.refetch();
    debtCollection.refetch();
    monthlyExpense.refetch();
    cardManagement.refetch();
    entertainment.refetch();
    welfare.refetch();
    todayIssue.refetch();
  }, [
    dailyReport, receivable, debtCollection, monthlyExpense,
    cardManagement, entertainment, welfare, todayIssue,
  ]);

  return {
    overview,
    finance,
    sales,
    expense,
    schedule,
    refetchAll,
  };
}

// ============================================
// 탭별 롤링 아이템 헬퍼
// ============================================

export function getRollingItems(tabKey: string, data: DashboardType2Data) {
  switch (tabKey) {
    case 'overview':
      return statsToRollingItems(data.overview.stats);
    case 'finance':
      return statsToRollingItems(data.finance.stats);
    case 'sales':
      return statsToRollingItems(data.sales.stats);
    case 'expense':
      return statsToRollingItems(data.expense.stats);
    case 'schedule':
      return statsToRollingItems(data.schedule.stats);
    default:
      return [];
  }
}
