import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Close } from '@mui/icons-material';

import * as playerSelectors from '../../../redux/selectors';
import { getInputPropsByName } from '@/modules/@common/Form/helpers';
import {
  removeErrorByPropAction,
  setAction,
  setSelectorAction,
  setSelectorsAction,
} from '@/modules/players/Editor/redux/slices';

import { FormRow, FormSection, useFormSettings } from '@/modules/@common/Form';
import PlaceholderList from './components/PlaceholderList/PlaceholderList';
import { Button, IconButton, InputAdornment, Switch, TextField } from '@/mui/components';

function CustomPlaceholderTab() {
  const dispatch = useDispatch();
  const { size } = useFormSettings();
  const customPlaceholderEnable = useSelector(playerSelectors.customPlaceholderEnableSelector);
  const scheme = useSelector(playerSelectors.schemeSelector);
  const selectors = useSelector(playerSelectors.selectorsSelector);

  // local state
  const [placeholderSelector, setPlaceholderSelector] = useState('');

  const handleSetState = (state) => dispatch(setAction(state)); //
  const [error, setError] = useState('');

  const applySelector = () => {
    const hasDuplicate = selectors?.some((item) => item.selector === placeholderSelector);
    if (!hasDuplicate) {
      dispatch(
        setSelectorAction({
          id: `${Math.random().toString(36)}`,
          selector: placeholderSelector,
        }),
      );
      setPlaceholderSelector('');
    }
    setError(hasDuplicate ? 'Selector already exists' : '');
  };
  const selectorValidation = getInputPropsByName(scheme, ['placeholderSelector']);
  return (
    <FormSection>
      <FormRow
        label="Set Custom Placeholder Selector"
        tooltip="For DFP/GAM or header embeds only. Use a <div> placeholder and verify the player loads correctly after changes."
      >
        <Switch
          color="primary"
          size={size}
          checked={customPlaceholderEnable}
          onChange={({ target }) =>
            handleSetState({
              customPlaceholderEnable: target.checked,
            })
          }
        />
      </FormRow>
      {customPlaceholderEnable && (
        <>
          <FormRow fullWidth>
            <TextField
              size={size}
              placeholder="Add placeholder selector"
              value={placeholderSelector}
              InputProps={{
                endAdornment: placeholderSelector ? (
                  <InputAdornment position="end">
                    <IconButton
                      size={size}
                      onClick={() => {
                        setPlaceholderSelector('');
                        setError('');
                      }}
                    >
                      <Close />
                    </IconButton>
                  </InputAdornment>
                ) : null,
              }}
              onChange={({ target: { value } }) => {
                setPlaceholderSelector(value);
                setError('');
              }}
              onKeyDown={(event) => {
                if (event.key === 'Enter' && customPlaceholderEnable && placeholderSelector.trim()) {
                  applySelector();
                }
              }}
              {...selectorValidation}
              error={selectorValidation.error || !!error}
              helperText={selectorValidation.helperText || error}
              onFocus={() => {
                setError('');
                dispatch(removeErrorByPropAction(['placeholderSelector']));
              }}
            />
            <Button
              variant="outlined"
              size={size}
              color="neutral"
              shape="rounded"
              disabled={!placeholderSelector.trim()}
              onClick={() => {
                applySelector();
              }}
            >
              Add
            </Button>
          </FormRow>
          {selectors && (
            <FormRow fullWidth>
              <PlaceholderList
                fields={selectors}
                scheme={scheme}
                removeErrorByPropAction={(keyArray) => dispatch(removeErrorByPropAction(keyArray))}
                onSetField={(items) => {
                  dispatch(setSelectorsAction(items));
                }}
              />
            </FormRow>
          )}
        </>
      )}
    </FormSection>
  );
}

export default CustomPlaceholderTab;
