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

type GenerationMode = 'brainstorm' | 'continuous';

interface CreateBody {
  main_prompt: string;
  liked_series: string;
  disliked_series: string;
  themes: string;
  requirements?: string;
  avoid?: string;
  brainstorm_count?: number;
  media_type: MediaType;
  use_web_search?: boolean;
  use_validator?: boolean;
  hard_requirements?: boolean;
  self_expansive?: boolean;
  expansive_passes?: number;
  expansive_mode?: 'soft' | 'extreme';
  generation_mode?: GenerationMode;
  total_count?: number;
  validate_results?: boolean;
}

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: CreateBody) => {
      let id = '';

      if (body.generation_mode === 'continuous') {
        const result = await createContinuousRecommendation({
          liked_series: body.liked_series,
          disliked_series: body.disliked_series,
          themes: body.themes,
          requirements: body.requirements ?? '',
          avoid: body.avoid ?? '',
          total_count: body.total_count ?? 30,
          media_type: body.media_type,
          use_web_search: body.use_web_search,
          validate_results: body.validate_results,
        });
        id = result.id;
      } else {
        const result = await createRecommendation(body);
        id = result.id;
      }

      await refreshList();
      setSelectedId(id);
      return id;
    },
    [refreshList],
  );

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

  const handleSubmitFeedback = useCallback(
    async (body: { item_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)));
    },
    [],
  );

  const updateTitle = useCallback((id: string, title: string) => {
    setList((prev) => prev.map((r) => (r.id === id ? { ...r, title } : r)));
  }, []);

  const deleteRec = useCallback(async (id: string) => {
    await deleteRecommendation(id);
    setList((prev) => prev.filter((r) => r.id !== id));
  }, []);

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