import type { Meta, StoryObj } from '@storybook/vue3-vite';
import { computed, ref, watch } from 'vue';
import {
  UiDialog,
  UiDialogClose,
  UiDialogContent,
  UiDialogDescription,
  UiDialogHeader,
  UiDialogTitle,
  UiDialogTrigger,
} from './index';
import { UiButton } from '../UiButton';
import { UiField, UiFieldContent, UiFieldLabel } from '../UiField';
import { UiIcon } from '../UiIcon';
import { UiInput } from '../UiInput';

/**
 * Modal dialog (reka-ui + design tokens). **`UiDialogContent`** defaults to **`max-w-[50vw]`**; use **`maxWidth`** with a preset (`max-w-sm` … `max-w-2xl`, `max-w-none`, etc.) to override. Built-in title/description headers include a dismiss control unless **`show-close-button`** is false or you use the **`#header`** slot (then add your own **`UiDialogClose`**).
 * @category Components
 * @useCases forms, confirmations, settings, multi-step flows
 */
const meta: Meta<typeof UiDialog> = {
  title: 'Components/UiDialog',
  component: UiDialog,
  tags: ['autodocs'],
  argTypes: {
    open: {
      control: 'boolean',
      description: 'Controlled open state (use `v-model:open`).',
    },
    modal: {
      control: 'boolean',
      description:
        'If true, traps focus and blocks interaction with the page while open.',
    },
  },
  args: {
    open: false,
    modal: true,
  },
};

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

function useUiDialogStoryArgs(args: { open?: boolean; modal?: boolean }) {
  const open = ref(args.open ?? false);
  watch(
    () => args.open,
    (v) => {
      open.value = v ?? false;
    },
  );
  const modal = computed(() => args.modal ?? true);
  return { open, modal };
}

const defaultTemplateSource = `<script setup lang="ts">
import {
  UiDialog,
  UiDialogTrigger,
  UiDialogContent,
  UiDialogClose,
  UiButton,
} from '@aleph-alpha/ui-library'
</script>

<template>
  <UiDialog>
    <UiDialogTrigger as-child>
      <UiButton variant="outline">Open dialog</UiButton>
    </UiDialogTrigger>
    <UiDialogContent
      max-width="max-w-[50vw]"
      title="Edit profile"
      description="Make changes to your profile here. Click save when done."
    >
      <p class="body-14-regular text-content-on-surface-secondary">
        Dialog body content goes in the default slot.
      </p>
      <template #actions>
        <UiDialogClose as-child>
          <UiButton variant="outline">Cancel</UiButton>
        </UiDialogClose>
        <UiButton>Save changes</UiButton>
      </template>
    </UiDialogContent>
  </UiDialog>
</template>`;

/**
 * Typical dialog: trigger, `title` / `description` props, body slot, and optional `#actions` for buttons.
 */
export const Default: Story = {
  args: {
    open: false,
  },

  render: (args) => ({
    components: {
      UiDialog,
      UiDialogClose,
      UiDialogContent,
      UiDialogTrigger,
      UiButton,
    },
    setup() {
      return useUiDialogStoryArgs(args);
    },
    template: `
      <UiDialog v-model:open="open" :modal="modal">
        <UiDialogTrigger as-child>
          <UiButton variant="outline">Open dialog</UiButton>
        </UiDialogTrigger>
        <UiDialogContent
          max-width="max-w-[50vw]"
          title="Edit profile"
          description="Make changes to your profile here. Click save when done."
        >
          <p class="body-14-regular text-content-on-surface-secondary">
            Dialog body content goes in the default slot. The header includes a close control; Cancel in actions also closes.
          </p>
          <template #actions>
            <UiDialogClose as-child>
              <UiButton variant="outline">Cancel</UiButton>
            </UiDialogClose>
            <UiButton>Save changes</UiButton>
          </template>
        </UiDialogContent>
      </UiDialog>
    `,
  }),

  parameters: {
    docs: {
      source: {
        code: defaultTemplateSource,
      },
    },
  },
};

