"use client";

import type { Meta, StoryObj } from "@storybook/react";
import { fn } from "@storybook/test";
import { BookOpen, Code2, Users, Zap } from "lucide-react";
import {
	type ProductCategory,
	ProductSelectionStep,
} from "../steps/product-selection-step";
import { type NextStep, SuccessStep } from "../steps/success-step";
import {
	type OnboardingStepConfig,
	OnboardingWizard,
	useOnboarding,
	WizardLayout,
} from "./index";

const meta: Meta<typeof OnboardingWizard> = {
	title: "Widgets/Onboarding/Wizard",
	component: OnboardingWizard,
	parameters: {
		layout: "fullscreen",
	},
};

export default meta;
type Story = StoryObj<typeof OnboardingWizard>;

// =============================================================================
// STEP DATA
// =============================================================================

const businessFunctions: ProductCategory[] = [
	{
		id: "support",
		title: "Customer Support / Ticketing",
		subcategories: ["Helpdesk", "Live Chat", "Ticket Management"],
	},
	{
		id: "crm",
		title: "CRM / Lead Management",
		subcategories: ["Contact Management", "Pipeline Tracking", "Deal Scoring"],
	},
	{
		id: "email",
		title: "Email Marketing / Automation",
		subcategories: ["Campaigns", "Drip Sequences", "Templates"],
	},
	{
		id: "billing",
		title: "Billing / Subscription Management",
		subcategories: ["Invoicing", "Recurring Payments", "Usage Tracking"],
	},
	{
		id: "project",
		title: "Project Management / Task Tracking",
		subcategories: ["Kanban", "Gantt Charts", "Time Tracking"],
	},
	{
		id: "hr",
		title: "HR / Employee Management",
		subcategories: ["Onboarding", "PTO Tracking", "Performance Reviews"],
	},
	{
		id: "inventory",
		title: "Inventory Management",
		subcategories: ["Stock Levels", "Order Fulfillment", "Warehousing"],
	},
	{
		id: "analytics",
		title: "Analytics / Reporting",
		subcategories: ["Dashboards", "Custom Reports", "Data Visualization"],
	},
];

const systems: ProductCategory[] = [
	{
		id: "databases",
		title: "Existing Databases",
		subcategories: ["PostgreSQL", "MySQL", "MongoDB", "Redis"],
	},
	{
		id: "saas",
		title: "Current SaaS Tools",
		subcategories: ["Salesforce", "HubSpot", "Zendesk", "Intercom"],
	},
	{
		id: "internal",
		title: "Internal APIs or Custom Systems",
		subcategories: ["REST APIs", "GraphQL", "Legacy Systems"],
	},
	{
		id: "integrations",
		title: "Third-party Integrations",
		subcategories: ["Stripe", "Slack", "Twilio", "SendGrid"],
	},
];

const nextSteps: NextStep[] = [
	{
		title: "Explore the API documentation",
		description:
			"Learn how to make your first API call and integrate with your application.",
		icon: <BookOpen className="h-5 w-5" />,
		actionText: "View Docs",
		onAction: fn(),
	},
	{
		title: "Generate API keys",
		description:
			"Create your first API key to start making authenticated requests.",
		icon: <Code2 className="h-5 w-5" />,
		actionText: "Generate",
		onAction: fn(),
	},
	{
		title: "Invite your team",
		description: "Add team members to collaborate on this project.",
		icon: <Users className="h-5 w-5" />,
		actionText: "Invite",
		onAction: fn(),
		optional: true,
	},
	{
		title: "Set up webhooks",
		description:
			"Configure real-time notifications for events in your application.",
		icon: <Zap className="h-5 w-5" />,
		actionText: "Configure",
		onAction: fn(),
		optional: true,
	},
];

// =============================================================================
// STEP COMPONENTS (using real step components with useOnboarding hook)
// =============================================================================

function BusinessFunctionStep() {
	const { goNext, goBack, isFirst } = useOnboarding();

	const handleSubmit = async (selectedIds: string[]) => {
		await new Promise((resolve) => setTimeout(resolve, 400));
		fn()(selectedIds);
		goNext();
	};

	return (
		<ProductSelectionStep
			title="What business function do you need?"
			description="Select all the areas where you need API functionality."
			categories={businessFunctions}
			onSubmit={handleSubmit}
			backButton={
				!isFirst
					? {
							text: "Back",
							onClick: goBack,
						}
					: undefined
			}
		/>
	);
}

function SystemsConnectStep() {
	const { goNext, goBack } = useOnboarding();

	const handleSubmit = async (selectedIds: string[]) => {
		await new Promise((resolve) => setTimeout(resolve, 400));
		fn()(selectedIds);
		goNext();
	};

	return (
		<ProductSelectionStep
			title="What systems do you need to connect?"
			description="Select all the systems you want to integrate with."
			categories={systems}
			onSubmit={handleSubmit}
			backButton={{
				text: "Back",
				onClick: goBack,
			}}
		/>
	);
}

function CompleteStep() {
	const { goBack } = useOnboarding();

	return (
		<SuccessStep
			title="You're all set!"
			message="Your project has been created successfully. Here's what you can do next to get the most out of the platform."
			nextSteps={nextSteps}
			primaryAction={{
				text: "Go to Dashboard",
				onClick: () => alert("Going to dashboard!"),
			}}
			secondaryAction={{
				text: "Start Over",
				onClick: goBack,
			}}
		/>
	);
}

// =============================================================================
// STORIES
// =============================================================================

const exampleSteps: OnboardingStepConfig[] = [
	{
		path: "business-function",
		name: "Business Function",
		component: BusinessFunctionStep,
	},
	{ path: "systems-connect", name: "Systems", component: SystemsConnectStep },
	{ path: "complete", name: "Complete", component: CompleteStep },
];

export const Default: Story = {
	args: {
		steps: exampleSteps,
		onComplete: () => alert("Wizard completed!"),
		layout: WizardLayout,
	},
};

export const WithoutLayout: Story = {
	args: {
		steps: exampleSteps,
		onComplete: () => alert("Wizard completed!"),
	},
};

export const TwoSteps: Story = {
	args: {
		steps: [
			{
				path: "business-function",
				name: "Business Function",
				component: BusinessFunctionStep,
			},
			{ path: "complete", name: "Complete", component: CompleteStep },
		],
		onComplete: () => alert("Wizard completed!"),
		layout: WizardLayout,
	},
};
