import { Link } from 'react-router-dom'
import { Check, ChevronRight } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { OnboardingStatus } from '@/api/onboarding'
import { useTrialBanner } from '@/hooks/useTrialBanner'
import type { TrialBannerStage } from '@/hooks/useTrialBanner'
import { useOnboardingStatus } from '@/hooks/useOnboardingStatus'
import { FOCUS_START_SESSION_EVENT } from '@/components/dashboard/StartSessionInput'

/**
 * Unified setup checklist — single list (no SOLO/TEAM bifurcation).
 *
 * Replaces the old `OnboardingChecklist` widget. Items match `NextStepCard`'s
 * priority order. The "Pick a plan" item is gated on the trial stage.
 *
 * Surfaced behind a "Show all setup steps" toggle on the dashboard so the
 * always-visible surface is just the single next-step card.
 */

interface ChecklistItem {
  key: string
  label: string
  path: string
  done: boolean
}

const PLAN_GATE_STAGES: ReadonlyArray<TrialBannerStage> = [
  'warning',
  'urgent',
  'expired',
]

// eslint-disable-next-line react-refresh/only-export-components -- pure helper exported for focused unit tests
export function buildChecklistItems(
  status: OnboardingStatus,
  trialStage: TrialBannerStage | null,
): ChecklistItem[] {
  const items: ChecklistItem[] = [
    {
      key: 'verify_email',
      label: 'Verify your email',
      path: '/verify-email',
      done: status.email_verified,
    },
    {
      key: 'shop_setup',
      label: 'Set up your shop',
      path: '/welcome/step-1',
      done: status.shop_setup_done,
    },
    {
      key: 'ran_session',
      label: 'Run your first FlowPilot session',
      path: '/',
      done: status.ran_session,
    },
    {
      key: 'connected_psa',
      label: 'Connect your PSA',
      path: '/account/integrations',
      done: status.connected_psa,
    },
    {
      key: 'invited_teammate',
      label: 'Invite a teammate',
      path: '/account',
      done: status.invited_teammate,
    },
  ]

  if (trialStage && PLAN_GATE_STAGES.includes(trialStage)) {
    items.push({
      key: 'pick_plan',
      label: 'Pick a plan',
      path: '/account/billing/select-plan',
      done: false,
    })
  }

  return items
}

export function SetupChecklist() {
  const status = useOnboardingStatus()
  const { stage } = useTrialBanner()

  if (!status || status.dismissed) return null

  const items = buildChecklistItems(status, stage)
  const completedCount = items.filter((i) => i.done).length
  const totalCount = items.length

  return (
    <div className="card-interactive overflow-hidden" data-testid="setup-checklist">
      <div className="px-4 pt-3 pb-2">
        <p className="font-sans text-[0.625rem] uppercase tracking-[0.12em] font-semibold text-muted-foreground">
          Setup steps · {completedCount} of {totalCount}
        </p>
      </div>
      <ul className="px-2 pb-2 space-y-1">
        {items.map((item) => (
          <li key={item.key}>
            {item.done ? (
              <div
                className="w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm cursor-default"
                data-testid={`checklist-item-${item.key}`}
                data-done="true"
              >
                <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md border border-transparent bg-primary">
                  <Check size={12} className="text-white" />
                </span>
                <span className="flex-1 text-muted-foreground line-through">
                  {item.label}
                </span>
              </div>
            ) : item.key === 'ran_session' ? (
              <button
                type="button"
                onClick={() => window.dispatchEvent(new Event(FOCUS_START_SESSION_EVENT))}
                className={cn(
                  'w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors text-left',
                  'hover:bg-[rgba(255,255,255,0.04)]',
                )}
                data-testid={`checklist-item-${item.key}`}
                data-done="false"
              >
                <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md border border-border" />
                <span className="flex-1 text-foreground">{item.label}</span>
                <ChevronRight size={14} className="text-muted-foreground shrink-0" />
              </button>
            ) : (
              <Link
                to={item.path}
                className={cn(
                  'w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors text-left',
                  'hover:bg-[rgba(255,255,255,0.04)]',
                )}
                data-testid={`checklist-item-${item.key}`}
                data-done="false"
              >
                <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md border border-border" />
                <span className="flex-1 text-foreground">{item.label}</span>
                <ChevronRight size={14} className="text-muted-foreground shrink-0" />
              </Link>
            )}
          </li>
        ))}
      </ul>
    </div>
  )
}

export default SetupChecklist
