import { useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

import { Checkbox, Radio, Stack, Typography } from '@mui/material';
import { type Meta, type StoryObj } from '@storybook/react-vite';

import DesignCheckbox from '../../design-system/Checkbox/Checkbox';
import RadioButton from '../../design-system/RadioButton/RadioButton';

import SelectionCard from './';
import FormSelectionCard from './form';

const meta: Meta<typeof SelectionCard> = {
  component: SelectionCard,
  title: 'Composed Components/Cards/SelectionCard',
  tags: ['autodocs'],
  args: {},
  render: props => {
    const [checked, setChecked] = useState(false);

    return (
      <SelectionCard
        {...props}
        checked={checked}
        onClick={setChecked}
        fullWidth
      >
        <Typography
          variant="globalS"
          color={theme => theme.palette.new.text.neutral.default}
        >
          {checked ? 'Seleccionado' : 'No seleccionado'}
        </Typography>
      </SelectionCard>
    );
  },
};

export default meta;

type Story = StoryObj<typeof SelectionCard>;

export const Default: Story = {
  args: {},
};

export const Disabled: Story = {
  args: {
    disabled: true,
  },
};

export const FormSelectionCardDefaultStory: Story = {
  render: () => {
    const form = useForm({
      defaultValues: {
        myInput: false,
      },
    });

    const { myInput } = form.watch();

    return (
      <FormProvider {...form}>
        <FormSelectionCard name="myInput">
          {myInput ? 'selecionado' : 'no seleccionado'}
        </FormSelectionCard>
      </FormProvider>
    );
  },
};

export const FormSelectionCardRadioButtonStory: Story = {
  render: () => {
    const form = useForm({
      defaultValues: {
        myInput: false,
      },
    });

    const { myInput } = form.watch();

    return (
      <FormProvider {...form}>
        <FormSelectionCard name="myInput">
          <Radio checked={myInput} />
        </FormSelectionCard>
      </FormProvider>
    );
  },
};

export const FormSelectionCardCheckBoxStory: Story = {
  render: () => {
    const form = useForm({
      defaultValues: {
        myInput: false,
      },
    });

    const { myInput } = form.watch();

    return (
      <FormProvider {...form}>
        <FormSelectionCard name="myInput">
          <Checkbox checked={myInput} />
        </FormSelectionCard>
      </FormProvider>
    );
  },
};

export const FormSelectionCardOnlyOneOptionStory: Story = {
  render: () => {
    const form = useForm({
      defaultValues: {
        mainRoute: {
          myInput1: false,
          myInput2: false,
        },
      },
    });

    const { mainRoute } = form.watch();

    return (
      <FormProvider {...form}>
        <Stack sx={{ gap: 1 }}>
          <FormSelectionCard
            name="mainRoute.myInput1"
            isOnlyOption
          >
            <Checkbox checked={mainRoute.myInput1} />
          </FormSelectionCard>
          <FormSelectionCard
            name="mainRoute.myInput2"
            isOnlyOption
          >
            <Checkbox checked={mainRoute.myInput2} />
          </FormSelectionCard>
        </Stack>
      </FormProvider>
    );
  },
  parameters: {
    docs: {
      description: {
        story:
          'La prop isOnlyOption deshabilita todas las opciónes marcadas, menos la clickeada. Para su uso correcto es necesario aplicarlo para cada elemento (FormSelectionCard)',
      },
    },
  },
};

const radioOptions = [
  { id: 1, label: 'Opción A' },
  { id: 2, label: 'Opción B' },
  { id: 3, label: 'Opción C' },
  { id: 4, label: 'Opción D' },
];

export const DisabledRadioListStory: Story = {
  render: () => {
    const selectedId = 2;

    return (
      <Stack sx={{ gap: 1, width: '100%' }}>
        {radioOptions.map(option => {
          const isSelected = option.id === selectedId;

          return (
            <SelectionCard
              key={option.id}
              checked={isSelected}
              disabled={!isSelected}
              fullWidth
            >
              <span style={{ pointerEvents: 'none' }}>
                <RadioButton
                  checked={isSelected}
                  isActive={isSelected}
                  disabled
                  label={option.label}
                />
              </span>
            </SelectionCard>
          );
        })}
      </Stack>
    );
  },
  parameters: {
    docs: {
      description: {
        story:
          'Lista de SelectionCards con RadioButtons en estado disabled, simulando el comportamiento de InputSelectableListItem con selección única.',
      },
    },
  },
};

const checkboxOptions = [
  { id: 1, label: 'Opción 1' },
  { id: 2, label: 'Opción 2' },
  { id: 3, label: 'Opción 3' },
  { id: 4, label: 'Opción 4' },
];

export const ReadOnlyCheckboxListStory: Story = {
  render: () => {
    const [selectedIds, setSelectedIds] = useState<number[]>([1, 3]);

    const toggle = (id: number) =>
      setSelectedIds(prev =>
        prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id],
      );

    return (
      <Stack sx={{ gap: 1, width: '100%' }}>
        {checkboxOptions.map(option => {
          const isSelected = selectedIds.includes(option.id);

          return (
            <SelectionCard
              key={option.id}
              checked={isSelected}
              onClick={() => toggle(option.id)}
              fullWidth
            >
              <DesignCheckbox
                checked={isSelected}
                readOnly={true}
                label={option.label}
              />
            </SelectionCard>
          );
        })}
      </Stack>
    );
  },
  parameters: {
    docs: {
      description: {
        story:
          'List of SelectionCards where the card is the state controller and the inner HuCheckbox is mounted with `readOnly` to act as a purely presentational indicator. Clicking anywhere on the card (empty area, checkbox square, or label) toggles the state exactly once — no need to wrap the checkbox in `<span style={{ pointerEvents: "none" }}>` or to call stopPropagation in handlers.',
      },
    },
  },
};

export const DisabledCheckboxListStory: Story = {
  render: () => {
    const selectedIds = [1, 3];

    return (
      <Stack sx={{ gap: 1, width: '100%' }}>
        {checkboxOptions.map(option => {
          const isSelected = selectedIds.includes(option.id);

          return (
            <SelectionCard
              key={option.id}
              checked={isSelected}
              disabled={!isSelected}
              fullWidth
            >
              <span style={{ pointerEvents: 'none' }}>
                <DesignCheckbox
                  checked={isSelected}
                  disabled
                  label={option.label}
                />
              </span>
            </SelectionCard>
          );
        })}
      </Stack>
    );
  },
  parameters: {
    docs: {
      description: {
        story:
          'Lista de SelectionCards con Checkboxes en estado disabled, simulando el comportamiento de InputSelectableListItem con selección múltiple.',
      },
    },
  },
};
