import type { Meta, StoryObj } from '@storybook/react';
import { FocusTrap } from './focus-trap';
import { Button } from './button';
import { Input } from './input';
import { useState } from 'react';

const meta: Meta = {
    title: 'UI/FocusTrap',
    component: FocusTrap,
    tags: ['autodocs'],
    argTypes: {
        active: { control: 'boolean' },
    },
};

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

export const Interactive: Story = {
    render: (args) => {
        const [active, setActive] = useState(false);

        return (
            <div className="space-y-4">
                <Button onClick={() => setActive(!active)}>
                    {active ? 'Disable Focus Trap' : 'Enable Focus Trap'}
                </Button>

                <div className={`p-6 border rounded-lg transition-colors ${active ? 'border-primary bg-card' : 'border-border'}`}>
                    <h3 className="mb-4 font-bold">{active ? 'Focus Trapped Here' : 'Normal Navigation'}</h3>

                    <FocusTrap {...args} active={active} onEscape={() => setActive(false)}>
                        <div className="space-y-4">
                            <Input placeholder="First focusable element" />
                            <div className="flex gap-2">
                                <Button variant="outline">Button 1</Button>
                                <Button variant="destructive">Button 2</Button>
                            </div>
                            <Input placeholder="Last focusable element" />
                        </div>
                    </FocusTrap>

                    {active && (
                        <p className="mt-4 text-sm text-muted-foreground">
                            Try tabbing through inputs. Focus should stay within this box. Press Escape to exit.
                        </p>
                    )}
                </div>

                <div className="p-4 border border-dashed border-border opacity-50">
                    <p>Elements outside trap (cannot reach freely when active)</p>
                    <Button variant="ghost" className="mt-2">Outside Button</Button>
                </div>
            </div>
        );
    },
};
