"use client";

import { useState, useCallback, useEffect } from "react";
import { searchEmails, type SearchHit } from "@/lib/api";

const DEFAULT_PAGE_SIZE = 25;

type SearchUser = { role: string } | null;

export function useSearch(user: SearchUser, pageSize: number) {
  const [query, setQuery] = useState("");
  const [fromFilter, setFromFilter] = useState("");
  const [toFilter, setToFilter] = useState("");
  const [dateFrom, setDateFrom] = useState("");
  const [dateTo, setDateTo] = useState("");
  const [sort, setSort] = useState("date_desc");
  const [hasAttachment, setHasAttachment] = useState<boolean | undefined>(undefined);

  const [results, setResults] = useState<SearchHit[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [searching, setSearching] = useState(false);
  const [searched, setSearched] = useState(false);

  const doSearch = useCallback(
    async (p: number) => {
      setSearching(true);
      try {
        const res = await searchEmails({
          q: query || undefined,
          from: fromFilter || undefined,
          to: toFilter || undefined,
          date_from: dateFrom || undefined,
          date_to: dateTo || undefined,
          sort: sort !== "date_desc" ? sort : undefined,
          has_attachment: hasAttachment,
          page: p,
          page_size: pageSize,
        });
        setResults(res.hits || []);
        setTotal(res.total);
        setPage(p);
        setSearched(true);
      } catch {
        setResults([]);
        setTotal(0);
      } finally {
        setSearching(false);
      }
    },
    [query, fromFilter, toFilter, dateFrom, dateTo, sort, hasAttachment, pageSize]
  );

  // Alle Mails beim Öffnen der Seite laden — direkt, ohne useCallback-Closure
  useEffect(() => {
    if (!user || user.role === "superadmin") return;
    setSearching(true);
    searchEmails({ page: 1, page_size: pageSize })
      .then((res) => {
        setResults(res.hits || []);
        setTotal(res.total);
        setPage(1);
        setSearched(true);
      })
      .catch(() => {
        setResults([]);
        setTotal(0);
      })
      .finally(() => setSearching(false));
  }, [user, pageSize]);

  return {
    query,
    setQuery,
    fromFilter,
    setFromFilter,
    toFilter,
    setToFilter,
    dateFrom,
    setDateFrom,
    dateTo,
    setDateTo,
    sort,
    setSort,
    hasAttachment,
    setHasAttachment,
    results,
    setResults,
    total,
    setTotal,
    page,
    setPage,
    searching,
    setSearching,
    searched,
    setSearched,
    doSearch,
  };
}

export { DEFAULT_PAGE_SIZE };
