import { useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react';
import Box from '@mui/material/Box';
import { ServiceSelector } from './ServiceSelector';
import { StepIndicator } from '../../molecules/StepIndicator';
import { Typography } from '../../atoms/Typography';

const serviceTypes = [
  {
    id: 'burial',
    name: 'Traditional Burial',
    price: 4200,
    description:
      'Full service with chapel ceremony, viewing, hearse, and graveside committal. Includes coordination with cemetery and clergy.',
  },
  {
    id: 'cremation',
    name: 'Cremation with Service',
    price: 2800,
    description:
      'Chapel ceremony followed by cremation. Includes use of chapel, celebrant coordination, and return of ashes in a standard urn.',
  },
  {
    id: 'direct-cremation',
    name: 'Direct Cremation',
    price: 1600,
    description:
      'Simple cremation without a formal service. A private, no-fuss option. Ashes returned to the family within 5 business days.',
  },
  {
    id: 'memorial',
    name: 'Memorial Service',
    price: 3100,
    description:
      'Ceremony held after cremation or burial. Flexible timing allows for family to travel and gather. Venue of your choice.',
  },
];

const coffinOptions = [
  {
    id: 'eco',
    name: 'Eco Willow',
    price: 850,
    description: 'Handwoven natural willow. Biodegradable and sustainable.',
  },
  {
    id: 'classic',
    name: 'Classic Maple',
    price: 1400,
    description: 'Solid maple with satin finish and brass handles.',
  },
  {
    id: 'premium',
    name: 'Premium Oak',
    price: 2200,
    description: 'Quarter-sawn oak with high-gloss lacquer and gold-plated handles.',
  },
  {
    id: 'simple',
    name: 'Simple Pine',
    price: 600,
    description: 'Unfinished pine. Can be personalised with paint, photos, or messages.',
  },
];

const meta: Meta<typeof ServiceSelector> = {
  title: 'Organisms/ServiceSelector',
  component: ServiceSelector,
  tags: ['autodocs'],
  parameters: {
    layout: 'centered',
    design: {
      type: 'figma',
      url: 'https://www.figma.com/design/XUDUrw4yMkEexBCCYHXUvT/Parsons?node-id=2349-39505',
    },
  },
  decorators: [
    (Story) => (
      <Box sx={{ maxWidth: 560, width: '100%', mx: 'auto' }}>
        <Story />
      </Box>
    ),
  ],
};

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

// --- Default -----------------------------------------------------------------

/** Static view — nothing selected */
export const Default: Story = {
  args: {
    heading: 'Choose a service type',
    subheading: "Select the type of service you'd like to arrange. Prices are starting estimates.",
    items: serviceTypes,
    continueLabel: 'Continue',
  },
};

// --- Pre-selected ------------------------------------------------------------

/** With an option already selected */
export const PreSelected: Story = {
  args: {
    heading: 'Choose a service type',
    items: serviceTypes,
    selectedId: 'cremation',
    continueLabel: 'Continue',
  },
};

// --- Interactive -------------------------------------------------------------

/** Full interactive demo with state management */
export const Interactive: Story = {
  render: () => {
    const [selected, setSelected] = useState<string | undefined>();

    return (
      <ServiceSelector
        heading="Choose a service type"
        subheading="Select the type of service you'd like to arrange. Prices are starting estimates."
        items={serviceTypes}
        selectedId={selected}
        onSelect={setSelected}
        continueLabel="Continue"
        onContinue={() => alert(`Selected: ${selected}`)}
      />
    );
  },
};

// --- Coffin Selection --------------------------------------------------------

/** Coffin/casket selection — shorter descriptions */
export const CoffinSelection: Story = {
  render: () => {
    const [selected, setSelected] = useState<string | undefined>();

    return (
      <ServiceSelector
        heading="Choose a coffin"
        subheading="All coffins include a fitted interior lining and nameplate."
        items={coffinOptions}
        selectedId={selected}
        onSelect={setSelected}
        continueLabel="Continue"
        onContinue={() => alert(`Selected: ${selected}`)}
      />
    );
  },
};

// --- With Line Limit ---------------------------------------------------------

/** Descriptions clamped to 1 line with "View more" toggle */
export const WithLineLimit: Story = {
  render: () => {
    const [selected, setSelected] = useState<string | undefined>();

    return (
      <ServiceSelector
        heading="Choose a service type"
        subheading="Click 'View more' on any option to read the full description."
        items={serviceTypes}
        selectedId={selected}
        onSelect={setSelected}
        continueLabel="Continue"
        onContinue={() => alert(`Selected: ${selected}`)}
        maxDescriptionLines={1}
      />
    );
  },
};

// --- Without Continue Button -------------------------------------------------

/** Selection only — no continue action (parent manages flow) */
export const WithoutContinue: Story = {
  render: () => {
    const [selected, setSelected] = useState<string | undefined>('burial');

    return (
      <ServiceSelector
        heading="Service type"
        items={serviceTypes}
        selectedId={selected}
        onSelect={setSelected}
      />
    );
  },
};

// --- With Disabled Options ---------------------------------------------------

/** Some options are unavailable */
export const WithDisabledOptions: Story = {
  render: () => {
    const [selected, setSelected] = useState<string | undefined>();

    const items = serviceTypes.map((item) =>
      item.id === 'memorial'
        ? {
            ...item,
            disabled: true,
            description: item.description + ' (Currently unavailable at this location.)',
          }
        : item,
    );

    return (
      <ServiceSelector
        heading="Choose a service type"
        subheading="Some options may not be available at your chosen location."
        items={items}
        selectedId={selected}
        onSelect={setSelected}
        continueLabel="Continue"
        onContinue={() => alert(`Selected: ${selected}`)}
      />
    );
  },
};

// --- In Arrangement Flow Context ---------------------------------------------

/** ServiceSelector within a multi-step arrangement flow */
export const InArrangementFlow: Story = {
  render: () => {
    const [selected, setSelected] = useState<string | undefined>();

    const steps = [
      { label: 'Service' },
      { label: 'Coffin' },
      { label: 'Venue' },
      { label: 'Extras' },
      { label: 'Review' },
    ];

    return (
      <Box>
        <StepIndicator steps={steps} currentStep={0} sx={{ mb: 4 }} />

        <ServiceSelector
          heading="Choose a service type"
          subheading="This is the first step in creating your arrangement. You can change this later."
          items={serviceTypes}
          selectedId={selected}
          onSelect={setSelected}
          continueLabel="Continue to coffin selection"
          onContinue={() => alert('Next step: Coffin')}
          maxDescriptionLines={2}
        />

        <Typography
          variant="captionSm"
          color="text.secondary"
          sx={{ mt: 3, textAlign: 'center', display: 'block' }}
        >
          All prices are estimates and may vary based on your specific requirements.
        </Typography>
      </Box>
    );
  },
};
