import type { Meta, StoryObj } from '@storybook/react';
import { expect, userEvent, within } from 'storybook/test';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from './dialog';
import { Button } from '../button';
import { Input } from '../input';
import { Label } from '../label';
import { Plus } from 'lucide-react';
import React from 'react';

const meta = {
  title: 'UI/Dialog',
  component: Dialog,
  render: args => <Dialog {...args} />,
  argTypes: {
    open: {
      control: 'boolean',
      description: 'The open state of the dialog.',
    },
    modal: {
      control: 'boolean',
      description: 'Whether the dialog should be modal.',
      defaultValue: true,
    },
    // DialogContent prop exposed for Storybook controls
    size: {
      control: 'select',
      options: ['sm', 'md', 'lg', 'xl', '2xl', '3xl', '4xl', '5xl', 'full'],
      description: 'Width of the dialog (DialogContent prop).',
      defaultValue: 'lg',
      table: { category: 'DialogContent' },
    },
  },
} satisfies Meta;

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

export const Default: Story = {
  args: { size: 'lg' } as any,
  render: ({ size, ...args }: any) => (
    <Dialog {...args}>
      <DialogTrigger asChild>
        <Button variant="outline">Open Dialog</Button>
      </DialogTrigger>
      <DialogContent size={size}>
        <DialogHeader>
          <DialogTitle>Edit profile</DialogTitle>
          <DialogDescription>
            Make changes to your profile here. Click save when you're done.
          </DialogDescription>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="grid grid-cols-4 items-center gap-4">
            <Label htmlFor="name" className="text-right">
              Name
            </Label>
            <Input id="name" defaultValue="Pedro Duarte" className="col-span-3" />
          </div>
          <div className="grid grid-cols-4 items-center gap-4">
            <Label htmlFor="username" className="text-right">
              Username
            </Label>
            <Input id="username" defaultValue="@peduarte" className="col-span-3" />
          </div>
        </div>
        <DialogFooter>
          <Button type="submit">Save changes</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  ),
};

export const CreateMember: Story = {
  args: { size: 'md' } as any,
  render: ({ size, ...args }: any) => (
    <Dialog {...args}>
      <DialogTrigger asChild>
        <Button className="gap-2">
          <Plus className="size-4" /> New Member
        </Button>
      </DialogTrigger>
      <DialogContent size={size}>
        <DialogHeader>
          <DialogTitle>Add Team Member</DialogTitle>
          <DialogDescription>Enter the details of the new member below.</DialogDescription>
        </DialogHeader>
        <div className="grid gap-4 py-2">
          <div className="grid gap-2">
            <Label htmlFor="cm-name">Full Name</Label>
            <Input id="cm-name" placeholder="John Doe" />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="cm-email">Email address</Label>
            <Input id="cm-email" type="email" placeholder="john@example.com" />
          </div>
        </div>
        <DialogFooter>
          <Button type="submit">Invite Member</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  ),
};

export const WithScrollableBody: Story = {
  args: { size: 'md' } as any,
  render: ({ size, ...args }: any) => (
    <Dialog {...args}>
      <DialogTrigger asChild>
        <Button variant="outline">Long content dialog</Button>
      </DialogTrigger>
      <DialogContent size={size}>
        <DialogHeader>
          <DialogTitle>Terms of Service</DialogTitle>
          <DialogDescription>Please read the full terms before accepting.</DialogDescription>
        </DialogHeader>
        <DialogBody className="py-2">
          <div className="space-y-4 text-sm text-muted-foreground">
            {Array.from({ length: 12 }, (_, i) => (
              <p key={i}>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor
                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                exercitation ullamco laboris nisi ut aliquip ex ea commodo.
              </p>
            ))}
          </div>
        </DialogBody>
        <DialogFooter>
          <Button variant="outline">Decline</Button>
          <Button>Accept</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  ),
};

export const OpenClose: Story = {
  render: () => (
    <Dialog>
      <DialogTrigger asChild>
        <Button variant="outline">Open Dialog</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Confirm action</DialogTitle>
          <DialogDescription>Are you sure you want to proceed?</DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <Button type="submit">Confirm</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  ),
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    // Only test the trigger — Dialog content renders in a portal outside canvasElement
    const trigger = canvas.getByRole('button', { name: 'Open Dialog' });
    await expect(trigger).toBeInTheDocument();
    await expect(trigger).not.toBeDisabled();
    await userEvent.click(trigger);
    // Verify trigger received the click (dialog state managed by Radix portal)
    await expect(trigger).toBeInTheDocument();
  },
};
