import React, { forwardRef, useEffect, useState } from 'react';

import { Container } from '@cleartrip/ct-design-container';
import type { ContainerRef } from '@cleartrip/ct-design-container';
import { Radio } from '@cleartrip/ct-design-radio';
import { Typography, TypographyVariant } from '@cleartrip/ct-design-typography';
import { makeStyles } from '@cleartrip/ct-design-style-manager';

import { IRadioGroup, IRadioOption } from './type';

const staticRadioGroupStyles = makeStyles((theme) => {
  return {
    root: {
      padding: theme?.spacing[2],
    },
    heading: {
      display: 'flex',
      flexDirection: 'column',
      marginBottom: theme?.spacing[3],
      color: theme?.color.text.primary,
    },
    radioContainer: {
      display: 'flex',
      flexDirection: 'column',
      marginBottom: theme?.spacing[3],
    },
  };
});

const RadioGroup = forwardRef<ContainerRef, IRadioGroup>(({ radioList, heading, onClick, styleConfig }, ref) => {
  const [selectedRadioOption, setSelectedRadioOption] = useState<IRadioOption | undefined>(undefined);

  const {
    root: customRootStyles = [],
    heading: customHeadingStyles = [],
    radioContainer: customRadioContainerStyles = [],
  } = styleConfig || {};

  useEffect(() => {
    const initialSelectedOption = radioList?.find((option) => option?.checked);
    setSelectedRadioOption(initialSelectedOption);
  }, [radioList]);

  const handleOptionClick = (selectedOption: IRadioOption) => {
    setSelectedRadioOption(selectedOption);
    onClick?.(selectedOption);
  };

  return (
    <Container ref={ref} styleConfig={{ root: [staticRadioGroupStyles?.root, ...customRootStyles] }}>
      {!!heading &&
        (typeof heading === 'string' ? (
          <Typography
            variant={TypographyVariant.B2}
            styleConfig={{ root: [staticRadioGroupStyles?.heading, ...customHeadingStyles] }}
          >
            {heading}
          </Typography>
        ) : (
          heading
        ))}
      {radioList?.map((radioOption: IRadioOption) => {
        return (
          <Container
            key={radioOption.id}
            styleConfig={{ root: [staticRadioGroupStyles?.radioContainer, ...customRadioContainerStyles] }}
          >
            <Radio
              id={radioOption?.id}
              label={typeof radioOption.label === 'string' ? radioOption.label : undefined}
              disabled={radioOption?.disabled}
              onChange={() => handleOptionClick(radioOption)}
              checked={radioOption?.id === selectedRadioOption?.id}
            />
          </Container>
        );
      })}
    </Container>
  );
});

RadioGroup.displayName = 'RadioGroup';

export default RadioGroup;
