import type { Meta, StoryObj } from "@storybook/react";
import { addDays } from "date-fns";
import { useState } from "react";
import type { DateRange } from "react-day-picker";
import { DateRangeField } from "./DateRangeField";

const meta: Meta<typeof DateRangeField> = {
	title: "Widgets/Onboarding/Fields/DateRangeField",
	component: DateRangeField,
	parameters: {
		layout: "centered",
	},
	tags: ["autodocs"],
	argTypes: {
		onChange: { action: "changed" },
		disabled: { control: "boolean" },
		required: { control: "boolean" },
		numberOfMonths: { control: { type: "number", min: 1, max: 3 } },
	},
	decorators: [
		(Story) => (
			<div className="w-[400px]">
				<Story />
			</div>
		),
	],
};

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

// Wrapper to handle state
function DateRangeFieldWithState(
	props: React.ComponentProps<typeof DateRangeField>,
) {
	const [value, setValue] = useState<DateRange | undefined>(props.value);
	return <DateRangeField {...props} value={value} onChange={setValue} />;
}

export const Default: Story = {
	render: (args) => <DateRangeFieldWithState {...args} />,
	args: {
		id: "date-range",
		label: "Select Date Range",
		placeholder: "Pick a date range",
	},
};

export const WithDescription: Story = {
	render: (args) => <DateRangeFieldWithState {...args} />,
	args: {
		id: "date-range",
		label: "Project Timeline",
		description: "Select the start and end dates for your project",
		placeholder: "Pick start and end dates",
	},
};

export const WithValue: Story = {
	render: (args) => <DateRangeFieldWithState {...args} />,
	args: {
		id: "date-range",
		label: "Selected Range",
		value: {
			from: new Date(),
			to: addDays(new Date(), 7),
		},
	},
};

export const Required: Story = {
	render: (args) => <DateRangeFieldWithState {...args} />,
	args: {
		id: "date-range",
		label: "Required Date Range",
		required: true,
		placeholder: "Pick a date range",
	},
};

export const WithMinMaxDates: Story = {
	render: (args) => <DateRangeFieldWithState {...args} />,
	args: {
		id: "date-range",
		label: "Limited Range",
		description: "You can only select dates within the next 30 days",
		minDate: new Date(),
		maxDate: addDays(new Date(), 30),
	},
};

export const SingleMonth: Story = {
	render: (args) => <DateRangeFieldWithState {...args} />,
	args: {
		id: "date-range",
		label: "Single Month View",
		numberOfMonths: 1,
	},
};

export const WithError: Story = {
	render: (args) => <DateRangeFieldWithState {...args} />,
	args: {
		id: "date-range",
		label: "Date Range",
		error: "Please select a valid date range",
		touched: true,
	},
};

export const Disabled: Story = {
	render: (args) => <DateRangeFieldWithState {...args} />,
	args: {
		id: "date-range",
		label: "Disabled Field",
		value: {
			from: new Date(),
			to: addDays(new Date(), 7),
		},
		disabled: true,
	},
};
