import { useQuery } from "@tanstack/react-query";
import { Link } from "react-router-dom";
import { AlertTriangle, ArrowRight, Clock } from "lucide-react";
import { api } from "@/services/api";
import useAuth from "@/hooks/useAuth";
import type { OnboardingRequirements } from "@/services/companies.service";

interface OnboardingResumeBannerProps {
  /** Re-opens the onboarding wizard. */
  onResume: () => void;
}

interface BannerCopy {
  title: string;
  subtitle: string;
  cta: string;
}

/**
 * Wording is driven entirely by the backend's outstanding-items list — the
 * client never decides what's required, it just narrates what's left.
 */
function getCopy(
  requirements: OnboardingRequirements | undefined,
  pct: number,
): BannerCopy {
  // No data yet (or nothing started) — treat it as a fresh start.
  if (!requirements || requirements.progress.completed === 0) {
    return {
      title: "Set up your company profile",
      subtitle: "Unlock bookings, tracking and billing — it only takes a minute.",
      cta: "Start onboarding",
    };
  }

  // Everything's filled in but not yet submitted for review.
  if (requirements.isComplete) {
    return {
      title: "Everything's ready to go",
      subtitle: "Submit your profile to send it for approval.",
      cta: "Submit for review",
    };
  }

  const remaining = requirements.outstanding.length;
  if (remaining <= 2) {
    return {
      title: `Almost done — you're ${pct}% set up`,
      subtitle: `Just ${remaining} more ${
        remaining === 1 ? "item" : "items"
      } to finish: ${requirements.outstanding.join(", ")}.`,
      cta: "Finish onboarding",
    };
  }

  return {
    title: `You're ${pct}% set up`,
    subtitle: `${requirements.progress.completed} of ${requirements.progress.total} details added — finish to unlock bookings, tracking and billing.`,
    cta: "Continue onboarding",
  };
}

/** Circular percentage meter that reads at a glance against the dark banner. */
function ProgressRing({ pct }: { pct: number }) {
  const size = 56;
  const stroke = 5;
  const r = (size - stroke) / 2;
  const circumference = 2 * Math.PI * r;
  const offset = circumference * (1 - pct / 100);

  return (
    <span className="relative flex shrink-0 items-center justify-center">
      <svg width={size} height={size} className="-rotate-90">
        <circle
          cx={size / 2}
          cy={size / 2}
          r={r}
          fill="none"
          stroke="rgba(255,255,255,0.22)"
          strokeWidth={stroke}
        />
        <circle
          cx={size / 2}
          cy={size / 2}
          r={r}
          fill="none"
          stroke="#6ee7b7"
          strokeWidth={stroke}
          strokeLinecap="round"
          strokeDasharray={circumference}
          strokeDashoffset={offset}
          style={{ transition: "stroke-dashoffset 600ms ease" }}
        />
      </svg>
      <span className="absolute text-sm font-bold text-white">{pct}%</span>
    </span>
  );
}

/**
 * Prominent banner shown on onboarding-allowed pages after the wizard is
 * dismissed. Progress and copy are read straight from the backend's onboarding
 * requirements, so the banner always agrees with the wizard about what's left.
 */
