import VTable from './VTable.vue';
import VBadge from './VBadge.vue'; // For custom cell rendering example
import VAvatar from './VAvatar.vue'; // For custom cell rendering
import VIcon from './VIcon.vue';   // For custom header rendering
import VButton from './VButton.vue'; // For empty state actions
import type { Meta, StoryObj } from '@storybook/vue3';
import { ref } from 'vue';

const meta: Meta<typeof VTable> = {
  title: 'Valerie/VTable',
  component: VTable,
  tags: ['autodocs'],
  argTypes: {
    headers: { control: 'object', description: 'Array of header objects ({ key, label, ... }).' },
    items: { control: 'object', description: 'Array of item objects for rows.' },
    stickyHeader: { control: 'boolean' },
    stickyFooter: { control: 'boolean' },
    tableClass: { control: 'text', description: 'Custom class(es) for the table element.' },
    caption: { control: 'text', description: 'Caption text for the table.' },
    // Slots are demonstrated in stories
  },
  parameters: {
    docs: {
      description: {
        component: 'A table component for displaying tabular data. Supports custom rendering for headers and cells, sticky header/footer, empty state, and more.',
      },
    },
  },
};

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

const sampleHeaders = [
  { key: 'id', label: 'ID', sortable: true, headerClass: 'id-header', cellClass: 'id-cell' },
  { key: 'name', label: 'Name', sortable: true },
  { key: 'email', label: 'Email Address' },
  { key: 'status', label: 'Status', cellClass: 'status-cell-shared' },
  { key: 'actions', label: 'Actions', sortable: false },
];

const sampleItems = [
  { id: 1, name: 'Alice Wonderland', email: 'alice@example.com', status: 'Active', role: 'Admin' },
  { id: 2, name: 'Bob The Builder', email: 'bob@example.com', status: 'Inactive', role: 'Editor' },
  { id: 3, name: 'Charlie Brown', email: 'charlie@example.com', status: 'Pending', role: 'Viewer' },
  { id: 4, name: 'Diana Prince', email: 'diana@example.com', status: 'Active', role: 'Admin' },
];

export const BasicTable: Story = {
  args: {
    headers: sampleHeaders.filter(h => h.key !== 'actions'), // Exclude actions for basic
    items: sampleItems,
    caption: 'User information list.',
  },
};

export const StickyHeader: Story = {
  args: {
    ...BasicTable.args,
    stickyHeader: true,
    items: [...sampleItems, ...sampleItems, ...sampleItems], // More items to make scroll visible
  },
  // Decorator to provide a scrollable container for the story
  decorators: [() => ({ template: '<div style="height: 200px; overflow-y: auto; border: 1px solid #ccc;"><story/></div>' })],
};

export const CustomCellRendering: Story = {
  render: (args) => ({
    components: { VTable, VBadge, VAvatar },
    setup() { return { args }; },
    template: `
      <VTable :headers="args.headers" :items="args.items" :caption="args.caption">
        <template #item.name="{ item }">
          <div style="display: flex; align-items: center;">
            <VAvatar :initials="item.name.substring(0,1)" size="sm" style="width: 24px; height: 24px; font-size: 0.7em; margin-right: 8px;" />
            <span>{{ item.name }}</span>
          </div>
        </template>
        <template #item.status="{ value }">
          <VBadge
            :text="value"
            :variant="value === 'Active' ? 'success' : (value === 'Inactive' ? 'neutral' : 'pending')"
          />
        </template>
        <template #item.actions="{ item }">
          <VButton size="sm" variant="primary" @click="() => alert('Editing item ' + item.id)">Edit</VButton>
        </template>
      </VTable>
    `,
  }),
  args: {
    headers: sampleHeaders,
    items: sampleItems,
    caption: 'Table with custom cell rendering for Status and Actions.',
  },
};

export const CustomHeaderRendering: Story = {
  render: (args) => ({
    components: { VTable, VIcon },
    setup() { return { args }; },
    template: `
      <VTable :headers="args.headers" :items="args.items">
        <template #header.name="{ header }">
          {{ header.label }} <VIcon name="alert" size="sm" style="color: blue;" />
        </template>
         <template #header.email="{ header }">
          <i>{{ header.label }} (italic)</i>
        </template>
      </VTable>
    `,
  }),
  args: {
    headers: sampleHeaders.filter(h => h.key !== 'actions'),
    items: sampleItems.slice(0, 2),
  },
};

