import * as React from 'react';
import { Dayjs } from 'dayjs';
import useForkRef from '@mui/utils/useForkRef';
import { styled } from '@mui/material/styles';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DatePicker, DatePickerProps } from '@mui/x-date-pickers/DatePicker';
import {
  unstable_useDateField as useDateField,
  UseDateFieldProps,
} from '@mui/x-date-pickers/DateField';
import { useClearableField } from '@mui/x-date-pickers/hooks';
import {
  BaseSingleInputPickersTextFieldProps,
  BaseSingleInputFieldProps,
  DateValidationError,
  FieldSection,
} from '@mui/x-date-pickers/models';
import { Unstable_PickersSectionList as PickersSectionList } from '@mui/x-date-pickers/PickersSectionList';
import { alpha, IconButton } from '@mui/material';
import { ClearIcon } from '@mui/x-date-pickers';
import SvgColor from '../svg-color';

const BrowserFieldRoot = styled('div', { name: 'BrowserField', slot: 'Root' })({
  display: 'flex',
  alignItems: 'center',
  padding: '4px',
  gap: '2px',
});

const BrowserFieldIcon = styled('div', { name: 'BrowserField', slot: 'Icon' })({
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  cursor: 'pointer',
});

const BrowserFieldContent = styled('div', {
  name: 'BrowserField',
  slot: 'Content',
})(({ theme }) => ({
  flex: 1,
  color: alpha(theme.palette.text.secondary, 0.4),
  fontSize: 12,
  lineHeight: 'normal',
  whiteSpace: 'nowrap',
}));

interface BrowserTextFieldProps
  extends BaseSingleInputPickersTextFieldProps<true>,
    Omit<React.HTMLAttributes<HTMLDivElement>, keyof BaseSingleInputPickersTextFieldProps<true>> {
  onClear?: React.MouseEventHandler<Element> | undefined;
}

const BrowserTextField = React.forwardRef(
  (
    props: BrowserTextFieldProps & {
      onClear: React.MouseEventHandler<Element> | undefined;
    },
    ref: React.Ref<unknown>
  ) => {
    const {
      elements,
      sectionListRef,
      contentEditable,
      onFocus,
      onBlur,
      tabIndex,
      onInput,
      onPaste,
      onKeyDown,
      InputProps: { ref: InputPropsRef, startAdornment } = {},
      value,
      onClear,
      ...other
    } = props;

    const handleRef = useForkRef(InputPropsRef, ref);

    return (
      <BrowserFieldRoot ref={handleRef} {...other}>
        {startAdornment}
        <BrowserFieldContent>
          <PickersSectionList
            elements={elements}
            sectionListRef={sectionListRef}
            contentEditable={contentEditable}
            onFocus={onFocus}
            onBlur={onBlur}
            tabIndex={tabIndex}
            onInput={onInput}
            onPaste={onPaste}
            onKeyDown={onKeyDown}
          />
        </BrowserFieldContent>

        {value && onClear && (
          <IconButton size="small" onClick={onClear} sx={{ m: 0, p: 0 }}>
            <ClearIcon fontSize="small" />
          </IconButton>
        )}
      </BrowserFieldRoot>
    );
  }
);

interface BrowserDateFieldProps
  extends UseDateFieldProps<Dayjs, true>,
    BaseSingleInputFieldProps<Dayjs | null, Dayjs, FieldSection, true, DateValidationError> {}

const BrowserDateField = React.forwardRef(
  (props: BrowserDateFieldProps, ref: React.Ref<HTMLDivElement>) => {
    const { slots, slotProps, ...textFieldProps } = props;

    const fieldResponse = useDateField<Dayjs, true, typeof textFieldProps>({
      ...textFieldProps,
      enableAccessibleFieldDOMStructure: true,
    });

    const processedFieldProps = useClearableField({
      ...fieldResponse,
      slots,
      slotProps,
    });

    return <BrowserTextField onClear={props.onClear} ref={ref} {...processedFieldProps} />;
  }
);
const BrowserYearMonthDatePicker = React.forwardRef(
  (
    props: DatePickerProps<Dayjs> & {
      onClear: React.MouseEventHandler<Element> | undefined;
    },
    ref: React.Ref<HTMLDivElement>
  ) => {
    const { value, onChange, onClear, ...rest } = props;
    const [open, setOpen] = React.useState(false);

    const handleToggle = () => setOpen((prev) => !prev);

    return (
      <DatePicker
        ref={ref}
        open={open}
        onClose={() => setOpen(false)}
        value={value}
        onChange={onChange}
        format="YYYY-MM"
        views={['year', 'month']}
        openTo="month"
        {...rest}
        slots={{ field: BrowserDateField, ...props.slots }}
        slotProps={{
          ...props.slotProps,
          field: {
            ...(props.slotProps?.field || {}),
            value,
            onClear,
            InputProps: {
              startAdornment: (
                <BrowserFieldIcon onClick={handleToggle}>
                  <SvgColor
                    src="/assets/icons/ic_date.svg"
                    sx={{
                      color: 'text.secondary',
                      width: 14,
                      mr: '2px',
                    }}
                  />
                </BrowserFieldIcon>
              ),
            },
          },
        }}
      />
    );
  }
);
BrowserTextField.displayName = 'BrowserTextField';
BrowserDateField.displayName = 'BrowserDateField';
BrowserYearMonthDatePicker.displayName = 'BrowserYearMonthDatePicker';


interface BrowserV7FieldProps {
  value: Dayjs | null;
  onChange: (newValue: Dayjs | null) => void;
  onClear: React.MouseEventHandler<Element> | undefined;
}

export default function CustomYearMonthDatePicker({
  value,
  onChange,
  onClear,
}: BrowserV7FieldProps) {
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="fr">
      <BrowserYearMonthDatePicker
        value={value}
        onChange={onChange}
        onClear={onClear}
        slotProps={{
          field: { clearable: true },
        }}
      />
    </LocalizationProvider>
  );
}
