"use client";

import { useState, useEffect } from "react";
import {
  searchEmails,
  listSavedSearches,
  createSavedSearch,
  deleteSavedSearch,
  type SearchHit,
  type SavedSearch,
} from "@/lib/api";

type SavedSearchUser = { role: string } | null;

interface UseSavedSearchesParams {
  user: SavedSearchUser;
  pageSize: number;
  query: string;
  fromFilter: string;
  toFilter: string;
  dateFrom: string;
  dateTo: string;
  hasAttachment: boolean | undefined;
  setQuery: (v: string) => void;
  setFromFilter: (v: string) => void;
  setToFilter: (v: string) => void;
  setDateFrom: (v: string) => void;
  setDateTo: (v: string) => void;
  setHasAttachment: (v: boolean | undefined) => void;
  setResults: (v: SearchHit[]) => void;
  setTotal: (v: number) => void;
  setPage: (v: number) => void;
  setSearching: (v: boolean) => void;
  setSearched: (v: boolean) => void;
}

export function useSavedSearches(params: UseSavedSearchesParams) {
  const {
    user,
    pageSize,
    query,
    fromFilter,
    toFilter,
    dateFrom,
    dateTo,
    hasAttachment,
    setQuery,
    setFromFilter,
    setToFilter,
    setDateFrom,
    setDateTo,
    setHasAttachment,
    setResults,
    setTotal,
    setPage,
    setSearching,
    setSearched,
  } = params;

  const [savedSearches, setSavedSearches] = useState<SavedSearch[]>([]);
  const [savedLoading, setSavedLoading] = useState(false);
  const [savePopoverOpen, setSavePopoverOpen] = useState(false);
  const [saveName, setSaveName] = useState("");
  const [saving, setSaving] = useState(false);
  const [savedListOpen, setSavedListOpen] = useState(false);

  // Load saved searches on mount
  useEffect(() => {
    if (!user || user.role === "superadmin") return;
    setSavedLoading(true);
    listSavedSearches()
      .then((list) => setSavedSearches(list || []))
      .catch(() => setSavedSearches([]))
      .finally(() => setSavedLoading(false));
  }, [user]);

  function buildCurrentQuery(): Record<string, string> {
    const q: Record<string, string> = {};
    if (query) q.q = query;
    if (fromFilter) q.from = fromFilter;
    if (toFilter) q.to = toFilter;
    if (dateFrom) q.date_from = dateFrom;
    if (dateTo) q.date_to = dateTo;
    if (hasAttachment) q.has_attachment = "true";
    return q;
  }

  async function handleSaveSearch() {
    if (!saveName.trim()) return;
    setSaving(true);
    try {
      const saved = await createSavedSearch(saveName.trim(), buildCurrentQuery());
      setSavedSearches((prev) => [saved, ...prev]);
      setSaveName("");
      setSavePopoverOpen(false);
    } catch (e) {
      alert(`Suche speichern fehlgeschlagen: ${e instanceof Error ? e.message : e}`);
    } finally {
      setSaving(false);
    }
  }

  function handleApplySavedSearch(s: SavedSearch) {
    setQuery(s.query.q || "");
    setFromFilter(s.query.from || "");
    setToFilter(s.query.to || "");
    setDateFrom(s.query.date_from || "");
    setDateTo(s.query.date_to || "");
    setHasAttachment(s.query.has_attachment === "true" ? true : undefined);
    setSavedListOpen(false);
    // Trigger search after state updates
    setTimeout(() => {
      // We need to search with the saved query directly since state isn't updated yet
      setSearching(true);
      searchEmails({
        q: s.query.q || undefined,
        from: s.query.from || undefined,
        to: s.query.to || undefined,
        date_from: s.query.date_from || undefined,
        date_to: s.query.date_to || undefined,
        has_attachment: s.query.has_attachment === "true" ? true : undefined,
        page: 1,
        page_size: pageSize,
      })
        .then((res) => {
          setResults(res.hits || []);
          setTotal(res.total);
          setPage(1);
          setSearched(true);
        })
        .catch(() => {
          setResults([]);
          setTotal(0);
        })
        .finally(() => setSearching(false));
    }, 0);
  }

  async function handleDeleteSavedSearch(id: number) {
    try {
      await deleteSavedSearch(id);
      setSavedSearches((prev) => prev.filter((s) => s.id !== id));
    } catch (e) {
      alert(`Loeschen fehlgeschlagen: ${e instanceof Error ? e.message : e}`);
    }
  }

  return {
    savedSearches,
    savedLoading,
    savePopoverOpen,
    setSavePopoverOpen,
    saveName,
    setSaveName,
    saving,
    savedListOpen,
    setSavedListOpen,
    buildCurrentQuery,
    handleSaveSearch,
    handleApplySavedSearch,
    handleDeleteSavedSearch,
  };
}
