"use client";

import { useState, useEffect, useCallback } from "react";
import {
  getUpcomingRecurringCandidates,
  setRecurringCandidateDecision,
} from "@/lib/api";
import type { RecurringCandidateItem } from "@/types/api";
import { useToast } from "@/store/toast.store";

export function useUpcomingRecurringCandidates(options: { autoFetch?: boolean } = {}) {
  const { autoFetch = true } = options;
  const [candidates, setCandidates] = useState<RecurringCandidateItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const toast = useToast();

  const fetchUpcoming = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await getUpcomingRecurringCandidates();
      if (res.success && Array.isArray(res.data)) {
        setCandidates(res.data);
      } else {
        setCandidates([]);
      }
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Failed to load upcoming recurring candidates";
      console.error("Failed to fetch upcoming recurring candidates", err);
      setError(msg);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    let ignore = false;
    if (autoFetch) {
      getUpcomingRecurringCandidates()
        .then((res) => {
          if (!ignore && res.success && Array.isArray(res.data)) {
            setCandidates(res.data);
          }
        })
        .catch((err: unknown) => {
          if (!ignore) {
            const msg = err instanceof Error ? err.message : "Failed to load upcoming recurring candidates";
            setError(msg);
          }
        });
    }
    return () => {
      ignore = true;
    };
  }, [autoFetch]);

  const updateCandidateDecision = useCallback(
    async (candidateId: number, action: "on" | "off", applyToSeries?: boolean) => {
      try {
        const res = await setRecurringCandidateDecision(candidateId, {
          action,
          ...(action === "on" && applyToSeries !== undefined ? { apply_to_series: applyToSeries } : {}),
        });

        if (res.success) {
          const updatedSeriesAuto = res.data.series_auto_schedule;
          const updatedToggle = res.data.app_toggle_enabled;

          const current = candidates.find((c) => c.candidate_id === candidateId);
          const seriesId = current?.recurring_series_id;

          setCandidates((prev) =>
            prev.map((c) => {
              if (c.candidate_id === candidateId) {
                return {
                  ...c,
                  app_toggle_enabled: updatedToggle,
                  series_auto_schedule:
                    updatedSeriesAuto !== undefined ? updatedSeriesAuto : c.series_auto_schedule,
                };
              }
              if (
                seriesId &&
                c.recurring_series_id === seriesId &&
                (applyToSeries || updatedSeriesAuto)
              ) {
                return {
                  ...c,
                  series_auto_schedule:
                    updatedSeriesAuto !== undefined ? updatedSeriesAuto : true,
                  ...(action === "on" && applyToSeries ? { app_toggle_enabled: true } : {}),
                };
              }
              return c;
            })
          );
          return { success: true, data: res.data };
        } else {
          toast.error("Failed to update candidate decision", res.message);
          return { success: false, error: res.message };
        }
      } catch (err: unknown) {
        const msg = err instanceof Error ? err.message : "Network error";
        toast.error("Error setting decision", msg);
        return { success: false, error: msg };
      }
    },
    [candidates, toast]
  );

  return {
    candidates,
    loading,
    error,
    refetch: fetchUpcoming,
    updateCandidateDecision,
  };
}
