import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import CachedIcon from '@mui/icons-material/Cached';

import {
  ACCOUNT_OPTIONS,
  ACCOUNT_TYPE_ALL,
  ACCOUNT_TYPE_DEMAND,
  ACCOUNT_TYPE_PUBLISHER,
  FILTER_VIDEO_DUPLICATES_BY_OPTIONS,
} from '../../../../List/constants';
import { FEE_BUSINESS_MODEL_IMPRESSIONS_CPM, FEE_BUSINESS_MODEL_OPTIONS } from '../../../constants';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import * as selectors from '../../../redux/selectors';
import { getSalesforceDataAction, removeErrorByPropAction, setAction } from '../../../redux/slices';
import { getInputPropsByName } from '@/modules/@common/Form/helpers';
import { showNotificationAction } from '@/modules/layout/redux/slices';

import { FormImageUploader, FormRow, useFormSettings } from '@/modules/@common/Form';
import { CircularProgress, IconButton, InputAdornment, MenuItem, Select, Switch, TextField } from '@/mui/components';
import { CustomSalesForce } from '@/mui/components/CustomIcon';

import styles from './DetailsTab.module.scss';

const accountOptions = ACCOUNT_OPTIONS.filter((account) => account.value !== ACCOUNT_TYPE_ALL);

const FIELD_CUSTOM_LOADING_MAX_LENGTH_NAME = 15;
const LOGO_MAX_SIZE = 1024 * 1024; // 1 MB
const MAX_WIDTH = 1000;
const MAX_HEIGHT = 1000;

async function validateImageDimensions(file) {
  return new Promise((resolve) => {
    const img = new Image();
    const reader = new FileReader();

    reader.onload = (e) => {
      img.src = e.target.result;
    };

    img.onload = () => {
      const width = img.naturalWidth;
      const height = img.naturalHeight;
      const isValid = !(width >= MAX_WIDTH && height >= MAX_HEIGHT);
      resolve(isValid);
    };

    reader.readAsDataURL(file);
  });
}