const contentStoryTemplateSource = `<script setup lang="ts">
import {
  UiDialog,
  UiDialogTrigger,
  UiDialogContent,
  UiDialogClose,
  UiButton,
} from '@aleph-alpha/ui-library'
</script>

<template>
  <UiDialog>
    <UiDialogTrigger as-child>
      <UiButton variant="outline">Open content dialog</UiButton>
    </UiDialogTrigger>
    <UiDialogContent
      max-width="max-w-lg"
      title="Dialog title"
      description="This is a dialog description."
    >
      <div class="flex max-h-[min(60vh,22rem)] flex-col gap-4 overflow-y-auto pr-1 body-14-regular text-content-on-surface-secondary">
        <p class="shrink-0 body-14-medium text-content-on-surface-primary">Lorem ipsum</p>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum hendrerit ex vitae sodales. Donec id leo ipsum. Phasellus volutpat aliquet mauris, et blandit nulla laoreet vitae. Quisque ante dui, porta eu felis nec, scelerisque pharetra turpis.
        </p>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum hendrerit ex vitae sodales. Donec id leo ipsum. Phasellus volutpat aliquet mauris, et blandit nulla laoreet vitae. Quisque ante dui, porta eu felis nec, scelerisque pharetra turpis.
        </p>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum hendrerit ex vitae sodales. Donec id leo ipsum. Phasellus volutpat aliquet mauris, et blandit nulla laoreet vitae. Quisque ante dui, porta eu felis nec, scelerisque pharetra turpis.
        </p>
      </div>
      <template #actions>
        <UiDialogClose as-child>
          <UiButton type="button" variant="outline">Cancel</UiButton>
        </UiDialogClose>
      </template>
    </UiDialogContent>
  </UiDialog>
</template>`;

/**
 * Long body copy in the default slot: title, description, stacked paragraphs, single Cancel in `#actions`.
 */
export const Content: Story = {
  render: (args) => ({
    components: {
      UiDialog,
      UiDialogClose,
      UiDialogContent,
      UiDialogTrigger,
      UiButton,
    },
    setup() {
      return useUiDialogStoryArgs(args);
    },
    template: `
      <UiDialog v-model:open="open" :modal="modal">
        <UiDialogTrigger as-child>
          <UiButton variant="outline">Open content dialog</UiButton>
        </UiDialogTrigger>
        <UiDialogContent
          max-width="max-w-lg"
          title="Dialog title"
          description="This is a dialog description."
        >
          <div class="flex max-h-[min(60vh,22rem)] flex-col gap-4 overflow-y-auto pr-1 body-14-regular text-content-on-surface-secondary">
            <p class="shrink-0 body-14-medium text-content-on-surface-primary">Lorem ipsum</p>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum hendrerit ex vitae sodales. Donec id leo ipsum. Phasellus volutpat aliquet mauris, et blandit nulla laoreet vitae. Quisque ante dui, porta eu felis nec, scelerisque pharetra turpis.
            </p>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum hendrerit ex vitae sodales. Donec id leo ipsum. Phasellus volutpat aliquet mauris, et blandit nulla laoreet vitae. Quisque ante dui, porta eu felis nec, scelerisque pharetra turpis.
            </p>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum hendrerit ex vitae sodales. Donec id leo ipsum. Phasellus volutpat aliquet mauris, et blandit nulla laoreet vitae. Quisque ante dui, porta eu felis nec, scelerisque pharetra turpis.
            </p>
          </div>
          <template #actions>
            <UiDialogClose as-child>
              <UiButton type="button" variant="outline">Cancel</UiButton>
            </UiDialogClose>
          </template>
        </UiDialogContent>
      </UiDialog>
    `,
  }),
  parameters: {
    docs: {
      source: {
        code: contentStoryTemplateSource,
      },
    },
  },
};

const actionsSlotTemplateSource = `<script setup lang="ts">
import {
  UiDialog,
  UiDialogTrigger,
  UiDialogContent,
  UiDialogClose,
  UiButton,
} from '@aleph-alpha/ui-library'
</script>

<template>
  <UiDialog>
    <UiDialogTrigger as-child>
      <UiButton variant="outline">Open with actions slot</UiButton>
    </UiDialogTrigger>
    <UiDialogContent
      max-width="max-w-lg"
      title="Share document"
      description="Anyone with the link can view this file."
    >
      <p class="body-14-regular text-content-on-surface-secondary">
        Body content uses the default slot. Put buttons in <code>#actions</code>; they render in the
        dialog footer row.
      </p>
      <template #actions>
        <UiButton type="button" variant="ghost">Discard</UiButton>
        <UiDialogClose as-child>
          <UiButton type="button" variant="outline">Cancel</UiButton>
        </UiDialogClose>
        <UiButton type="button">Copy link</UiButton>
      </template>
    </UiDialogContent>
  </UiDialog>
</template>`;

