import { useEffect, useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react';
import { Button } from './Button';
import AddIcon from '@mui/icons-material/Add';
import ArrowForwardIcon from '@mui/icons-material/ArrowForward';
import SearchIcon from '@mui/icons-material/Search';
import CheckIcon from '@mui/icons-material/Check';

const meta: Meta<typeof Button> = {
  title: 'Atoms/Button',
  component: Button,
  tags: ['autodocs'],
  parameters: {
    layout: 'centered',
    design: {
      type: 'figma',
      url: 'https://www.figma.com/design/3t6fpT5inh7zzjxQdW8U5p/Design-System---Template?node-id=28-50',
    },
  },
  argTypes: {
    variant: {
      control: 'select',
      options: ['contained', 'soft', 'outlined', 'text'],
      description: 'Visual style variant',
      table: { defaultValue: { summary: 'contained' } },
    },
    color: {
      control: 'select',
      options: ['primary', 'secondary'],
      description: 'Colour intent',
      table: { defaultValue: { summary: 'primary' } },
    },
    size: {
      control: 'select',
      options: ['xs', 'small', 'medium', 'large'],
      description: 'Size preset',
      table: { defaultValue: { summary: 'medium' } },
    },
    loading: {
      control: 'boolean',
      description: 'Show loading spinner and disable interaction',
      table: { defaultValue: { summary: 'false' } },
    },
    underline: {
      control: 'boolean',
      description: 'Underline decoration for text variant buttons',
      table: { defaultValue: { summary: 'false' } },
    },
    disabled: {
      control: 'boolean',
      description: 'Disable the button',
      table: { defaultValue: { summary: 'false' } },
    },
    fullWidth: {
      control: 'boolean',
      description: 'Stretch to full width of parent container',
      table: { defaultValue: { summary: 'false' } },
    },
    onClick: { action: 'clicked' },
  },
};

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

// ─── Default ────────────────────────────────────────────────────────────────

/** Default button appearance — primary contained, medium size */
export const Default: Story = {
  args: {
    children: 'Get started',
  },
};

// ─── Figma Mapping ──────────────────────────────────────────────────────────

/**
 * Maps directly to the Figma button component columns:
 * - **Primary** → `contained` + `primary` (strong copper fill)
 * - **Secondary/Brand** → `soft` + `primary` (warm tonal fill)
 * - **Secondary/Grey** → `soft` + `secondary` (neutral tonal fill)
 * - **Ghost** → `text` + `primary` (no fill, copper text)
 */
export const FigmaMapping: Story = {
  name: 'Figma Mapping',
  render: () => (
    <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
      <Button variant="contained">Primary</Button>
      <Button variant="soft">Sec / Brand</Button>
      <Button variant="soft" color="secondary">
        Sec / Grey
      </Button>
      <Button variant="text">Ghost</Button>
    </div>
  ),
};

// ─── Variants ───────────────────────────────────────────────────────────────

/** All visual variants for primary (brand) colour */
export const VariantsPrimary: Story = {
  name: 'Variants — Primary',
  render: () => (
    <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
      <Button variant="contained">Contained</Button>
      <Button variant="soft">Soft</Button>
      <Button variant="outlined">Outlined</Button>
      <Button variant="text">Text</Button>
    </div>
  ),
};

/** All visual variants for secondary (neutral grey) colour */
export const VariantsSecondary: Story = {
  name: 'Variants — Secondary',
  render: () => (
    <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
      <Button variant="contained" color="secondary">
        Contained
      </Button>
      <Button variant="soft" color="secondary">
        Soft
      </Button>
      <Button variant="outlined" color="secondary">
        Outlined
      </Button>
      <Button variant="text" color="secondary">
        Text
      </Button>
    </div>
  ),
};

// ─── Sizes ──────────────────────────────────────────────────────────────────

/** All four sizes side by side */
export const AllSizes: Story = {
  render: () => (
    <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
      <Button size="xs">Extra small</Button>
      <Button size="small">Small</Button>
      <Button size="medium">Medium</Button>
      <Button size="large">Large</Button>
    </div>
  ),
};

/** All sizes in soft variant */
export const AllSizesSoft: Story = {
  name: 'All Sizes — Soft',
  render: () => (
    <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
      <Button variant="soft" size="xs">
        Extra small
      </Button>
      <Button variant="soft" size="small">
        Small
      </Button>
      <Button variant="soft" size="medium">
        Medium
      </Button>
      <Button variant="soft" size="large">
        Large
      </Button>
    </div>
  ),
};

// ─── With Icons ─────────────────────────────────────────────────────────────

/** Button with a leading (start) icon */
export const WithStartIcon: Story = {
  args: {
    children: 'Add to package',
    startIcon: <AddIcon />,
  },
};

/** Button with a trailing (end) icon */
export const WithEndIcon: Story = {
  args: {
    children: 'Continue',
    endIcon: <ArrowForwardIcon />,
  },
};

/** Button with both leading and trailing icons */
export const WithBothIcons: Story = {
  args: {
    children: 'Search',
    startIcon: <SearchIcon />,
    endIcon: <ArrowForwardIcon />,
  },
};

/** Icons across all sizes */
export const IconsAllSizes: Story = {
  name: 'Icons — All Sizes',
  render: () => (
    <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
      <Button size="xs" startIcon={<AddIcon />}>
        Add
      </Button>
      <Button size="small" startIcon={<AddIcon />}>
        Add
      </Button>
      <Button size="medium" startIcon={<AddIcon />}>
        Add
      </Button>
      <Button size="large" startIcon={<AddIcon />}>
        Add
      </Button>
    </div>
  ),
};

// ─── States ─────────────────────────────────────────────────────────────────

/** Disabled button */
export const Disabled: Story = {
  args: {
    children: 'Unavailable',
    disabled: true,
  },
};

/** Disabled across all variants */
export const DisabledAllVariants: Story = {
  name: 'Disabled — All Variants',
  render: () => (
    <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
      <Button disabled>Contained</Button>
      <Button disabled variant="soft">
        Soft
      </Button>
      <Button disabled variant="outlined">
        Outlined
      </Button>
      <Button disabled variant="text">
        Text
      </Button>
    </div>
  ),
};

/** Loading state with spinner (spinner appears on the right) */
export const Loading: Story = {
  args: {
    children: 'Submitting...',
    loading: true,
  },
};

/** Loading across variants */
export const LoadingAllVariants: Story = {
  name: 'Loading — All Variants',
  render: () => (
    <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
      <Button loading>Submitting...</Button>
      <Button loading variant="soft">
        Processing...
      </Button>
      <Button loading variant="outlined">
        Processing...
      </Button>
      <Button loading variant="text">
        Loading...
      </Button>
    </div>
  ),
};

// ─── Loading → Success Pattern ──────────────────────────────────────────────

/**
 * Demonstrates the recommended loading → success flow for async actions.
 *
 * The Button itself stays simple — the consumer controls the state
 * by toggling `loading`, `children`, and `endIcon`. Click to see the flow.
 */
export const LoadingToSuccess: Story = {
  name: 'Loading → Success Pattern',
  render: function LoadingSuccessDemo() {
    const [status, setStatus] = useState<'idle' | 'loading' | 'success'>('idle');

    useEffect(() => {
      if (status === 'loading') {
        const timer = setTimeout(() => setStatus('success'), 1500);
        return () => clearTimeout(timer);
      }
      if (status === 'success') {
        const timer = setTimeout(() => setStatus('idle'), 2000);
        return () => clearTimeout(timer);
      }
    }, [status]);

    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16, alignItems: 'center' }}>
        <Button
          loading={status === 'loading'}
          endIcon={status === 'success' ? <CheckIcon /> : undefined}
          color={status === 'success' ? 'success' : 'primary'}
          onClick={() => setStatus('loading')}
        >
          {status === 'idle' && 'Add to package'}
          {status === 'loading' && 'Adding...'}
          {status === 'success' && 'Added'}
        </Button>
        <p style={{ fontSize: 12, color: '#737373', margin: 0 }}>
          Click to see: idle → loading → success → idle
        </p>
      </div>
    );
  },
};

