import type { Meta, StoryObj } from '@storybook/react';
import { Stepper, Step } from './stepper';
import { useStepper } from './use-stepper';
import { Button } from '../button';
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '../card';
import React, { useState } from 'react';
import { Check } from 'lucide-react';
import { cn } from '../../shared/utils';

const meta: Meta<typeof Stepper> = {
  title: 'UI/Stepper',
  component: Stepper,
  render: args => <Stepper {...args} />,
};

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

export const Default: Story = {
  render: args => {
    const [currentStep, setCurrentStep] = useState(1);
    const totalSteps = 4;

    return (
      <Card className="w-[600px] mx-auto">
        <CardHeader>
          <CardTitle>Onboarding Process</CardTitle>
        </CardHeader>
        <CardContent className="space-y-8">
          <Stepper {...args} currentStep={args.currentStep ?? currentStep}>
            <Step step={1} label="Account" description="Set up your profile" />
            <Step
              step={2}
              label="Subscription Plan"
              description="Select a subscription plan that fits your needs from the available options"
            />
            <Step step={3} label="Payment" description="Add billing info" />
            <Step step={4} label="Done" description="Finish and launch" />
          </Stepper>

          <div className="flex h-32 items-center justify-center rounded-lg border border-dashed text-muted-foreground">
            {currentStep === 1 && 'Profile Setup Content'}
            {currentStep === 2 && 'Plan Selection Content'}
            {currentStep === 3 && 'Billing Information Content'}
            {currentStep === 4 && 'Confirmation Content'}
          </div>
        </CardContent>
        <CardFooter className="flex justify-between border-t pt-6">
          <Button
            variant="outline"
            onClick={() => setCurrentStep(s => Math.max(1, s - 1))}
            disabled={currentStep === 1}
          >
            Previous
          </Button>
          <Button onClick={() => setCurrentStep(s => Math.min(totalSteps, s + 1))}>
            {currentStep === totalSteps ? 'Finish' : 'Next Step'}
          </Button>
        </CardFooter>
      </Card>
    );
  },
};

/**
 * ## useStepper — Headless Hook
 *
 * Use `useStepper` when you need step navigation logic (next/prev/goTo,
 * async validation guard, first/last flags) but want to render a completely
 * custom step indicator UI — or when the step controls live far away from
 * the `<Stepper>` visual component.
 *
 * The `onBeforeNext` guard lets you run async form validation before the
 * step advances. Return `false` to block the transition.
 *
 * ```tsx
 * import { useStepper } from '@xertica/ui/stepper';
 *
 * const { currentStep, totalSteps, next, prev, isFirstStep, isLastStep } =
 *   useStepper({ totalSteps: 3, onBeforeNext: () => form.trigger() });
 * ```
 */
export const HeadlessHook: Story = {
  name: 'useStepper (headless)',
  render: () => {
    const steps = [
      { id: 1, label: 'Personal Info', content: 'Fill in your name and email.' },
      { id: 2, label: 'Address', content: 'Enter your shipping address.' },
      { id: 3, label: 'Review', content: 'Confirm your details before submitting.' },
    ];

    const { currentStep, totalSteps, next, prev, goTo, isFirstStep, isLastStep, canGoPrev } =
      useStepper({
        totalSteps: steps.length,
        // Simulate async validation — always passes in this demo
        onBeforeNext: async step => {
          console.log(`Validating step ${step}…`);
          await new Promise(r => setTimeout(r, 300));
          return true;
        },
      });

    return (
      <div className="w-[520px] space-y-6">
        {/* Custom step indicator — pill style */}
        <nav aria-label="Progress" className="flex items-center gap-2">
          {steps.map((step, idx) => {
            const isCompleted = step.id < currentStep;
            const isActive = step.id === currentStep;
            return (
              <React.Fragment key={step.id}>
                <button
                  onClick={() => goTo(step.id)}
                  className={cn(
                    'flex items-center gap-2 rounded-full px-3 py-1.5 text-sm font-medium transition-colors',
                    isActive && 'bg-primary text-primary-foreground',
                    isCompleted && 'bg-primary/20 text-primary hover:bg-primary/30',
                    !isActive && !isCompleted && 'bg-muted text-muted-foreground hover:bg-muted/80'
                  )}
                  aria-current={isActive ? 'step' : undefined}
                >
                  {isCompleted ? (
                    <Check className="h-3.5 w-3.5" />
                  ) : (
                    <span className="flex h-4 w-4 items-center justify-center rounded-full border border-current text-xs">
                      {step.id}
                    </span>
                  )}
                  {step.label}
                </button>
                {idx < steps.length - 1 && (
                  <div
                    className={cn(
                      'h-px flex-1',
                      step.id < currentStep ? 'bg-primary' : 'bg-border'
                    )}
                  />
                )}
              </React.Fragment>
            );
          })}
        </nav>

        {/* Step content */}
        <div className="rounded-xl border bg-card p-6 shadow-sm">
          <h3 className="mb-1 font-semibold">{steps[currentStep - 1].label}</h3>
          <p className="text-sm text-muted-foreground">{steps[currentStep - 1].content}</p>

          <div className="mt-6 flex h-20 items-center justify-center rounded-lg border border-dashed text-sm text-muted-foreground">
            Step {currentStep} of {totalSteps} — form fields go here
          </div>
        </div>

        {/* Navigation controls */}
        <div className="flex justify-between">
          <Button variant="outline" onClick={prev} disabled={!canGoPrev}>
            Back
          </Button>
          <Button onClick={() => next()}>{isLastStep ? 'Submit' : 'Continue'}</Button>
        </div>

        {isFirstStep && (
          <p className="text-center text-xs text-muted-foreground">
            Step navigation is driven entirely by <code>useStepper</code> — no{' '}
            <code>&lt;Stepper&gt;</code> component used.
          </p>
        )}
      </div>
    );
  },
};
