import { useEffect, useMemo, useRef } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Loader2 } from "lucide-react";
import { toast } from "sonner";
import type { ApplicationItem } from "@/data/mockApplications";
import { getResumeApplicantDashboardHref } from "@/lib/applicantRegistrationSession";
import { createApplicantApplication } from "@/lib/applicantApplicationsApi";
import { resolveApplicationDraftCaseId } from "@/lib/resolveApplicationDraftCaseId";
import { syncApplicantSubmissionFromApplicationItem } from "@/lib/applicantSubmissionRecord";

function normalizeItem(row: ApplicationItem & { draft_case_id?: string }): ApplicationItem {
  const fromSnake = typeof row.draft_case_id === "string" ? row.draft_case_id.trim() : "";
  const fromCamel = row.draftCaseId?.trim() ?? "";
  const draftCaseId = fromCamel || fromSnake || undefined;
  return { ...row, draftCaseId };
}

export default function RenewFormPanel() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const requestedRef = useRef(false);

  const returnTo = useMemo(() => {
    const raw = searchParams.get("returnTo") ?? "/dashboard";
    return raw.startsWith("/dashboard") ? raw : "/dashboard";
  }, [searchParams]);

  useEffect(() => {
    if (requestedRef.current) return;
    requestedRef.current = true;

    void (async () => {
      try {
        const created = await createApplicantApplication();
        const row = created.application;
        if (!row) throw new Error("Không nhận được dữ liệu hồ sơ mới từ máy chủ.");
        const normalized = normalizeItem(row as ApplicationItem & { draft_case_id?: string });
        syncApplicantSubmissionFromApplicationItem(normalized);
        const caseId = resolveApplicationDraftCaseId(normalized);
        if (!caseId) throw new Error("Không nhận được mã bản nháp (case) từ máy chủ.");
        navigate(getResumeApplicantDashboardHref(caseId), { replace: true });
      } catch (error) {
        toast.error(error instanceof Error ? error.message : "Không thể tạo hồ sơ mới.");
        navigate(`/dashboard/documents?returnTo=${encodeURIComponent(returnTo)}`, { replace: true });
      }
    })();
  }, [navigate, returnTo]);

  return (
    <div className="h-[calc(100vh-4rem)] flex items-center justify-center">
      <div className="flex items-center gap-2 text-sm text-muted-foreground">
        <Loader2 className="h-4 w-4 animate-spin" />
        Đang tạo hồ sơ mới...
      </div>
    </div>
  );
}