// ─── Text / Underline ───────────────────────────────────────────────────────

/** Text button with underline decoration (link-style) */
export const TextWithUnderline: Story = {
  args: {
    children: 'Go back',
    variant: 'text',
    underline: true,
  },
};

/** Text buttons with and without underline */
export const TextButtonComparison: Story = {
  name: 'Text Buttons — With & Without Underline',
  render: () => (
    <div style={{ display: 'flex', gap: 24, alignItems: 'center' }}>
      <Button variant="text">No underline</Button>
      <Button variant="text" underline>
        With underline
      </Button>
      <Button variant="text" color="secondary">
        Secondary
      </Button>
      <Button variant="text" color="secondary" underline>
        Secondary underlined
      </Button>
    </div>
  ),
};

/** Text button sizes (from the merged Text Button Figma component) */
export const TextButtonSizes: Story = {
  name: 'Text Buttons — All Sizes',
  render: () => (
    <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
      <Button variant="text" size="xs">
        Extra small
      </Button>
      <Button variant="text" size="small">
        Small
      </Button>
      <Button variant="text" size="medium">
        Medium
      </Button>
      <Button variant="text" size="large">
        Large
      </Button>
    </div>
  ),
};

// ─── Full Width ─────────────────────────────────────────────────────────────

/** Full width button (useful in mobile layouts and forms) */
export const FullWidth: Story = {
  args: {
    children: 'Complete arrangement',
    fullWidth: true,
    size: 'large',
  },
  decorators: [
    (Story) => (
      <div style={{ width: 360 }}>
        <Story />
      </div>
    ),
  ],
};

// ─── Edge Cases ─────────────────────────────────────────────────────────────

/** Long content to test text wrapping and overflow */
export const LongContent: Story = {
  args: {
    children: 'Add funeral arrangement to your saved packages for comparison',
  },
};

// ─── Complete Matrix ────────────────────────────────────────────────────────

/** Full variant x colour matrix for visual QA */
export const CompleteMatrix: Story = {
  render: () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      {(['contained', 'soft', 'outlined', 'text'] as const).map((variant) => (
        <div key={variant}>
          <div
            style={{ marginBottom: 8, fontWeight: 600, fontSize: 14, textTransform: 'capitalize' }}
          >
            {variant}
          </div>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
            <Button variant={variant} color="primary">
              Primary
            </Button>
            <Button variant={variant} color="secondary">
              Secondary
            </Button>
            <Button variant={variant} color="primary" startIcon={<AddIcon />}>
              With icon
            </Button>
            <Button variant={variant} color="primary" disabled>
              Disabled
            </Button>
            <Button variant={variant} color="primary" loading>
              Loading...
            </Button>
          </div>
        </div>
      ))}
    </div>
  ),
};