/**
 * **`#actions` slot** — place all footer buttons here (wrapped in `DialogFooter` for alignment).
 * Use `UiDialogClose` with `as-child` around buttons that should close the dialog.
 */
export const WithActionsSlot: Story = {
  render: (args) => ({
    components: {
      UiDialog,
      UiDialogClose,
      UiDialogContent,
      UiDialogTrigger,
      UiButton,
    },
    setup() {
      return useUiDialogStoryArgs(args);
    },
    template: `
      <UiDialog v-model:open="open" :modal="modal">
        <UiDialogTrigger as-child>
          <UiButton variant="outline">Open with actions slot</UiButton>
        </UiDialogTrigger>
        <UiDialogContent
          max-width="max-w-lg"
          title="Share document"
          description="Anyone with the link can view this file."
        >
          <p class="body-14-regular text-content-on-surface-secondary">
            Body content uses the default slot. Put buttons in <code class="rounded bg-background-surface-muted px-1 py-0.5 label-12-medium">#actions</code>; they render in the dialog footer row.
          </p>
          <template #actions>
            <UiButton type="button" variant="ghost">Discard</UiButton>
            <UiDialogClose as-child>
              <UiButton type="button" variant="outline">Cancel</UiButton>
            </UiDialogClose>
            <UiButton type="button">Copy link</UiButton>
          </template>
        </UiDialogContent>
      </UiDialog>
    `,
  }),
  parameters: {
    docs: {
      source: {
        code: actionsSlotTemplateSource,
      },
    },
  },
};

const titleOnlyTemplateSource = `<script setup lang="ts">
import {
  UiDialog,
  UiDialogTrigger,
  UiDialogContent,
  UiButton,
} from '@aleph-alpha/ui-library'
</script>

<template>
  <UiDialog>
    <UiDialogTrigger as-child>
      <UiButton variant="outline">Open</UiButton>
    </UiDialogTrigger>
    <UiDialogContent title="Notifications" max-width="max-w-md">
      <p class="body-14-regular text-content-on-surface-secondary">
        No description or footer actions — header still includes a close control (and Escape / overlay click).
      </p>
    </UiDialogContent>
  </UiDialog>
</template>`;

/**
 * Title only: no `description`, no `#actions` slot; header close is still shown by default.
 */
export const TitleOnly: Story = {
  render: (args) => ({
    components: {
      UiDialog,
      UiDialogContent,
      UiDialogTrigger,
      UiButton,
    },
    setup() {
      return useUiDialogStoryArgs(args);
    },
    template: `
      <UiDialog v-model:open="open" :modal="modal">
        <UiDialogTrigger as-child>
          <UiButton variant="outline">Open</UiButton>
        </UiDialogTrigger>
        <UiDialogContent title="Notifications" max-width="max-w-md">
          <p class="body-14-regular text-content-on-surface-secondary">
            No description or footer actions — header still includes a close control (and Escape / overlay click).
          </p>
        </UiDialogContent>
      </UiDialog>
    `,
  }),
  parameters: {
    docs: {
      source: {
        code: titleOnlyTemplateSource,
      },
    },
  },
};

const maxWidthTemplateSource = `<script setup lang="ts">
import {
  UiDialog,
  UiDialogTrigger,
  UiDialogContent,
  UiDialogClose,
  UiButton,
} from '@aleph-alpha/ui-library'
</script>

<template>
  <UiDialog>
    <UiDialogTrigger as-child>
      <UiButton variant="outline">Narrow dialog</UiButton>
    </UiDialogTrigger>
    <UiDialogContent
      max-width="max-w-lg"
      title="Confirm"
      description="This dialog uses max-width to stay readable on large screens."
    >
      <template #actions>
        <UiDialogClose as-child>
          <UiButton variant="outline">Close</UiButton>
        </UiDialogClose>
      </template>
    </UiDialogContent>
  </UiDialog>
</template>`;

