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

import { Box, Button, Typography } from '@mui/material';
import { type Meta, type StoryObj } from '@storybook/react-vite';

import FormSwitcherCard from './form';
import SwitcherCard from '.';

const meta: Meta<typeof SwitcherCard> = {
  component: SwitcherCard,
  title: 'Composed Components/Cards/SwitcherCard',
  tags: ['autodocs'],
  args: {
    sx: {
      width: '100%',
    },
    slotProps: {
      title: {
        title: 'Configuración de notificaciones',
        description: 'Gestiona tus preferencias de notificaciones',
      },
    },
    children: (
      <Box sx={{ p: 2, borderRadius: 1, backgroundColor: 'background.paper' }}>
        <Typography>
          Este es el contenido que se muestra cuando el switcher está activado.
          Puedes incluir cualquier componente o contenido aquí.
        </Typography>
      </Box>
    ),
  },
  argTypes: {
    disabled: {
      control: { type: 'boolean' },
    },
    open: {
      control: { type: 'boolean' },
    },
  },
};

export default meta;

type Story = StoryObj<typeof SwitcherCard>;

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

export const WithTooltip: Story = {
  args: {
    slotProps: {
      title: {
        title: 'Configuración avanzada',
        description: 'Opciones de configuración avanzada',
      },
      tooltip: {
        description: 'Esta configuración afecta el comportamiento del sistema',
      },
    },
  },
};

export const Disabled: Story = {
  args: {
    disabled: true,
    slotProps: {
      title: {
        title: 'Función deshabilitada',
        description: 'Esta función no está disponible',
      },
    },
  },
};

export const InitiallyOpen: Story = {
  args: {
    open: true,
    slotProps: {
      title: {
        title: 'Contenido inicialmente visible',
        description: 'El contenido se muestra por defecto',
      },
    },
  },
};

export const WithCallback: Story = {
  args: {
    slotProps: {
      title: {
        title: 'Con callback',
        description: 'Ejemplo con función de callback',
      },
    },
    onContentToggle: isOpen => {
      alert(`El contenido está ${isOpen ? 'abierto' : 'cerrado'}`);
    },
  },
};

// Componente wrapper para demostrar React Hook Form
const FormExample = () => {
  const methods = useForm({
    defaultValues: {
      example: false,
    },
  });

  const {
    handleSubmit,
    watch,
    formState: { errors },
  } = methods;

  const onSubmit = (data: any) => {
    // eslint-disable-next-line no-console
    console.log('Form data:', data);
    alert(`Datos del formulario: ${JSON.stringify(data, null, 2)}`);
  };

  const watchedValues = watch();

  return (
    <FormProvider {...methods}>
      <Box sx={{ width: '100%', maxWidth: 600 }}>
        <form onSubmit={handleSubmit(onSubmit)}>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <FormSwitcherCard
              name="example"
              switcherCardProps={{
                slotProps: {
                  title: {
                    title: 'Título de SwitcherCard',
                    description: 'Descripción de SwitcherCard',
                  },
                  tooltip: {
                    description: 'Tooltip de SwitcherCard',
                  },
                },
              }}
              rules={{
                required: 'Debes seleccionar una opción',
              }}
            >
              <Box
                sx={{
                  mt: 2,
                  p: 2,
                  borderRadius: 1,
                  backgroundColor: 'background.paper',
                }}
              >
                <Typography>
                  Lorem ipsum dolor sit amet consectetur adipisicing elit.
                </Typography>
              </Box>
            </FormSwitcherCard>

            <Box sx={{ mt: 2 }}>
              <Button
                type="submit"
                variant="contained"
                fullWidth
              >
                Guardar preferencias
              </Button>
            </Box>

            {errors.example && (
              <Typography
                color="error"
                variant="body2"
              >
                {errors.example.message}
              </Typography>
            )}

            <Box
              sx={{ mt: 2, p: 2, backgroundColor: 'grey.100', borderRadius: 1 }}
            >
              <Typography
                variant="h6"
                gutterBottom
              >
                Valores actuales del formulario:
              </Typography>
              <Typography
                variant="body2"
                component="pre"
              >
                {JSON.stringify(watchedValues, null, 2)}
              </Typography>
            </Box>
          </Box>
        </form>
      </Box>
    </FormProvider>
  );
};

export const WithForm: Story = {
  render: () => <FormExample />,
  parameters: {
    docs: {
      description: {
        story:
          'Ejemplo de uso del componente SwitcherCard integrado con React Hook Form usando el componente FormSwitcherCard.',
      },
    },
  },
};
