import {
  Box,
  Checkbox,
  CustomModalLayout,
  CustomModalLayoutProps,
  FormField,
  Input,
  Text,
} from '@wix/design-system';
import React, { useState } from 'react';
import _ from 'lodash';

export type SettingsPreferences = {
  groupType?: 'views' | 'tabs';
  filters?: boolean;
  dnd?: boolean;
  customColumns?: boolean;
  addNew?: boolean;
  bulkActions?: boolean;
  advancedSorting?: boolean;
  limit: number;
  initialError?: boolean;
  refreshError?: boolean;
  fetchNextPageError?: boolean;
  fetchTranslationsError?: boolean;
};

export interface SettingsModalLayoutProps extends CustomModalLayoutProps {
  ok: (preferences: SettingsPreferences) => void;
  cancel: () => void;
  preferences: SettingsPreferences;
}

type SettingsKeys = keyof SettingsPreferences;

type SupportedFeatures = {
  [key in SettingsKeys]: string | { key: string; value: string }[];
};

const features: SupportedFeatures = {
  initialError: '',
  refreshError: '',
  fetchNextPageError: '',
  fetchTranslationsError: '',
  groupType: [
    { key: 'views', value: 'Views' },
    { key: 'tabs', value: 'Tabs' },
  ],
  addNew: 'Add New Item',
  bulkActions: 'Bulk Actions',
  customColumns: 'Custom Columns',
  dnd: 'Drag & Drop',
  filters: 'Filters',
  advancedSorting: 'Advanced Sorting',
  limit: 'Limit',
};

export const SettingsModalLayout = (props: SettingsModalLayoutProps) => {
  const { ok, cancel, preferences: oldPreferences, ...rest } = props;

  const [preferences, setPreferences] = useState({ ...oldPreferences });

  return (
    <CustomModalLayout
      primaryButtonText="Save"
      primaryButtonOnClick={() => {
        ok(preferences);
      }}
      secondaryButtonOnClick={() => cancel()}
      onCloseButtonClick={() => cancel()}
      secondaryButtonText="Cancel"
      title="Demo Settings"
      {...rest}
    >
      <Box gap="SP3" direction="vertical">
        <Box direction="vertical" gap="SP2" paddingBottom="SP3">
          <Text>Features:</Text>
          {_.reduce<SupportedFeatures, JSX.Element[]>(
            features,
            (acc, value, key) => {
              const feature = key as SettingsKeys;
              if (_.isArray(value)) {
                return _.concat(
                  acc,
                  value.map((option) => (
                    <Checkbox
                      key={option.key}
                      checked={preferences[feature] === option.key}
                      onChange={() =>
                        setPreferences({
                          ...preferences,
                          [key]:
                            preferences[feature] !== option.key
                              ? option.key
                              : undefined,
                        })
                      }
                    >
                      {option.value}
                    </Checkbox>
                  )),
                );
              }

              if (typeof preferences[feature] === 'number') {
                acc.push(
                  <FormField key={key} label={value}>
                    <Input
                      key={key}
                      value={preferences[feature] as number}
                      onChange={(e) => {
                        const { value: newValue } = e.target;
                        setPreferences({
                          ...preferences,
                          [key]: newValue ? parseInt(newValue, 10) : 10,
                        });
                      }}
                    />
                  </FormField>,
                );
                return acc;
              }
              acc.push(
                <Checkbox
                  key={key}
                  checked={!!preferences[feature]}
                  onChange={() =>
                    setPreferences({
                      ...preferences,
                      [key]: !preferences[feature],
                    })
                  }
                >
                  {value || _.startCase(key)}
                </Checkbox>,
              );

              return acc;
            },
            [],
          )}
        </Box>
      </Box>
    </CustomModalLayout>
  );
};