export default function OnboardingResumeBanner({
  onResume,
}: OnboardingResumeBannerProps) {
  const requirementsQuery = useQuery(
    api.companies.onboardingRequirements.queryOptions({ retry: false }),
  );

  const requirements = requirementsQuery.data;
  const { completed, total } = requirements?.progress ?? {
    completed: 0,
    total: 0,
  };
  const pct = total > 0 ? Math.round((completed / total) * 100) : 0;
  const { title, subtitle, cta } = getCopy(requirements, pct);

  return (
    <div className="bg-gradient-to-r from-[#065f46] via-[#0A6F4D] to-[#0A8A5F] px-6 py-4 shadow-md">
      <div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-4">
        <div className="flex items-center gap-4">
          <ProgressRing pct={pct} />
          <span className="flex flex-col gap-0.5">
            <span className="flex items-center gap-2">
              <span className="relative flex h-2 w-2">
                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-[#6ee7b7] opacity-75" />
                <span className="relative inline-flex h-2 w-2 rounded-full bg-[#6ee7b7]" />
              </span>
              <span className="text-base font-bold tracking-tight text-white">
                {title}
              </span>
            </span>
            <span className="text-sm text-white/80">{subtitle}</span>
          </span>
        </div>
        <button
          type="button"
          onClick={onResume}
          className="inline-flex items-center gap-2 rounded-lg bg-white px-5 py-2.5 text-sm font-semibold text-[#0A6F4D] shadow-sm transition-transform hover:scale-[1.02] hover:bg-white/95"
        >
          {cta}
          <ArrowRight size={16} />
        </button>
      </div>
    </div>
  );
}

/**
 * Post-onboarding review banner. Surfaces (in priority order):
 *  1. A pending profile-edit review — the whole account is locked until an admin
 *     approves the submitted changes.
 *  2. A rejected profile-edit review — links to Settings to amend & resubmit.
 *  3. Per-operational-profile approval — bookings unlock as each role clears.
 * Self-hides when there's nothing outstanding.
 */
export function AccountReviewBanner() {
  const { company, reviewStatus, reviewNote } = useAuth();
  const profiles = company?.company?.companyProfiles ?? [];
  const pending = profiles.filter((p) => p.status === "pending");
  const approved = profiles.filter((p) => p.status === "active");

  // 1. Profile-edit review pending — the account-wide lock.
  if (reviewStatus === "pending") {
    return (
      <div className="border-b border-amber-200 bg-amber-50 px-6 py-3">
        <div className="mx-auto flex max-w-6xl items-center gap-3">
          <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-700">
            <Clock size={18} />
          </span>
          <span className="flex flex-col gap-0.5">
            <span className="text-sm font-semibold text-amber-900">
              Your profile changes are under review
            </span>
            <span className="text-xs text-amber-800">
              Editing and creating new contracts or bookings is paused until an
              administrator approves your submitted changes.
            </span>
          </span>
        </div>
      </div>
    );
  }

  // 2. Profile-edit review rejected — prompt to fix & resubmit.
  if (reviewStatus === "rejected") {
    return (
      <div className="border-b border-red-200 bg-red-50 px-6 py-3">
        <div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3">
          <div className="flex items-center gap-3">
            <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-red-100 text-red-700">
              <AlertTriangle size={18} />
            </span>
            <span className="flex flex-col gap-0.5">
              <span className="text-sm font-semibold text-red-900">
                Your recent changes were not approved
              </span>
              <span className="text-xs text-red-800">
                {reviewNote
                  ? `Reviewer note: ${reviewNote}`
                  : "Please update your details and resubmit for review."}
              </span>
            </span>
          </div>
          <Link
            to="/settings"
            className="inline-flex items-center gap-2 rounded-lg bg-red-600 px-4 py-2 text-sm font-semibold text-white shadow-sm transition-transform hover:scale-[1.02]"
          >
            Review &amp; resubmit
            <ArrowRight size={16} />
          </Link>
        </div>
      </div>
    );
  }

  // 3. Per-operational-profile approval (existing behaviour).
  if (profiles.length === 0 || pending.length === 0) return null;

  const pendingLabel = pending
    .map((p) => p.type.replace(/_/g, " "))
    .join(", ");

  return (
    <div className="border-b border-amber-200 bg-amber-50 px-6 py-3">
      <div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-700">
            <Clock size={18} />
          </span>
          <span className="flex flex-col gap-0.5">
            <span className="text-sm font-semibold text-amber-900">
              Your account is under review
            </span>
            <span className="text-xs text-amber-800">
              We're reviewing your {pendingLabel}{" "}
              {pending.length === 1 ? "profile" : "profiles"}. You can create
              bookings under a profile as soon as it's approved.
            </span>
          </span>
        </div>
        <span className="text-xs font-medium text-amber-800">
          {approved.length} of {profiles.length} approved
        </span>
      </div>
    </div>
  );
}
