import { useEffect, useState } from 'react';

import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { type Meta, type StoryObj } from '@storybook/react-vite';
import {
  IconBell,
  IconDoor,
  IconPencil,
  IconSettings,
  IconSparkles,
} from '@tabler/icons-react';

import { type AvatarSwitcherCardProps } from './types';
import AvatarSwitcherCard from './index';

const meta: Meta<typeof AvatarSwitcherCard> = {
  component: AvatarSwitcherCard,
  title: 'Composed Components/Cards/AvatarSwitcherCard',
  tags: ['autodocs'],
  parameters: {
    docs: {
      description: {
        component: `
Card for enabling or disabling a product feature from a settings-style list.

Combines an icon avatar, title, description, optional status pills, optional icon-button actions, and a toggle switch in a single row.

## When to use
- Feature toggles in admin or workspace settings
- Module activation rows with contextual metadata (badges, configuration shortcuts)
- Lists where each item can be turned on/off independently
        `,
      },
    },
  },
  argTypes: {
    icon: {
      description: 'Tabler icon displayed inside the avatar.',
      table: {
        type: { summary: 'TablerIcon' },
      },
      control: false,
    },
    title: {
      description: 'Primary heading shown next to the avatar.',
      table: {
        type: { summary: 'string' },
      },
      control: { type: 'text' },
    },
    description: {
      description: 'Secondary text displayed below the title.',
      table: {
        type: { summary: 'string' },
      },
      control: { type: 'text' },
    },
    checked: {
      description: 'Current on/off state of the switcher.',
      table: {
        type: { summary: 'boolean' },
        defaultValue: { summary: 'false' },
      },
      control: { type: 'boolean' },
    },
    disabled: {
      description:
        'When `true`, disables the switcher, action buttons, and avatar interaction.',
      table: {
        type: { summary: 'boolean' },
        defaultValue: { summary: 'false' },
      },
      control: { type: 'boolean' },
    },
    onChange: {
      description: 'Callback fired when the switcher state changes.',
      table: {
        type: { summary: '(checked: boolean) => void' },
      },
      control: false,
    },
    pills: {
      description: 'Optional status pills rendered before the actions.',
      table: {
        type: { summary: 'PillsProps[]' },
      },
      control: false,
    },
    actions: {
      description: 'Optional icon-button actions rendered before the switcher.',
      table: {
        type: { summary: 'IconButtonProps[]' },
      },
      control: false,
    },
    sx: {
      description: 'MUI `sx` style overrides applied to the root container.',
      table: {
        type: { summary: 'SxProps' },
      },
      control: false,
    },
    slotProps: {
      description: 'Props forwarded to each inner slot of the card.',
      table: {
        type: { summary: 'AvatarSwitcherCardSlotProps' },
      },
      control: false,
    },
  },
  args: {
    title: 'Onboarding',
    description: 'Crea procesos para darle la bienvenida a tus colaboradores.',
    icon: IconDoor,
    checked: false,
    disabled: false,
  },
};

export default meta;

type Story = StoryObj<typeof AvatarSwitcherCard>;

const defaultPills: NonNullable<AvatarSwitcherCardProps['pills']> = [
  {
    label: 'New',
    type: 'success',
    hasIcon: false,
  },
  {
    label: 'Beta',
    type: 'highlight',
    hasIcon: false,
  },
];

const settingsAction: NonNullable<AvatarSwitcherCardProps['actions']>[number] =
  {
    id: 'settings',
    'aria-label': 'Configuración',
    variant: 'tertiary',
    children: <IconSettings />,
    onClick: () => alert('[AvatarSwitcherCard] Settings'),
  };

const editAction: NonNullable<AvatarSwitcherCardProps['actions']>[number] = {
  id: 'edit',
  'aria-label': 'Editar',
  variant: 'tertiary',
  children: <IconPencil />,
  onClick: () => alert('[AvatarSwitcherCard] Edit'),
};

type ControlledCardProps = Partial<AvatarSwitcherCardProps> &
  Pick<AvatarSwitcherCardProps, 'title' | 'description' | 'icon'> & {
    showState?: boolean;
  };

const ControlledCard = ({
  checked: initialChecked = false,
  onChange,
  showState = false,
  ...props
}: ControlledCardProps) => {
  const [checked, setChecked] = useState(initialChecked);

  useEffect(() => {
    setChecked(initialChecked);
  }, [initialChecked]);

  const card = (
    <AvatarSwitcherCard
      {...props}
      checked={checked}
      onChange={value => {
        setChecked(value);
        onChange?.(value);
      }}
    />
  );

  if (!showState) {
    return card;
  }

  return (
    <Stack sx={{ gap: 2 }}>
      {card}
      <StatePreview checked={checked} />
    </Stack>
  );
};

const StatePreview = ({ checked }: { checked: boolean }) => (
  <Typography
    variant="globalXS"
    color="text.secondary"
  >
    Estado actual: <strong>{checked ? 'activado' : 'desactivado'}</strong>
  </Typography>
);

