"use client";

import { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "@/app/components/LocaleLink";
import toast from "react-hot-toast";

import { getProfileProgress, submitAstrologerProfile,
  friendlyErrorMessage,
} from "@/app/lib/astrologer";
import {
  STEP_ROUTES,
  EDIT_STEP_ROUTES,
  TOTAL_STEPS,
  getNextStepRoute,
  ProfileProgress,
} from "@/app/lib/astrologerSteps";

function ProfileProgressContent() {
  const router = useRouter();
  const params = useSearchParams();

  // ?view=1 shows the checklist instead of auto-redirecting to the
  // next incomplete step — used when linking here from the Profile hub.
  const viewOnly = params.get("view") === "1";

  const [progress, setProgress] = useState<ProfileProgress | null>(
    null
  );
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    const token = localStorage.getItem("astrologerToken");

    if (!token) {
      router.replace("/astrologer/signin");
      return;
    }

    const load = async () => {
      try {
        const response = await getProfileProgress(token);

        if (!response.success) {
          toast.error(
            response.message || "Unable to load your profile progress."
          );
          setLoading(false);
          return;
        }

        const data: ProfileProgress = response.data ?? response;

        setProgress(data);
        setLoading(false);

        // Not viewOnly -> this page is purely a router: resume at the
        // pending step, land on Under Review, or the profile hub, per
        // getNextStepRoute's next_screen-driven decision. ?view=1
        // (from the Profile hub's "View profile progress" link) is
        // the only way to see the checklist without being bounced
        // onward, EXCEPT once every step is done but nothing has been
        // submitted yet — stay put so Submit Profile is reachable
        // (matches the "Profile Setup Steps" mockup).
        const notYetSubmitted =
          data.is_profile_completed &&
          data.next_screen !== "profile_under_review" &&
          !["PENDING", "APPROVED"].includes(
            (data.admin_status || "").toUpperCase()
          );

        if (!viewOnly && !notYetSubmitted) {
          router.replace(getNextStepRoute(data));
        }
      } catch {
        toast.error("Unable to load your profile progress.");
        setLoading(false);
      }
    };

    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSubmit = async () => {
    const token = localStorage.getItem("astrologerToken");

    if (!token) {
      router.replace("/astrologer/signin");
      return;
    }

    try {
      setSubmitting(true);

      const response = await submitAstrologerProfile(token);

      if (!response.success) {
        toast.error(friendlyErrorMessage(response.message, "Unable to submit your profile."));
        return;
      }

      // One-time Thank You screen — the flag is consumed on first view.
      try {
        sessionStorage.setItem("astrologerProfileSubmittedThankYou", "1");
      } catch {
        // Without sessionStorage the thank-you page just redirects on.
      }

      router.push("/astrologer/profile/thank-you");
    } catch (error: any) {
      toast.error(
        error.response?.data?.message ?? "Unable to submit your profile."
      );
    } finally {
      setSubmitting(false);
    }
  };

  const isRedirecting =
    !viewOnly && progress && !progress.is_profile_completed;

  if (loading || isRedirecting) {
    return (
      <section className="py-5 d-flex align-items-center justify-content-center min-vh-100">
        <p className="text-white">Loading your profile...</p>
      </section>
    );
  }

  if (!progress) {
    return (
      <section className="py-5 d-flex align-items-center justify-content-center min-vh-100">
        <p className="text-white">
          Unable to load your profile progress.
        </p>
      </section>
    );
  }

  const completed = progress.steps.filter((s) => s.completed).length;

  const notYetSubmitted =
    progress.is_profile_completed &&
    progress.next_screen !== "profile_under_review" &&
    !["PENDING", "APPROVED"].includes(
      (progress.admin_status || "").toUpperCase()
    );

  const nextRoute = getNextStepRoute(progress);

  // Once the profile is fully done (approved, under review, or just
  // finished but not yet submitted), revisiting a step from this
  // checklist means editing it — otherwise the astrologer is still
  // mid-registration and should land back on the same wizard step.
  const stepRoutes = progress.is_profile_completed ? EDIT_STEP_ROUTES : STEP_ROUTES;

  return (
    <section className="astrologer-wizard-page" style={{ paddingTop: "120px", paddingBottom: "120px" }}>
      <div className="container">
        <div className="row justify-content-center">
          <div className="col-lg-6">
            <div className="card card-bg-primary border-0 rounded-4 mb-4">
              <div className="card-body p-4 d-flex align-items-center gap-4">
                <div className="astrologer-progress-ring-wrap">
                  <svg
                    viewBox="0 0 100 100"
                    className="astrologer-progress-ring"
                  >
                    <circle
                      cx="50"
                      cy="50"
                      r="42"
                      className="astrologer-progress-ring-bg"
                    />
                    <circle
                      cx="50"
                      cy="50"
                      r="42"
                      className="astrologer-progress-ring-fg"
                      style={{
                        strokeDasharray: `${
                          2 * Math.PI * 42
                        }`,
                        strokeDashoffset: `${
                          2 *
                          Math.PI *
                          42 *
                          (1 - progress.completion_percentage / 100)
                        }`,
                      }}
                    />
                  </svg>
                  <div className="astrologer-progress-ring-label">
                    <strong>
                      {progress.completion_percentage}%
                    </strong>
                    <span>completion</span>
                  </div>
                </div>

                <div>
                  <div className="terms-text-color text-uppercase small">
                    Profile status
                  </div>
                  <span className="badge bg-warning text-dark mb-2">
                    {progress.profile_status}
                  </span>

                  <div className="terms-text-color text-uppercase small mt-2">
                    Current step
                  </div>
                  <div className="text-white fw-semibold">
                    {Math.min(progress.current_step + 1, TOTAL_STEPS)} of{" "}
                    {TOTAL_STEPS}
                  </div>
                </div>
              </div>
            </div>

            <h5 className="text-white mb-1">Profile Setup Steps</h5>
            <p className="terms-text-color mb-3">
              {progress.is_profile_completed
                ? "Great! You have completed all the steps."
                : `${completed} of ${TOTAL_STEPS} steps completed.`}
            </p>

            <div className="card card-bg-primary border-0 rounded-4 mb-4">
              <div className="card-body p-2">
                {progress.steps
                  .slice()
                  .sort((a, b) => a.step - b.step)
                  .map((s) => (
                    <Link
                      key={s.step}
                      href={stepRoutes[s.step] ?? "#"}
                      className="astrologer-step-row"
                    >
                      <span className="astrologer-step-row-index">
                        {s.step}
                      </span>

                      <span className="astrologer-step-row-title">
                        {s.title}
                      </span>

                      <span
                        className={`astrologer-step-row-status ${
                          s.completed ? "is-complete" : ""
                        }`}
                      >
                        {s.completed ? "✓" : ""}
                      </span>
                    </Link>
                  ))}
              </div>
            </div>

            {notYetSubmitted ? (
              <button
                type="button"
                className="btn btn-primary py-3 w-100"
                onClick={handleSubmit}
                disabled={submitting}
              >
                {submitting ? "Submitting..." : "Submit Profile"}
              </button>
            ) : (
              <Link
                href={nextRoute}
                className="btn btn-primary py-3 w-100"
              >
                {nextRoute === "/astrologer/profile/review"
                  ? "View status"
                  : nextRoute === "/astrologer/dashboard"
                  ? "Go to your dashboard"
                  : "Continue"}
              </Link>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

export default function AstrologerProfileProgressPage() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <ProfileProgressContent />
    </Suspense>
  );
}
