import { useState, useEffect, useCallback } from 'preact/hooks';
import type { RecommendationSummary, FeedbackEntry } from '../types/index.js';
import {
  listRecommendations,
  createRecommendation,
  rerankRecommendation,
  submitFeedback,
  getFeedback,
} from '../api/client.js';

export function useRecommendations() {
  const [list, setList] = useState<RecommendationSummary[]>([]);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [feedback, setFeedback] = useState<FeedbackEntry[]>([]);

  const refreshList = useCallback(async () => {
    const rows = await listRecommendations();
    setList(rows);
  }, []);

  const refreshFeedback = useCallback(async () => {
    const rows = await getFeedback();
    setFeedback(rows);
  }, []);

  useEffect(() => {
    void refreshList();
    void refreshFeedback();
  }, [refreshList, refreshFeedback]);

  const createNew = useCallback(
    async (body: {
      main_prompt: string;
      liked_shows: string;
      disliked_shows: string;
      themes: string;
    }) => {
      const { id } = await createRecommendation(body);
      await refreshList();
      setSelectedId(id);
      return id;
    },
    [refreshList],
  );

  const rerank = useCallback(
    async (id: string) => {
      await rerankRecommendation(id);
      // Update local list to show pending status
      setList((prev) =>
        prev.map((r) => (r.id === id ? { ...r, status: 'pending' as const } : r)),
      );
    },
    [],
  );

  const handleSubmitFeedback = useCallback(
    async (body: { tv_show_name: string; stars: number; feedback?: string }) => {
      await submitFeedback(body);
      await refreshFeedback();
    },
    [refreshFeedback],
  );

  const updateStatus = useCallback(
    (id: string, status: RecommendationSummary['status']) => {
      setList((prev) => prev.map((r) => (r.id === id ? { ...r, status } : r)));
    },
    [],
  );

  return {
    list,
    selectedId,
    feedback,
    setSelectedId,
    createNew,
    rerank,
    submitFeedback: handleSubmitFeedback,
    updateStatus,
    refreshList,
  };
}