export const Default: Story = {
  render: args => (
    <ControlledCard
      {...args}
      showState
      pills={defaultPills}
      actions={[settingsAction]}
    />
  ),
  parameters: {
    docs: {
      description: {
        story:
          'Default configuration with status pills and a settings action. The switcher is controlled locally so you can toggle it in the canvas.',
      },
    },
  },
};

export const Minimal: Story = {
  render: args => <ControlledCard {...args} />,
  parameters: {
    docs: {
      description: {
        story:
          'Minimal variant with only avatar, title, description, and switcher — no pills or actions.',
      },
    },
  },
};

export const Checked: Story = {
  render: args => (
    <ControlledCard
      {...args}
      checked
      pills={defaultPills}
      actions={[settingsAction]}
    />
  ),
  parameters: {
    docs: {
      description: {
        story: 'Feature row with the switcher initially turned on.',
      },
    },
  },
};

export const Disabled: Story = {
  render: args => (
    <ControlledCard
      {...args}
      checked
      disabled
      pills={defaultPills}
      actions={[settingsAction]}
      slotProps={{
        switcher: {
          disabledTooltip: {
            description:
              'Activa el módulo principal para habilitar esta opción.',
          },
        },
      }}
    />
  ),
  parameters: {
    docs: {
      description: {
        story:
          'Disabled row: switcher, actions, and avatar are non-interactive. Use `slotProps.switcher.disabledTooltip` to explain why.',
      },
    },
  },
};

export const WithPillsOnly: Story = {
  render: args => (
    <ControlledCard
      {...args}
      pills={defaultPills}
    />
  ),
  parameters: {
    docs: {
      description: {
        story: 'Status pills without secondary actions.',
      },
    },
  },
};

export const WithActionsOnly: Story = {
  render: args => (
    <ControlledCard
      {...args}
      actions={[editAction, settingsAction]}
    />
  ),
  parameters: {
    docs: {
      description: {
        story:
          'Multiple icon-button actions without status pills — useful for configurable modules.',
      },
    },
  },
};

export const LongContent: Story = {
  render: args => (
    <ControlledCard
      {...args}
      title="Onboarding avanzado para colaboradores con procesos personalizados por área"
      description="Crea procesos detallados para darle la bienvenida a tus colaboradores y guiarlos durante sus primeras semanas en la organización."
      pills={[{ label: 'Beta', type: 'highlight', hasIcon: false }]}
      actions={[settingsAction]}
    />
  ),
  parameters: {
    docs: {
      description: {
        story:
          'Stress test for long title and description copy. Use the Width toolbar to validate responsive behavior on narrow viewports.',
      },
    },
  },
};

export const WithSlotProps: Story = {
  render: args => (
    <ControlledCard
      {...args}
      title="Reconocimientos"
      description="Permite que los colaboradores envíen reconocimientos públicos."
      icon={IconSparkles}
      pills={[{ label: 'New', type: 'success', hasIcon: false }]}
      actions={[settingsAction]}
      slotProps={{
        avatar: {
          color: 'highlight',
          size: 'large',
        },
        title: {
          sx: { maxWidth: 420 },
        },
        switcher: {
          sx: { width: 'auto' },
        },
      }}
    />
  ),
  parameters: {
    docs: {
      description: {
        story:
          'Customize inner slots via `slotProps` — avatar appearance, title constraints, and switcher layout.',
      },
    },
  },
};

const FeatureListExample = () => {
  const [onboardingEnabled, setOnboardingEnabled] = useState(true);
  const [recognitionEnabled, setRecognitionEnabled] = useState(false);
  const [notificationsEnabled, setNotificationsEnabled] = useState(true);

  return (
    <Stack sx={{ gap: 2, width: '100%' }}>
      <Typography
        variant="globalM"
        fontWeight="fontWeightSemiBold"
      >
        Módulos del workspace
      </Typography>
      <AvatarSwitcherCard
        title="Onboarding"
        description="Crea procesos para darle la bienvenida a tus colaboradores."
        icon={IconDoor}
        checked={onboardingEnabled}
        onChange={setOnboardingEnabled}
        pills={[{ label: 'New', type: 'success', hasIcon: false }]}
        actions={[settingsAction]}
      />
      <AvatarSwitcherCard
        title="Reconocimientos"
        description="Permite enviar reconocimientos públicos entre colaboradores."
        icon={IconSparkles}
        checked={recognitionEnabled}
        onChange={setRecognitionEnabled}
        pills={[{ label: 'Beta', type: 'highlight', hasIcon: false }]}
        actions={[editAction, settingsAction]}
      />
      <AvatarSwitcherCard
        title="Notificaciones push"
        description="Envía alertas en tiempo real a dispositivos móviles."
        icon={IconBell}
        checked={notificationsEnabled}
        onChange={setNotificationsEnabled}
        actions={[settingsAction]}
      />
    </Stack>
  );
};

export const FeatureList: Story = {
  render: () => <FeatureListExample />,
  parameters: {
    docs: {
      description: {
        story:
          'Typical settings-page layout with multiple independent toggles in a vertical list.',
      },
    },
  },
};
