import {
  FormControl,
  FormHelperText,
  Box,
  Typography,
  Slider,
  TextField,
  Grid,
} from '@mui/material';
import { useFormContext, Controller } from 'react-hook-form';
import { type ReactNode } from 'react';
import type { IFormLayoutType } from '.';

export type SliderInputFormFieldProps = {
  max?: number;
  min?: number;
  step?: number;
  name: string;
  label: string;
  tooltip?: ReactNode;
  defaultValue?: number;
  className?: string;
} & IFormLayoutType;

export function SliderInputFormField({
  max = 100,
  min = 0,
  step = 1,
  label,
  name,
  tooltip,
  defaultValue = 0,
  className,
  layout = 'horizontal',
}: SliderInputFormFieldProps) {
  const { control, formState: { errors } } = useFormContext();

  const isHorizontal = layout === 'horizontal';

  return (
    <Box sx={{ mb: 3 }} className={className}>
      <Controller
        name={name}
        control={control}
        defaultValue={defaultValue}
        render={({ field }) => (
          <Box>
            <Typography 
              variant="h6" 
              gutterBottom={!isHorizontal}
              sx={{ 
                mb: isHorizontal ? 1 : 2,
                fontSize: isHorizontal ? '0.875rem' : '1.25rem',
                color: isHorizontal ? 'text.secondary' : 'text.primary'
              }}
            >
              {label}
              {tooltip && (
                <Typography 
                  component="span" 
                  variant="caption" 
                  sx={{ ml: 1, color: 'text.secondary' }}
                >
                  {tooltip}
                </Typography>
              )}
            </Typography>
            
            <Grid container spacing={2} alignItems="center">
              <Grid size={{xs: isHorizontal ? 8 : 9}}>
                <FormControl fullWidth>
                  <Slider
                    {...field}
                    min={min}
                    max={max}
                    step={step}
                    valueLabelDisplay="auto"
                    sx={{ mt: 1 }}
                  />
                </FormControl>
              </Grid>
              <Grid size={{xs: isHorizontal ? 4 : 3}}>
                <FormControl>
                  <TextField
                    {...field}
                    type="number"
                    size="small"
                    inputProps={{ min, max, step }}
                    sx={{ width: '80px' }}
                  />
                </FormControl>
              </Grid>
            </Grid>
            
            {errors[name] && (
              <FormHelperText error sx={{ mt: 1 }}>
                {errors[name]?.message as string}
              </FormHelperText>
            )}
          </Box>
        )}
      />
    </Box>
  );
}
