"use client";

import { useEffect, useState } from "react";
import type { OpportunityDetails } from "./learnServeFormTypes";

/** localStorage keys for a create that has not been finished yet. */
const OPPORTUNITY_ID_KEY = "learnServe_opportunityId";
const OPPORTUNITY_DETAILS_KEY = "learnServe_opportunityDetails";

/**
 * The id and schedule of the opportunity being worked on.
 *
 * Publishing is two steps — create the opportunity, then attach its timings —
 * and the second step needs the first one's id. If the organizer closes the tab
 * in between, that id is the only way back to a half-published record, so the
 * create flow keeps it in `localStorage` along with the schedule the timings
 * editor is anchored to.
 *
 * Editing needs none of that: the id is in the URL and the schedule is on the
 * record, so both come straight from the loaded opportunity and nothing is
 * persisted. A repost is treated as a create, because it produces a new record.
 */
export function useInProgressOpportunity({
  navState,
  id,
  isRepublish,
  opportunityData,
}: {
  /** `null` until the stashed navigation payload has been read. */
  navState: unknown;
  id?: string;
  isRepublish?: boolean;
  opportunityData?: {
    start_date?: string | null;
    end_date?: string | null;
    start_time?: string | null;
    end_time?: string | null;
  } | null;
}) {
  const [opportunityId, setOpportunityId] = useState<number | null>(null);
  const [opportunityDetails, setOpportunityDetails] = useState<OpportunityDetails>(
    { startDate: "", endDate: "", startTime: "", endTime: "" }
  );

  /*
   * Seeding, not synchronising.
   *
   * Both values are real state — the timings editor writes them through the
   * setters returned below — so they cannot be derived. What the three effects
   * this replaces actually did was *seed* them from whichever source applies
   * once that source was readable, and React's documented adjust-on-change
   * pattern expresses that without a committed intermediate render
   * (react.dev/learn/you-might-not-need-an-effect).
   *
   * Reading `localStorage` here is safe despite being inside a render: the
   * guard is `navState !== null`, and `navState` is `null` through the server
   * render and the first client render (`useNavState` fills it on mount), so
   * the read only ever happens after hydration. It is also idempotent, which
   * matters because React discards and re-runs the render that calls a setter.
   *
   * Keying on the full `(id, isRepublish)` tuple rather than a one-shot flag
   * keeps the old dependency lists: navigating straight from one editor to
   * another without unmounting re-seeds, exactly as the effects did.
   */
  const seedKey =
    navState === null ? null : `${id ?? ""}|${isRepublish ? 1 : 0}`;
  const [seededKey, setSeededKey] = useState<string | null>(null);
  if (seedKey !== null && seedKey !== seededKey) {
    setSeededKey(seedKey);
    if (id && !isRepublish) {
      setOpportunityId(Number(id));
    } else {
      const savedId = localStorage.getItem(OPPORTUNITY_ID_KEY);
      setOpportunityId(savedId ? Number(savedId) : null);
    }
    // Restore the in-progress schedule for a create flow.
    if (!id) {
      const savedDetails = localStorage.getItem(OPPORTUNITY_DETAILS_KEY);
      if (savedDetails) {
        try {
          setOpportunityDetails(JSON.parse(savedDetails));
        } catch {
          // A malformed entry is not worth blocking the form over
        }
      }
    }
  }

  /*
   * Editing takes its schedule straight from the loaded opportunity. Keyed on
   * the payload's identity, which is what the effect depended on — so a
   * refetch still re-seeds the schedule from the server, overwriting whatever
   * the organizer had typed. That is pre-existing behaviour and is left as
   * it was; React Query is configured with a 1-minute `staleTime` and no
   * refetch on focus, so in practice it happens on remount and invalidation.
   */
  const editSeed = id && opportunityData && !isRepublish ? opportunityData : null;
  const [seededEdit, setSeededEdit] = useState<typeof editSeed>(null);
  if (editSeed !== null && editSeed !== seededEdit) {
    setSeededEdit(editSeed);
    setOpportunityDetails({
      startDate: editSeed.start_date || "",
      endDate: editSeed.end_date || "",
      startTime: editSeed.start_time?.slice(0, 5) || "",
      endTime: editSeed.end_time?.slice(0, 5) || "",
    });
  }

  useEffect(() => {
    if (opportunityId) {
      localStorage.setItem(OPPORTUNITY_ID_KEY, opportunityId.toString());
    }
  }, [opportunityId]);

  useEffect(() => {
    // Only the create flow needs its progress persisted
    if (id) return;
    localStorage.setItem(
      OPPORTUNITY_DETAILS_KEY,
      JSON.stringify(opportunityDetails)
    );
  }, [opportunityDetails, id]);

  return {
    opportunityId,
    setOpportunityId,
    opportunityDetails,
    setOpportunityDetails,
  };
}