/**
 * Narrower than the default **`max-w-[50vw]`** by setting **`max-width="max-w-lg"`** (or another preset).
 */
export const WithMaxWidth: Story = {
  render: (args) => ({
    components: {
      UiDialog,
      UiDialogClose,
      UiDialogContent,
      UiDialogTrigger,
      UiButton,
    },
    setup() {
      return useUiDialogStoryArgs(args);
    },
    template: `
      <UiDialog v-model:open="open" :modal="modal">
        <UiDialogTrigger as-child>
          <UiButton variant="outline">Narrow dialog</UiButton>
        </UiDialogTrigger>
        <UiDialogContent
          max-width="max-w-lg"
          title="Confirm"
          description="This dialog uses max-width to stay readable on large screens."
        >
          <template #actions>
            <UiDialogClose as-child>
              <UiButton variant="outline">Close</UiButton>
            </UiDialogClose>
          </template>
        </UiDialogContent>
      </UiDialog>
    `,
  }),
  parameters: {
    docs: {
      source: {
        code: maxWidthTemplateSource,
      },
    },
  },
};

const customHeaderTemplateSource = `<script setup lang="ts">
import {
  UiDialog,
  UiDialogTrigger,
  UiDialogContent,
  UiDialogHeader,
  UiDialogTitle,
  UiDialogDescription,
  UiDialogClose,
  UiButton,
  UiIcon,
} from '@aleph-alpha/ui-library'
</script>

<template>
  <UiDialog>
    <UiDialogTrigger as-child>
      <UiButton variant="outline">Custom header</UiButton>
    </UiDialogTrigger>
    <UiDialogContent :show-close-button="false">
      <template #header>
        <div class="flex items-start justify-between gap-4">
          <UiDialogHeader class="min-w-0 flex-1">
            <UiDialogTitle>Custom header slot</UiDialogTitle>
            <UiDialogDescription>
              Use the header slot when you need full control; add your own close control here.
            </UiDialogDescription>
          </UiDialogHeader>
          <UiDialogClose as-child>
            <UiButton variant="ghost" class="size-9 shrink-0 p-0" aria-label="Close dialog">
              <UiIcon name="x" :size="20" />
            </UiButton>
          </UiDialogClose>
        </div>
      </template>
      <p class="body-14-regular text-content-on-surface-secondary">Main content.</p>
      <template #actions>
        <UiDialogClose as-child>
          <UiButton variant="outline">Cancel</UiButton>
        </UiDialogClose>
        <UiButton>OK</UiButton>
      </template>
    </UiDialogContent>
  </UiDialog>
</template>`;

/**
 * Custom `#header` slot — supply layout yourself; set **`show-close-button`** to false to avoid a duplicate, then place **`UiDialogClose`** in the header row.
 */
export const CustomHeaderSlot: Story = {
  render: (args) => ({
    components: {
      UiDialog,
      UiDialogClose,
      UiDialogContent,
      UiDialogDescription,
      UiDialogHeader,
      UiDialogTitle,
      UiDialogTrigger,
      UiButton,
      UiIcon,
    },
    setup() {
      return useUiDialogStoryArgs(args);
    },
    template: `
      <UiDialog v-model:open="open" :modal="modal">
        <UiDialogTrigger as-child>
          <UiButton variant="outline">Custom header</UiButton>
        </UiDialogTrigger>
        <UiDialogContent :show-close-button="false">
          <template #header>
            <div class="flex items-start justify-between gap-4">
              <UiDialogHeader class="min-w-0 flex-1">
                <UiDialogTitle>Custom header slot</UiDialogTitle>
                <UiDialogDescription>
                  Use the header slot when you need full control; add your own close control here.
                </UiDialogDescription>
              </UiDialogHeader>
              <UiDialogClose as-child>
                <UiButton variant="ghost" class="size-9 shrink-0 p-0" aria-label="Close dialog">
                  <UiIcon name="x" :size="20" />
                </UiButton>
              </UiDialogClose>
            </div>
          </template>
          <p class="body-14-regular text-content-on-surface-secondary">Main content.</p>
          <template #actions>
            <UiDialogClose as-child>
              <UiButton variant="outline">Cancel</UiButton>
            </UiDialogClose>
            <UiButton>OK</UiButton>
          </template>
        </UiDialogContent>
      </UiDialog>
    `,
  }),
  parameters: {
    docs: {
      source: {
        code: customHeaderTemplateSource,
      },
    },
  },
};

