"use client";

import { use, useEffect, useState } from "react";
import { TemplateReviewCard } from "../../../../components/cards/TemplateReviewCard";
import { useTranslation } from "../../../../contexts/MessagesContext";
import {
  fetchTemplateBySlug,
  isTemplatesFetchAborted,
  type RuleTemplateDto,
} from "../../../../../lib/create/fetchTemplates";
import messages from "../../../../../messages/en/index";
import Alert from "../../../../components/modals/Alert";
import {
  CREATE_FLOW_REVIEW_RULE_LAYOUT_CLASS,
  CreateFlowLockupCardStepShell,
} from "../../components/CreateFlowLockupCardStepShell";
import { CreateFlowStepShell } from "../../components/CreateFlowStepShell";
import {
  CREATE_FLOW_MD_UP_COLUMN_MAX_CLASS,
  CREATE_FLOW_MD_CENTERED_SHELL_CLASS,
} from "../../components/createFlowLayoutTokens";
import { useCreateFlowMdUp } from "../../hooks/useCreateFlowMdUp";

interface PageProps {
  params: Promise<{ slug: string }>;
}

/** Template review — lockup + card, vertically centered (Figma `22142-898702`). */
export default function ReviewTemplatePage({ params }: PageProps) {
  const { slug: rawSlug } = use(params);
  const slug = decodeURIComponent(rawSlug);
  const mdUp = useCreateFlowMdUp();
  const t = useTranslation("create.templateReview");

  const [template, setTemplate] = useState<RuleTemplateDto | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const ac = new AbortController();
    let cancelled = false;
    void (async () => {
      if (!cancelled) {
        setLoading(true);
        setError(null);
      }
      try {
        const result = await fetchTemplateBySlug(slug, {
          signal: ac.signal,
        });
        if (cancelled) return;
        if (result === null) {
          setError(messages.create.templateReview.errors.notFound);
          setTemplate(null);
        } else if ("error" in result) {
          setError(result.error);
          setTemplate(null);
        } else {
          setTemplate(result);
          setError(null);
        }
      } catch (e) {
        if (cancelled || isTemplatesFetchAborted(e)) return;
        setError(messages.create.templateReview.errors.loadFailed);
        setTemplate(null);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
      ac.abort();
    };
  }, [slug]);

  if (loading) {
    return (
      <CreateFlowStepShell
        variant="wideGrid"
        contentTopBelowMd="space-800"
        className={CREATE_FLOW_MD_CENTERED_SHELL_CLASS}
      >
        <div
          className={`flex shrink-0 items-center justify-start pb-16 ${CREATE_FLOW_MD_UP_COLUMN_MAX_CLASS}`}
        >
          <p className="text-[var(--color-content-default-secondary,#a3a3a3)]">
            {t("loading")}
          </p>
        </div>
      </CreateFlowStepShell>
    );
  }

  if (error || !template) {
    return (
      <>
        <div
          className="pointer-events-none fixed left-0 right-0 top-14 z-[120] flex justify-center px-5 pt-3 md:top-20 md:px-12"
          aria-live="polite"
        >
          <div className="pointer-events-auto w-full max-w-[960px]">
            <Alert
              type="banner"
              status="danger"
              title={t("errors.loadFailed")}
              description={error ?? t("errors.notFound")}
              className="w-full"
            />
          </div>
        </div>
        <CreateFlowStepShell
          variant="wideGrid"
          contentTopBelowMd="space-800"
          className={CREATE_FLOW_MD_CENTERED_SHELL_CLASS}
        >
          <div
            className={`min-h-[40vh] shrink-0 ${CREATE_FLOW_MD_UP_COLUMN_MAX_CLASS}`}
            aria-hidden
          />
        </CreateFlowStepShell>
      </>
    );
  }

  return (
    <CreateFlowLockupCardStepShell
      lockupTitle={t("intro.title")}
      lockupDescription={t("intro.description")}
    >
      <TemplateReviewCard
        template={template}
        ruleCardClassName={CREATE_FLOW_REVIEW_RULE_LAYOUT_CLASS}
        size={mdUp ? "L" : "M"}
      />
    </CreateFlowLockupCardStepShell>
  );
}
