'use client';

import { motion, useReducedMotion } from 'framer-motion';
import { ArrowRight, Check } from 'lucide-react';
import Link from 'next/link';

import { buttonVariants } from '@/components/ui/button';
import { cn } from '@/lib/utils';

const items = [
  { key: 'emailVerified', label: 'Verify your email', text: 'Confirm your address to unlock label purchases.', href: '/verify-email/pending', action: 'Resend email' },
  { key: 'hasSenderAddress', label: 'Add a sender address', text: 'Where your parcels are picked up from.', href: '/shipments/new', action: 'Add address' },
  { key: 'hasFunds', label: 'Top up your wallet', text: 'Labels are paid from your prepaid balance.', href: '/wallet', action: 'Top up' },
  { key: 'hasShipment', label: 'Create your first shipment', text: 'Compare couriers and buy a label.', href: '/shipments/new', action: 'Create shipment' },
] as const;

const R = 30;
const CIRCUMFERENCE = 2 * Math.PI * R;

function ProgressRing({ done, total }: { done: number; total: number }) {
  const reduce = useReducedMotion();
  const fraction = total === 0 ? 0 : done / total;
  return (
    <div className="relative grid h-[72px] w-[72px] shrink-0 place-items-center" role="img" aria-label={`${done} of ${total} steps done`}>
      <svg viewBox="0 0 72 72" className="absolute inset-0 -rotate-90" aria-hidden="true">
        <circle cx="36" cy="36" r={R} fill="none" className="stroke-surface-muted" strokeWidth="6" />
        <motion.circle
          cx="36"
          cy="36"
          r={R}
          fill="none"
          className="stroke-primary"
          strokeWidth="6"
          strokeLinecap="round"
          strokeDasharray={CIRCUMFERENCE}
          initial={{ strokeDashoffset: reduce ? CIRCUMFERENCE * (1 - fraction) : CIRCUMFERENCE }}
          animate={{ strokeDashoffset: CIRCUMFERENCE * (1 - fraction) }}
          transition={{ duration: reduce ? 0 : 0.8, ease: [0.2, 0.8, 0.2, 1] }}
        />
      </svg>
      <span className="font-display text-h3 font-extrabold tabular-nums" aria-hidden="true">
        {done}/{total}
      </span>
    </div>
  );
}

export function OnboardingChecklist({
  progress,
}: {
  progress: { emailVerified: boolean; hasSenderAddress: boolean; hasFunds: boolean; hasShipment: boolean };
}) {
  const done = items.filter((item) => progress[item.key]).length;
  const currentIndex = items.findIndex((item) => !progress[item.key]);
  return (
    <section className="gradient-border rounded-xl p-5 shadow-sm md:p-6" aria-labelledby="onboarding-title">
      <div className="grid gap-6 lg:grid-cols-[minmax(0,2fr)_minmax(0,3fr)] lg:gap-10">
        <div className="flex items-start gap-4">
          <ProgressRing done={done} total={items.length} />
          <div>
            <h2 id="onboarding-title" className="font-display text-h2 font-bold">
              Get ready to ship
            </h2>
            <p className="mt-1 max-w-sm text-small text-muted-foreground">
              A few quick steps and you can buy your first label. Most teams finish in under five minutes.
            </p>
          </div>
        </div>
        <ol className="relative grid gap-1">
          {items.map((item, index) => {
            const complete = progress[item.key];
            const current = index === currentIndex;
            return (
              <li
                key={item.key}
                className={cn('relative flex items-start gap-3 rounded-lg px-3 py-2.5', current && 'bg-primary-soft')}
                aria-current={current ? 'step' : undefined}
              >
                {index < items.length - 1 ? <span className="absolute left-[23px] top-9 h-[calc(100%-20px)] w-px bg-border-strong" aria-hidden="true" /> : null}
                <span
                  className={cn(
                    'relative z-[1] mt-0.5 grid h-6 w-6 shrink-0 place-items-center rounded-full text-caption font-bold',
                    complete && 'bg-success text-primary-foreground',
                    current && 'bg-primary text-primary-foreground ring-4 ring-primary/15',
                    !complete && !current && 'border border-border-strong bg-surface text-subtle-foreground',
                  )}
                  aria-hidden="true"
                >
                  {complete ? <Check className="h-3.5 w-3.5" strokeWidth={3} /> : index + 1}
                </span>
                <div className="min-w-0 flex-1">
                  <p className={cn('text-small font-semibold', complete ? 'text-muted-foreground' : current ? 'text-foreground' : 'text-muted-foreground')}>
                    {item.label}
                    {complete ? <span className="sr-only"> (done)</span> : null}
                  </p>
                  {current ? <p className="mt-0.5 text-caption text-muted-foreground">{item.text}</p> : null}
                </div>
                {current ? (
                  <Link href={item.href} className={cn(buttonVariants({ size: 'sm' }), 'group shrink-0')}>
                    {item.action}
                    <ArrowRight className="h-3.5 w-3.5 transition-transform group-hover:translate-x-0.5" aria-hidden="true" />
                  </Link>
                ) : null}
              </li>
            );
          })}
        </ol>
      </div>
    </section>
  );
}
