/**
 * 侧边栏功能组合式函数
 *
 * 管理与侧边栏相关的状态和方法，包括：
 * - 侧边栏折叠状态
 * - 高级筛选（标签、日期、文本）
 * - 排序方式
 * - 录音分组显示
 * - 草稿箱重命名编辑状态
 * - 无限滚动加载
 */

import { ref, computed, watch, nextTick } from "vue";

/**
 * @param {Object} options - 配置选项
 * @param {Function} options.t - 翻译函数
 * @param {Object} options.filteredRecordings - 过滤后的录音列表 computed
 * @param {Function} options.loadRecordings - 加载录音函数
 * @param {Function} options.showToast - 显示提示函数
 * @param {Object} options.currentPage - 当前页码 ref
 * @param {Object} options.hasNextPage - 是否有下一页 ref
 * @param {Object} options.isLoadingMore - 是否正在加载更多 ref
 * @param {Object} options.searchQuery - 搜索查询 ref
 * @param {Object} options.availableTags - 可用标签列表 ref
 * @param {Object} options.draftNameInput - 草稿名称输入框 ref
 * @returns {Object} 侧边栏相关的状态和方法
 */
export function useSidebar({
  t,
  filteredRecordings,
  loadRecordings,
  showToast,
  currentPage,
  hasNextPage,
  isLoadingMore,
  searchQuery,
  availableTags,
  draftNameInput,
}) {
  // ============== 侧边栏 UI 状态 ==============
  const isSidebarCollapsed = ref(false);
  const showAdvancedFilters = ref(false);

  // ============== 筛选状态 ==============
  const filterTags = ref([]); // 选中的标签 ID 列表
  const filterDateRange = ref({ start: "", end: "" });
  const filterDatePreset = ref(""); // 'today', 'yesterday', 'week', 'month', etc.
  const filterTextQuery = ref("");

  // ============== 排序状态 ==============
  const sortBy = ref("created_at"); // 'created_at' 或 'meeting_date'

  // ============== 草稿箱编辑状态 ==============
  const editingDraftId = ref(null);
  const editingDraftName = ref("");
  const searchDebounceTimer = ref(null);

  // ============== 计算属性 ==============

  // 日期预设选项
  const datePresetOptions = computed(() => {
    return [
      { value: "today", label: t("sidebar.today") },
      { value: "yesterday", label: t("sidebar.yesterday") },
      { value: "thisweek", label: t("sidebar.thisWeek") },
      { value: "lastweek", label: t("sidebar.lastWeek") },
      { value: "thismonth", label: t("sidebar.thisMonth") },
      { value: "lastmonth", label: t("sidebar.lastMonth") },
    ];
  });

  // ============== 日期工具函数 ==============

  const isSameDay = (date1, date2) => {
    return (
      date1.getFullYear() === date2.getFullYear() &&
      date1.getMonth() === date2.getMonth() &&
      date1.getDate() === date2.getDate()
    );
  };

  const isToday = (date) => {
    const today = new Date();
    return isSameDay(date, today);
  };

  const isYesterday = (date) => {
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    return isSameDay(date, yesterday);
  };

  const isThisWeek = (date) => {
    const now = new Date();
    const startOfWeek = new Date(now);
    const day = now.getDay();
    const diff = now.getDate() - day + (day === 0 ? -6 : 1); // 周一为周开始
    startOfWeek.setDate(diff);
    startOfWeek.setHours(0, 0, 0, 0);

    const endOfWeek = new Date(startOfWeek);
    endOfWeek.setDate(startOfWeek.getDate() + 6);
    endOfWeek.setHours(23, 59, 59, 999);

    return date >= startOfWeek && date <= endOfWeek;
  };

  const isLastWeek = (date) => {
    const now = new Date();
    const startOfLastWeek = new Date(now);
    const day = now.getDay();
    const diff = now.getDate() - day + (day === 0 ? -6 : 1) - 7; // 上周一
    startOfLastWeek.setDate(diff);
    startOfLastWeek.setHours(0, 0, 0, 0);

    const endOfLastWeek = new Date(startOfLastWeek);
    endOfLastWeek.setDate(startOfLastWeek.getDate() + 6);
    endOfLastWeek.setHours(23, 59, 59, 999);

    return date >= startOfLastWeek && date <= endOfLastWeek;
  };

  const isThisMonth = (date) => {
    const now = new Date();
    return (
      date.getFullYear() === now.getFullYear() &&
      date.getMonth() === now.getMonth()
    );
  };

  const isLastMonth = (date) => {
    const now = new Date();
    const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
    return (
      date.getFullYear() === lastMonth.getFullYear() &&
      date.getMonth() === lastMonth.getMonth()
    );
  };

  const getDateForSorting = (recording) => {
    const dateStr =
      sortBy.value === "meeting_date"
        ? recording.meeting_date
        : recording.created_at;
    if (!dateStr) return null;
    return new Date(dateStr);
  };

  // ============== 分组录音列表 ==============

  const groupedRecordings = computed(() => {
    // Sort recordings based on the selected sort criteria
    const sortedRecordings = [...filteredRecordings.value].sort((a, b) => {
      const dateA = getDateForSorting(a);
      const dateB = getDateForSorting(b);

      // Handle null dates (put them at the end)
      if (!dateA && !dateB) return 0;
      if (!dateA) return 1;
      if (!dateB) return -1;

      return dateB - dateA; // Most recent first
    });

    const groups = {
      today: [],
      yesterday: [],
      thisWeek: [],
      lastWeek: [],
      thisMonth: [],
      lastMonth: [],
      older: [],
    };

    sortedRecordings.forEach((recording) => {
      const date = getDateForSorting(recording);
      if (!date) {
        groups.older.push(recording);
        return;
      }

      if (isToday(date)) {
        groups.today.push(recording);
      } else if (isYesterday(date)) {
        groups.yesterday.push(recording);
      } else if (isThisWeek(date)) {
        groups.thisWeek.push(recording);
      } else if (isLastWeek(date)) {
        groups.lastWeek.push(recording);
      } else if (isThisMonth(date)) {
        groups.thisMonth.push(recording);
      } else if (isLastMonth(date)) {
        groups.lastMonth.push(recording);
      } else {
        groups.older.push(recording);
      }
    });

    return [
      { title: t("sidebar.today"), items: groups.today },
      { title: t("sidebar.yesterday"), items: groups.yesterday },
      { title: t("sidebar.thisWeek"), items: groups.thisWeek },
      { title: t("sidebar.lastWeek"), items: groups.lastWeek },
      { title: t("sidebar.thisMonth"), items: groups.thisMonth },
      { title: t("sidebar.lastMonth"), items: groups.lastMonth },
      { title: t("sidebar.older"), items: groups.older },
    ].filter((group) => group.items.length > 0);
  });

  // ============== 侧边栏控制方法 ==============

  const toggleSidebar = () => {
    isSidebarCollapsed.value = !isSidebarCollapsed.value;
  };

  // ============== 筛选相关方法 ==============

  // Build search query from advanced filters
  const buildSearchQuery = () => {
    let query = [];

    // Add text search
    if (filterTextQuery.value.trim()) {
      query.push(filterTextQuery.value.trim());
    }

    // Add tag filters
    if (filterTags.value.length > 0) {
      const tagNames = filterTags.value
        .map((tagId) => {
          const tag = availableTags.value.find((t) => t.id === tagId);
          return tag ? `tag:${tag.name.replace(/\s+/g, "_")}` : "";
        })
        .filter(Boolean);
      query.push(...tagNames);
    }

    // Add date filter
    if (filterDatePreset.value) {
      query.push(`date:${filterDatePreset.value}`);
    } else if (filterDateRange.value.start || filterDateRange.value.end) {
      // Custom date range - send as separate parameters
      if (filterDateRange.value.start) {
        query.push(`date_from:${filterDateRange.value.start}`);
      }
      if (filterDateRange.value.end) {
        query.push(`date_to:${filterDateRange.value.end}`);
      }
    }

    return query.join(" ");
  };

  const applyAdvancedFilters = () => {
    searchQuery.value = buildSearchQuery();
  };

  const clearAllFilters = () => {
    filterTags.value = [];
    filterDateRange.value = { start: "", end: "" };
    filterDatePreset.value = "";
    filterTextQuery.value = "";
    searchQuery.value = "";
  };

  const filterByTag = (tag) => {
    // Use advanced filter instead of text-based
    filterTags.value = [tag.id];
    applyAdvancedFilters();
  };

  const clearTagFilter = () => {
    searchQuery.value = "";
    clearAllFilters();
  };

  // ============== 无限滚动加载 ==============

  const loadMoreRecordings = async () => {
    if (!hasNextPage.value || isLoadingMore.value) return;
    await loadRecordings(currentPage.value + 1, true, searchQuery.value);
  };

  // ============== 草稿重命名方法 ==============

  const startDraftRename = (draft) => {
    editingDraftId.value = draft.id;
    editingDraftName.value = draft.name;
    // 等待 DOM 更新后聚焦输入框
    nextTick(() => {
      if (draftNameInput.value && draftNameInput.value[0]) {
        draftNameInput.value[0].focus();
      } else if (draftNameInput.value) {
        draftNameInput.value.focus();
      }
    });
  };

  const saveDraftRename = async (draft) => {
    if (!editingDraftId.value) return;

    const newName = editingDraftName.value.trim();
    editingDraftId.value = null; // 退出编辑模式

    if (!newName || newName === draft.name) return;

    try {
      const resp = await fetch(`/tool/speakr/api/draft/${draft.id}/rename`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: newName }),
      });
      const data = await resp.json();

      if (data.success) {
        draft.name = newName;
        showToast("重命名成功", "fa-check");
      } else {
        throw new Error(data.error);
      }
    } catch (err) {
      console.error("Error renaming draft:", err);
      showToast(`重命名失败: ${err.message}`, "fa-exclamation-circle");
    }
  };

  // ============== 自动应用筛选的监听器 ==============

  // Auto-apply filters when they change (except text query which is debounced)
  watch(
    filterTags,
    () => {
      applyAdvancedFilters();
    },
    { deep: true }
  );

  watch(filterDatePreset, () => {
    applyAdvancedFilters();
  });

  watch(
    filterDateRange,
    () => {
      applyAdvancedFilters();
    },
    { deep: true }
  );

  // Debounce text query changes
  watch(filterTextQuery, (newValue) => {
    clearTimeout(searchDebounceTimer.value);
    searchDebounceTimer.value = setTimeout(() => {
      applyAdvancedFilters();
    }, 300);
  });

  return {
    // 状态
    isSidebarCollapsed,
    showAdvancedFilters,
    filterTags,
    filterDateRange,
    filterDatePreset,
    filterTextQuery,
    sortBy,
    editingDraftId,
    editingDraftName,

    // 计算属性
    datePresetOptions,
    groupedRecordings,

    // 方法
    toggleSidebar,
    buildSearchQuery,
    applyAdvancedFilters,
    clearAllFilters,
    filterByTag,
    clearTagFilter,
    loadMoreRecordings,
    startDraftRename,
    saveDraftRename,
  };
}