export const EmptyStateTable: Story = {
  render: (args) => ({
    components: { VTable, VButton, VIcon },
    setup() { return { args }; },
    template: `
      <VTable :headers="args.headers" :items="args.items">
        <template #empty-state>
          <div style="text-align: center; padding: 2rem;">
            <VIcon name="search" size="lg" style="margin-bottom: 1rem; color: #6c757d;" />
            <h3>No Users Found</h3>
            <p>There are no users matching your current criteria. Try adjusting your search or filters.</p>
            <VButton variant="primary" @click="() => alert('Add User clicked')">Add New User</VButton>
          </div>
        </template>
      </VTable>
    `,
  }),
  args: {
    headers: sampleHeaders,
    items: [], // Empty items array
  },
};

export const WithFooter: Story = {
   render: (args) => ({
    components: { VTable },
    setup() { return { args }; },
    template: `
      <VTable :headers="args.headers" :items="args.items" :stickyFooter="args.stickyFooter">
        <template #footer>
          <tr>
            <td :colspan="args.headers.length -1" style="text-align: right; font-weight: bold;">Total Users:</td>
            <td style="font-weight: bold;">{{ args.items.length }}</td>
          </tr>
          <tr>
            <td :colspan="args.headers.length" style="text-align: center; font-size: 0.9em;">
              End of user list.
            </td>
          </tr>
        </template>
      </VTable>
    `,
  }),
  args: {
    headers: sampleHeaders.filter(h => h.key !== 'actions' && h.key !== 'email'), // Simplified headers for footer example
    items: sampleItems,
    stickyFooter: false,
  },
};

export const StickyHeaderAndFooter: Story = {
  ...WithFooter, // Reuses render from WithFooter
  args: {
    ...WithFooter.args,
    stickyHeader: true,
    stickyFooter: true,
    items: [...sampleItems, ...sampleItems, ...sampleItems], // More items for scrolling
  },
  decorators: [() => ({ template: '<div style="height: 250px; overflow-y: auto; border: 1px solid #ccc;"><story/></div>' })],
};


export const WithCustomTableAndCellClasses: Story = {
  args: {
    headers: [
      { key: 'id', label: 'ID', headerClass: 'text-danger font-weight-bold', cellClass: 'text-muted' },
      { key: 'name', label: 'Name', headerClass: ['bg-light-blue', 'p-2'], cellClass: (item) => ({ 'text-success': item.status === 'Active' }) },
      { key: 'email', label: 'Email' },
    ],
    items: sampleItems.slice(0,2).map(item => ({...item, headerClass:'should-not-apply-here'})), // added dummy prop to item
    tableClass: 'table-striped table-hover custom-global-table-class', // Example global/utility classes
    caption: 'Table with custom classes applied via props.',
  },
  // For this story to fully work, the specified custom classes (e.g., text-danger, bg-light-blue)
  // would need to be defined globally or in valerie-ui.scss.
  // Storybook will render the classes, but their visual effect depends on CSS definitions.
  parameters: {
    docs: {
      description: { story: 'Demonstrates applying custom CSS classes to the table, header cells, and body cells using `tableClass`, `headerClass`, and `cellClass` props. The actual styling effect depends on these classes being defined in your CSS.'}
    }
  }
};

export const FullRowSlot: Story = {
  render: (args) => ({
    components: { VTable, VBadge },
    setup() { return { args }; },
    template: `
      <VTable :headers="args.headers" :items="args.items">
        <template #item="{ item, rowIndex }">
          <tr :class="rowIndex % 2 === 0 ? 'bg-light-gray' : 'bg-white'">
            <td colspan="1" style="font-weight:bold;">ROW {{ rowIndex + 1 }}</td>
            <td colspan="2">
              <strong>{{ item.name }}</strong> ({{ item.email }}) - Role: {{item.role}}
            </td>
            <td><VBadge :text="item.status" :variant="item.status === 'Active' ? 'success' : 'neutral'" /></td>
          </tr>
        </template>
      </VTable>
    `,
  }),
  args: {
    headers: sampleHeaders.filter(h => h.key !== 'actions'), // Adjust headers as the slot takes full control
    items: sampleItems,
  },
  parameters: {
    docs: {
      description: {story: "Demonstrates using the `item` slot to take full control of row rendering. The `headers` prop is still used for `<thead>` generation, but `<tbody>` rows are completely defined by this slot."}
    }
  }
};