const formTemplateSource = `<script setup lang="ts">
import { ref } from 'vue'
import {
  UiDialog,
  UiDialogTrigger,
  UiDialogContent,
  UiDialogClose,
  UiButton,
  UiField,
  UiFieldLabel,
  UiFieldContent,
  UiInput,
} from '@aleph-alpha/ui-library'

const name = ref('')
const email = ref('')

function onSubmit() {
  // handle save (e.g. API call), then close dialog
}
</script>

<template>
  <UiDialog>
    <UiDialogTrigger as-child>
      <UiButton variant="outline">New project</UiButton>
    </UiDialogTrigger>
    <UiDialogContent
      max-width="max-w-lg"
      title="Create project"
      description="Add a name and contact email. You can change these later."
    >
      <form
        id="dialog-create-project-form"
        class="flex flex-col gap-4"
        @submit.prevent="onSubmit"
      >
        <UiField>
          <UiFieldLabel for="dialog-project-name">Project name</UiFieldLabel>
          <UiFieldContent>
            <UiInput
              id="dialog-project-name"
              v-model="name"
              name="projectName"
              placeholder="My project"
              autocomplete="off"
            />
          </UiFieldContent>
        </UiField>
        <UiField>
          <UiFieldLabel for="dialog-project-email">Email</UiFieldLabel>
          <UiFieldContent>
            <UiInput
              id="dialog-project-email"
              v-model="email"
              type="email"
              name="email"
              placeholder="you@company.com"
              autocomplete="email"
            />
          </UiFieldContent>
        </UiField>
      </form>
      <template #actions>
        <UiDialogClose as-child>
          <UiButton type="button" variant="outline">Cancel</UiButton>
        </UiDialogClose>
        <UiButton type="submit" form="dialog-create-project-form">Create</UiButton>
      </template>
    </UiDialogContent>
  </UiDialog>
</template>`;

/**
 * Form in the default slot: use a `<form>`, `UiField` + `UiInput`, and wire primary submit to the action button via `form` + `id` when actions sit outside the form.
 */
export const WithForm: Story = {
  render: (args) => ({
    components: {
      UiDialog,
      UiDialogClose,
      UiDialogContent,
      UiDialogTrigger,
      UiButton,
      UiField,
      UiFieldContent,
      UiFieldLabel,
      UiInput,
    },
    setup() {
      const { open, modal } = useUiDialogStoryArgs(args);
      const name = ref('');
      const email = ref('');

      function onSubmit() {
        name.value = '';
        email.value = '';
      }

      return { open, modal, name, email, onSubmit };
    },
    template: `
      <UiDialog v-model:open="open" :modal="modal">
        <UiDialogTrigger as-child>
          <UiButton variant="outline">New project</UiButton>
        </UiDialogTrigger>
        <UiDialogContent
          max-width="max-w-lg"
          title="Create project"
          description="Add a name and contact email. You can change these later."
        >
          <form
            id="dialog-create-project-form"
            class="flex flex-col gap-4"
            @submit.prevent="onSubmit"
          >
            <UiField>
              <UiFieldLabel for="dialog-project-name">Project name</UiFieldLabel>
              <UiFieldContent>
                <UiInput
                  id="dialog-project-name"
                  v-model="name"
                  name="projectName"
                  placeholder="My project"
                  autocomplete="off"
                />
              </UiFieldContent>
            </UiField>
            <UiField>
              <UiFieldLabel for="dialog-project-email">Email</UiFieldLabel>
              <UiFieldContent>
                <UiInput
                  id="dialog-project-email"
                  v-model="email"
                  type="email"
                  name="email"
                  placeholder="you@company.com"
                  autocomplete="email"
                />
              </UiFieldContent>
            </UiField>
          </form>
          <template #actions>
            <UiDialogClose as-child>
              <UiButton type="button" variant="outline">Cancel</UiButton>
            </UiDialogClose>
            <UiButton type="submit" form="dialog-create-project-form">Create</UiButton>
          </template>
        </UiDialogContent>
      </UiDialog>
    `,
  }),
  parameters: {
    docs: {
      source: {
        code: formTemplateSource,
      },
    },
  },
};