function DetailsTab() {
  const { size } = useFormSettings();
  const dispatch = useDispatch();
  const router = useRouter();

  const salesforceId = useSelector(selectors.salesforceIdSelector);
  const salesforceInstanceUrl = useSelector(selectors.salesforceInstanceUrlSelector);
  const isSalesforceDataLoading = useSelector(selectors.isSalesforceDataLoadingSelector);
  const name = useSelector(selectors.nameSelector);
  const salesManager = useSelector(selectors.salesManagerSelector);
  const accountManager = useSelector(selectors.accountManagerSelector);
  const accountManagerEmail = useSelector(selectors.accountManagerEmailSelector);
  const type = useSelector(selectors.typeSelector);
  const avatarUrl = useSelector(selectors.avatarUrlSelector);
  const customLogoUrl = useSelector(selectors.customLogoUrlSelector);
  const customLoadingMessage = useSelector(selectors.customLoadingMessageSelector);
  const customLoginPageUrl = useSelector(selectors.customLoginPageUrlSelector);
  const subdomain = useSelector(selectors.subdomainSelector);
  const publisherRevShare = useSelector(selectors.publisherRevShareSelector);
  const expenses = useSelector(selectors.expensesSelector);
  const usersLimit = useSelector(selectors.usersLimitSelector);
  const videoDuplicatesBy = useSelector(selectors.videoDuplicatesBy);

  const publisherDemand = useSelector(selectors.publisherDemandSelector);
  const adServingFeeBusinessModel = useSelector(selectors.adServingFeeBusinessModelSelector);
  const adServingFeeDisplay = useSelector(selectors.adServingFeeDisplaySelector);
  const adServingFeeVideo = useSelector(selectors.adServingFeeVideoSelector);

  const scheme = useSelector(selectors.schemeSelector);

  const id = parseInt(router.query.id, 10);
  const isReadOnly = !!id;

  const handleSetState = (state) => dispatch(setAction(state));
  const handleGetSalesforceDataAction = () => dispatch(getSalesforceDataAction());
  const handleGotoSalesforceAccountPage = () => {
    const instanceUrlPrefix = salesforceInstanceUrl.slice(0, salesforceInstanceUrl.indexOf('.'));
    window.open(`${instanceUrlPrefix}.lightning.force.com/lightning/r/Account/${salesforceId}/view`);
  };

  return (
    <>
      <FormRow label="Salesforce Account Id">
        <TextField
          size={size}
          placeholder="Enter Salesforce Account Id"
          value={salesforceId}
          disabled={isReadOnly || isSalesforceDataLoading}
          onChange={(e) =>
            handleSetState({
              salesforceId: e.target.value,
              name: '',
              salesManager: '',
              accountManager: '',
              accountManagerEmail: '',
              type: '',
              accountDashboards: null,
            })
          }
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <IconButton
                  disabled={isReadOnly || !salesforceId || isSalesforceDataLoading}
                  onClick={handleGetSalesforceDataAction}
                >
                  {isSalesforceDataLoading ? <CircularProgress size="xSmall" /> : <CachedIcon />}
                </IconButton>
              </InputAdornment>
            ),
          }}
          {...getInputPropsByName(scheme, ['salesforceId'])}
          onFocus={() => dispatch(removeErrorByPropAction(['salesforceId']))}
        />
      </FormRow>
      <FormRow label="Account Name">
        <TextField
          size={size}
          placeholder=""
          value={name}
          disabled
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <IconButton color="primary" onClick={handleGotoSalesforceAccountPage} disabled={!name}>
                  <CustomSalesForce className={!name ? '' : styles.SalesForceIcon} />
                </IconButton>
              </InputAdornment>
            ),
          }}
          onChange={(e) => handleSetState({ name: e.target.value })}
          {...getInputPropsByName(scheme, ['name'])}
          onFocus={() => dispatch(removeErrorByPropAction(['name']))}
        />
      </FormRow>
      {type === ACCOUNT_TYPE_DEMAND && (
        <>
          <FormRow label="Publisher Demand">
            <Switch
              color="primary"
              size={size}
              checked={publisherDemand}
              disabled={isReadOnly}
              onChange={(e) =>
                handleSetState({
                  publisherDemand: e.target.checked,
                })
              }
            />
          </FormRow>

          {publisherDemand && (
            <>
              <FormRow label="Ad-Serving Fee - Business Model">
                <Select
                  size={size}
                  placeholder="Select Ad-Serving Fee-Business Model"
                  value={adServingFeeBusinessModel}
                  onChange={(event) => handleSetState({ adServingFeeBusinessModel: event.target.value })}
                >
                  {FEE_BUSINESS_MODEL_OPTIONS.map((option) => (
                    <MenuItem key={option.value} value={option.value}>
                      {option.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormRow>

              <FormRow
                label={`Ad-Serving Fee-Video 
                (${adServingFeeBusinessModel === FEE_BUSINESS_MODEL_IMPRESSIONS_CPM ? '$' : '%'})`}
              >
                <TextField
                  type="number"
                  size={size}
                  placeholder=""
                  value={adServingFeeVideo}
                  onChange={(e) => handleSetState({ adServingFeeVideo: parseFloat(e.target.value) })}
                  {...getInputPropsByName(scheme, ['adServingFeeVideo'])}
                  onFocus={() => dispatch(removeErrorByPropAction(['adServingFeeVideo']))}
                />
              </FormRow>

              <FormRow
                label={`Ad-Serving Fee-Display
                (${adServingFeeBusinessModel === FEE_BUSINESS_MODEL_IMPRESSIONS_CPM ? '$' : '%'})`}
              >
                <TextField
                  type="number"
                  size={size}
                  placeholder=""
                  value={adServingFeeDisplay}
                  onChange={(e) => handleSetState({ adServingFeeDisplay: parseFloat(e.target.value) })}
                  {...getInputPropsByName(scheme, ['adServingFeeDisplay'])}
                  onFocus={() => dispatch(removeErrorByPropAction(['adServingFeeDisplay']))}
                />
              </FormRow>
            </>
          )}
        </>
      )}
      <FormRow label="Sales Manager">
        <TextField
          size={size}
          placeholder=""
          value={salesManager}
          disabled
          onChange={(e) => handleSetState({ salesManager: e.target.value })}
        />
      </FormRow>
      <FormRow label="Account Manager">
        <TextField
          size={size}
          placeholder=""
          value={accountManager}
          disabled
          onChange={(e) => handleSetState({ accountManager: e.target.value })}
        />
      </FormRow>
      <FormRow label="Account Manager Email">
        <TextField
          size={size}
          placeholder=""
          value={accountManagerEmail}
          disabled
          onChange={(e) => handleSetState({ accountManagerEmail: e.target.value })}
        />
      </FormRow>
      <FormRow label="Type">
        <Select
          size={size}
          placeholder="Select type"
          value={type}
          disabled
          onChange={(event) => handleSetState({ type: event.target.value })}
        >
          {accountOptions.map((option) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
        </Select>
      </FormRow>
      <FormRow
        label="Custom Logo"
        tooltip="Your logo will be displayed in Watch.
        Dark mode logo preferred Dimensions: Max width: 152px, Max height: 46px"
      >
        <FormImageUploader
          image={avatarUrl}
          accept=".jpeg, .jpg, .png"
          restrictionMessage="JPEG, PNG."
          onValidateAsync={async (file) => {
            const allowedFormats = ['image/jpeg', 'image/png'];

            // Check image dimensions
            const isValidDimensions = await validateImageDimensions(file);
            if (!isValidDimensions) {
              dispatch(
                showNotificationAction({
                  key: 'Invalid image dimensions',
                  type: TYPE_ERROR,
                  message: `File has the wrong dimensions. It must be less than ${MAX_WIDTH}px by ${MAX_HEIGHT}px`,
                }),
              );
              return false;
            }

            if (!allowedFormats.includes(file.type)) {
              dispatch(
                showNotificationAction({
                  key: 'The file type is not supported',
                  type: TYPE_ERROR,
                  message: 'The file type is not supported',
                }),
              );
              return false;
            }

            if (file.size >= LOGO_MAX_SIZE) {
              dispatch(
                showNotificationAction({
                  key: 'File is too large!',
                  type: TYPE_ERROR,
                  message: 'File is too large! Max size is 1Mb',
                }),
              );
              return false;
            }

            return true;
          }}
          onLoad={(event, file, fileResult) => {
            handleSetState({
              avatarUrl: fileResult,
              avatar: {
                base64Url: fileResult,
                mimeType: file.type,
              },
            });
          }}
          onError={(event, file, error) => {
            dispatch(
              showNotificationAction({
                key: error,
                type: TYPE_ERROR,
                message: error,
              }),
            );
          }}
          onRemove={() => {
            handleSetState({
              avatarUrl: '',
              avatar: { base64Url: '', mimeType: '' },
            });
          }}
        />
      </FormRow>
      <FormRow label="Custom Logo URL">
        <TextField
          size={size}
          placeholder="Enter Custom Logo URL"
          value={customLogoUrl}
          onChange={(e) => handleSetState({ customLogoUrl: e.target.value })}
          {...getInputPropsByName(scheme, ['customLogoUrl'])}
          onFocus={() => dispatch(removeErrorByPropAction(['customLogoUrl']))}
          label=""
        />
      </FormRow>
      <FormRow label="Custom Loading Message">
        <TextField
          size={size}
          placeholder="Enter Custom Loading Message"
          value={customLoadingMessage}
          onChange={(e) => handleSetState({ customLoadingMessage: e.target.value })}
          inputProps={{ maxLength: FIELD_CUSTOM_LOADING_MAX_LENGTH_NAME }}
        />
      </FormRow>
      <FormRow label="Custom Login Page">
        <TextField
          multiline
          minRows={3}
          maxRows={3}
          size={size}
          placeholder="Enter Custom Login Page"
          value={customLoginPageUrl}
          onChange={(e) => handleSetState({ customLoginPageUrl: e.target.value })}
          {...getInputPropsByName(scheme, ['customLoginPageUrl'])}
          onFocus={() => dispatch(removeErrorByPropAction(['customLoginPageUrl']))}
          label=""
        />
      </FormRow>
      <FormRow label="Subdomain">
        <TextField
          size={size}
          placeholder="Subdomain"
          value={subdomain}
          onChange={(e) => handleSetState({ subdomain: e.target.value })}
        />
      </FormRow>
      {type === ACCOUNT_TYPE_PUBLISHER && (
        <>
          <FormRow label="Publisher Rev-Share (%)">
            <TextField
              type="number"
              size={size}
              placeholder="Publisher Rev-Share"
              value={publisherRevShare}
              onChange={(e) => handleSetState({ publisherRevShare: e.target.value })}
              {...getInputPropsByName(scheme, ['publisherRevShare'])}
              onFocus={() => dispatch(removeErrorByPropAction(['publisherRevShare']))}
            />
          </FormRow>
          <FormRow label="Expenses (%)">
            <TextField
              type="number"
              size={size}
              placeholder="Expenses"
              value={expenses}
              onChange={(e) => handleSetState({ expenses: e.target.value })}
              {...getInputPropsByName(scheme, ['expenses'])}
              onFocus={() => dispatch(removeErrorByPropAction(['expenses']))}
            />
          </FormRow>
        </>
      )}
      <FormRow label="User Limit">
        <TextField
          type="number"
          size={size}
          placeholder="Total Number of Users"
          value={usersLimit}
          onChange={(e) => handleSetState({ usersLimit: e.target.value })}
          {...getInputPropsByName(scheme, ['usersLimit'])}
          onFocus={() => dispatch(removeErrorByPropAction(['usersLimit']))}
        />
      </FormRow>
      <FormRow label="Filter Video Duplicates by">
        <Select
          size={size}
          placeholder="Select Video Duplicates by"
          value={videoDuplicatesBy}
          onChange={(event) => handleSetState({ videoDuplicatesBy: event.target.value })}
        >
          {FILTER_VIDEO_DUPLICATES_BY_OPTIONS.map((option) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
        </Select>
      </FormRow>
    </>
  );
}

export default DetailsTab;
