import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import {
  createWalkthroughCheckin,
  deleteWalkthroughCheckin,
  listWalkthroughCheckins,
} from '@/shared/api/walkthrough';
import type { WalkthroughCheckinCreateDto } from '@/shared/types/walkthrough';
import { WALKTHROUGH_QUERY_KEYS } from '@/shared/constants/walkthrough';
import type { WalkthroughSummaryRange } from '@/shared/constants/walkthrough';
import type {
  WalkthroughCheckInPage,
  WalkthroughCheckInTab,
  WalkthroughCheckInTabId,
  WalkthroughGrowthPlan,
} from '@/business/walkthrough/types';
import {
  buildWalkthroughAutoSummary,
  buildWalkthroughCheckInStats,
  buildWalkthroughHistoryRows,
  calculateWalkthroughCategoryAverages,
  calculateWalkthroughOverallPctFromAverages,
  calculateWalkthroughTeacherFrequencies,
  calculateWalkthroughTrend,
  createWalkthroughCategoryAverageMap,
  filterWalkthroughCheckins,
  findWalkthroughAttentionFlags,
  findWalkthroughRecognitions,
  getWalkthroughStatus,
  listWalkthroughTeachers,
} from '@/business/walkthrough/selectors';
import type { WalkthroughCheckinDto } from '@/shared/types/walkthrough';
import { getApiListRows } from '@/shared/business/apiListRows';
import { useInvalidatingMutation } from '@/shared/business/queryMutations';
import { getOptionalErrorMessage } from '@/shared/errors/errorMessages';

const EMPTY_GROWTH_PLAN: WalkthroughGrowthPlan = {
  strengths: '',
  focusAreas: '',
  nextSteps: '',
  reviewDate: '',
};

const EMPTY_WALKTHROUGH_CHECKINS: readonly WalkthroughCheckinDto[] = [];

const WALKTHROUGH_CHECK_IN_TABS: readonly WalkthroughCheckInTab[] = [
  { id: 'new', label: 'New Check-In' },
  { id: 'summary', label: 'Performance Summary' },
  { id: 'history', label: 'History' },
];

export function useWalkthroughCheckins(teacherName?: string) {
  return useQuery({
    queryKey: teacherName ? [...WALKTHROUGH_QUERY_KEYS.checkins, teacherName] : WALKTHROUGH_QUERY_KEYS.checkins,
    queryFn: () => getApiListRows(listWalkthroughCheckins(teacherName)),
  });
}

export function useSaveWalkthroughCheckin() {
  return useInvalidatingMutation({
    mutationFn: (request: WalkthroughCheckinCreateDto) => createWalkthroughCheckin(request),
    invalidateQueryKey: WALKTHROUGH_QUERY_KEYS.checkins,
  });
}

export function useDeleteWalkthroughCheckin() {
  return useInvalidatingMutation({
    mutationFn: (id: string) => deleteWalkthroughCheckin(id),
    invalidateQueryKey: WALKTHROUGH_QUERY_KEYS.checkins,
  });
}

export function useWalkthroughCheckInPage(userName: string): WalkthroughCheckInPage {
  const [activeTab, setActiveTab] = useState<WalkthroughCheckInTabId>('new');
  const checkinsQuery = useWalkthroughCheckins();
  const saveCheckinMutation = useSaveWalkthroughCheckin();

  const checkins = checkinsQuery.data ?? EMPTY_WALKTHROUGH_CHECKINS;
  const errorMessage = getOptionalErrorMessage(
    checkinsQuery.error || saveCheckinMutation.error,
    'Walk-through data could not be saved or loaded. Please try again.',
  );
  const stats = useMemo(() => buildWalkthroughCheckInStats(checkins), [checkins]);
  const historyRows = useMemo(() => buildWalkthroughHistoryRows(checkins), [checkins]);

  return {
    activeTab,
    tabs: WALKTHROUGH_CHECK_IN_TABS,
    checkins,
    stats,
    historyRows,
    loading: checkinsQuery.isLoading,
    submitting: saveCheckinMutation.isPending,
    errorMessage,
    userName,
    setActiveTab,
    refresh: async () => {
      await checkinsQuery.refetch();
    },
    submit: async (data) => {
      await saveCheckinMutation.mutateAsync(data);
    },
  };
}

export function useWalkthroughSummary(checkins: readonly WalkthroughCheckinDto[]) {
  const [selectedTeacher, setSelectedTeacher] = useState('all');
  const [timeRange, setTimeRange] = useState<WalkthroughSummaryRange>('60');
  const [presentationMode, setPresentationMode] = useState(false);
  const [showReport, setShowReport] = useState(false);
  const [growthPlan, setGrowthPlan] = useState<WalkthroughGrowthPlan>(EMPTY_GROWTH_PLAN);

  const teachers = useMemo(() => listWalkthroughTeachers(checkins), [checkins]);

  const filteredCheckins = useMemo(
    () => filterWalkthroughCheckins(checkins, selectedTeacher, timeRange),
    [checkins, selectedTeacher, timeRange],
  );

  const categoryAverages = useMemo(
    () => calculateWalkthroughCategoryAverages(filteredCheckins),
    [filteredCheckins],
  );

  const categoryAverageByKey = useMemo(
    () => createWalkthroughCategoryAverageMap(categoryAverages),
    [categoryAverages],
  );

  const overallPct = useMemo(
    () => calculateWalkthroughOverallPctFromAverages(categoryAverages, filteredCheckins.length),
    [categoryAverages, filteredCheckins.length],
  );

  const status = useMemo(() => getWalkthroughStatus(overallPct), [overallPct]);

  const flags = useMemo(
    () => findWalkthroughAttentionFlags(filteredCheckins, selectedTeacher),
    [filteredCheckins, selectedTeacher],
  );

  const recognitions = useMemo(
    () => findWalkthroughRecognitions(filteredCheckins, selectedTeacher),
    [filteredCheckins, selectedTeacher],
  );

  const trendData = useMemo(() => calculateWalkthroughTrend(filteredCheckins), [filteredCheckins]);

  const autoSummary = useMemo(
    () => buildWalkthroughAutoSummary(
      filteredCheckins.length,
      categoryAverages,
      overallPct,
      selectedTeacher,
      timeRange,
    ),
    [categoryAverages, filteredCheckins.length, overallPct, selectedTeacher, timeRange],
  );

  const teacherFrequencies = useMemo(
    () => calculateWalkthroughTeacherFrequencies(filteredCheckins, teachers),
    [filteredCheckins, teachers],
  );

  return {
    selectedTeacher,
    timeRange,
    presentationMode,
    showReport,
    growthPlan,
    teachers,
    filteredCheckins,
    categoryAverages,
    categoryAverageByKey,
    overallPct,
    status,
    flags,
    recognitions,
    trendData,
    autoSummary,
    teacherFrequencies,
    setSelectedTeacher,
    setTimeRange,
    setPresentationMode,
    setShowReport,
    setGrowthPlan,
  };
}
