import {
  Alert,
  Badge,
  Button,
  Fieldset,
  Group,
  Loader,
  Menu,
  SegmentedControl,
  Stack,
  Text,
  useMantineTheme,
} from '@mantine/core';
import { useInterval } from '@mantine/hooks';
import { modals } from '@mantine/modals';
import { notifications } from '@mantine/notifications';
import {
  IconCalendarClock,
  IconDatabase,
  IconFileTypeCsv,
  IconFileTypeSql,
  IconRecycle,
  IconSelect,
} from '@tabler/icons-react';
import { __, sprintf } from '@wordpress/i18n';
import { useEffect, useState } from 'react';
import useSWR from 'swr';
import {
  OptionNumberInput,
  OptionSelect,
  useOptionsContext,
} from '../components/Options';
import { exportWithFormat, post } from '../utils';

export function KeepCleanSettings({ analytics = 'clicks' }) {
  const { getOptions, updateOptions } = useOptionsContext();
  const [value, setValue] = useState();
  const theme = useMantineTheme();

  const { data, error, isLoading, isValidating, mutate } = useSWR(
    `wp_bannerize_get_${analytics}_count`,
    post,
  );
  const interval = useInterval(mutate, 5000);

  const label =
    analytics === 'clicks'
      ? __('Clicks', 'wp-bannerize')
      : __('Impressions', 'wp-bannerize');

  const handleChange = value => {
    setValue(value);
    updateOptions(`${analytics}.keep_clean`, value);
  };

  const handleCleanUp = async () => {
    modals.openConfirmModal({
      title: __('Please confirm your action'),
      centered: true,
      children: (
        <Text size="sm">
          {__(
            'Are you sure you want to run the clean up process? This action cannot be undone.',
            'wp-bannerize',
          )}
        </Text>
      ),
      labels: {
        confirm: __('Confirm', 'wp-bannerize'),
        cancel: __('Cancel', 'wp-bannerize'),
      },
      confirmProps: { color: 'red' },
      onConfirm: async () => {
        const response = await post(`wp_bannerize_keep_clean_${analytics}`, {
          mode: value,
        });

        mutate();

        if (+response > 0) {
          notifications.show({
            withBorder: true,
            color: 'green',
            title: sprintf(
              __('%s Clean Up successfully', 'wp-bannerize'),
              label,
            ),
            message: sprintf(
              __('%s %s have been deleted.', 'wp-bannerize'),
              response,
              label,
            ),
          });
        } else {
          notifications.show({
            withBorder: true,
            color: 'lime',
            title: sprintf(__('%s Clean Up', 'wp-bannerize'), label),
            message: sprintf(
              __('There are no %s to delete', 'wp-bannerize'),
              label,
            ),
          });
        }
      },
    });
  };

  const isDisabled = value === 'disabled';
  const isMaxRecords = value === 'delete_max_records_exceeded';
  const isRecentMonths = value === 'retain_within_recent_months';

  const schedules = [
    { value: 'manually', label: __('Manually', 'wp-bannerize') },
    { value: 'twicedaily', label: __('Twice Daily', 'wp-bannerize') },
    { value: 'daily', label: __('Once Daily', 'wp-bannerize') },
    { value: 'weekly', label: __('Once Weekly', 'wp-bannerize') },
  ];

  useEffect(() => {
    interval.start();
    return interval.stop;
  }, []);

  useEffect(() => {
    const value = getOptions(`${analytics}.keep_clean`);
    setValue(value);
  }, []);

  return (
    <Fieldset legend={__('Impressions table maintenance', 'wp-bannerize')}>
      <Stack>
        <Alert icon={<IconDatabase />}>
          <Group justify="space-between">
            <Text size="xs">
              {__('The current table contains', 'wp-bannerize')}{' '}
              <Badge>{isLoading ? <Loader size="xs" /> : data}</Badge>{' '}
              {sprintf(
                __(
                  '%s records. You can enable automatic table maintenance to keep the table clean.',
                  'wp-bannerize',
                ),
                label.toLowerCase(),
              )}
            </Text>
            {+data > 0 && (
              <Menu shadow="md" position="bottom-end" withArrow>
                <Menu.Target>
                  <Button
                    size="xs"
                    rightSection={<IconSelect style={{ width: 14 }} />}>
                    {__('Export', 'wp-bannerize')}
                  </Button>
                </Menu.Target>
                <Menu.Dropdown>
                  <Menu.Item
                    onClick={async () => {
                      exportWithFormat('csv', analytics);
                    }}
                    leftSection={
                      <IconFileTypeCsv
                        width={18}
                        color={theme.colors.blue[6]}
                      />
                    }>
                    {__('Export CSV', 'wp-bannerize')}
                  </Menu.Item>
                  <Menu.Item
                    onClick={async () => {
                      exportWithFormat('sql', analytics);
                    }}
                    leftSection={
                      <IconFileTypeSql
                        width={18}
                        color={theme.colors.blue[6]}
                      />
                    }>
                    {__('Export SQL', 'wp-bannerize')}
                  </Menu.Item>
                </Menu.Dropdown>
              </Menu>
            )}
          </Group>
        </Alert>
        <Group>
          <SegmentedControl
            size="xs"
            value={value}
            onChange={handleChange}
            data={[
              { label: __('Disabled', 'wp-bannerize'), value: 'disabled' },
              {
                label: __('Max Records', 'wp-bannerize'),
                value: 'delete_max_records_exceeded',
              },
              {
                label: __('Recent Months', 'wp-bannerize'),
                value: 'retain_within_recent_months',
              },
            ]}
          />
        </Group>
        {!isDisabled && (
          <Group align="end">
            {isMaxRecords && (
              <OptionNumberInput
                label={__(
                  'Delete records when the maximum is exceeded',
                  'wp-bannerize',
                )}
                min={100}
                path={`${analytics}.max_records`}
              />
            )}
            {isRecentMonths && (
              <OptionNumberInput
                label={__(
                  'Retain Impressions Within Recent Months',
                  'wp-bannerize',
                )}
                min={1}
                path={`${analytics}.num_months`}
              />
            )}
            {!isDisabled && (
              <Group>
                <OptionSelect
                  leftSection={<IconCalendarClock size={16} />}
                  data={schedules}
                  path={`${analytics}.schedules`}
                />
                <Button
                  size="xs"
                  color="red"
                  onClick={handleCleanUp}
                  rightSection={<IconRecycle size={16} />}>
                  {__('Clean up Now', 'wp-bannerize')}
                </Button>
              </Group>
            )}
          </Group>
        )}
      </Stack>
    </Fieldset>
  );
}
