import { Fragment, useEffect, useRef, useState } from 'react';
import DangerModal from '../components/shared/DangerModal';
import ImportRosterModal from '../components/team/ImportRosterModal';
import Form from 'react-bootstrap/Form';
import ContentCard from '../components/shared/ContentCard';
import { Button, InputGroup } from 'react-bootstrap';
import { getUser, updateUser } from '../api/Users';
import { useAuth } from '../auth/AuthProvider';
import { ExportData } from '../utils/ExportData';
import { useCSVReader } from 'react-papaparse';
import { addRosterFromCSV, getStaleUsers } from '../utils/ImportRosterHelper';
import { callClearData } from '../api/ClearData';
import TransferOwnershipModal from '../components/settings/TransferOwnershipModal';
import { imageDataURIs } from '../ImageExports';
import { Link } from 'react-router-dom';
import { useToast } from '../components/Toast/ToastContext';

const fileInputStyles = `
  .upload-button:hover:not(:disabled):not([readonly]) {
    background-color: var(--bs-secondary-bg);
  }
`;

// Settings page
export const Settings = () => {
  // Use OAuth2 to get the current user information
  const { user } = useAuth();
  const UNDEFINED_USER = -1;
  const [userId, setUserId] = useState<number>(UNDEFINED_USER);
  const [userType, setUserType] = useState<string>('');
  const [existingReceiveEmails, setExistingReceiveEmails] =
    useState<string>('');
  const [receiveEmails, setReceiveEmails] = useState<string>('');

  const { addToast } = useToast();

  // Modal logic
  const [showDangerModal, setShowDangerModal] = useState(false);
  const [dangerModalContent, setDangerModalContent] = useState<{
    title: string;
    bodyText: string;
    onPrimaryAction: () => void;
  } | null>(null);

  const [showImportModal, setShowImportModal] = useState(false);
  const [importModalContent, setImportModalContent] = useState<{
    title: string;
    staleUsers: any[];
    onPrimaryAction: () => void;
  } | null>(null);

  const [showTransferModal, setShowTransferModal] = useState(false);
  const [transferInitiated, setTransferInitiated] = useState(false);

  const userIsInstructor = userType === 'instructor';

  // Save Settings button logic
  const [enableSaveSettings, setEnableSaveSettings] = useState(false);

  // CSV Reader logic
  const { CSVReader } = useCSVReader();
  const [CSVData, setCSVData] = useState([]);

  // Import from CSV button logic
  const [enableImportRoster, setEnableImportRoster] = useState(false);
  const removeFileButton = useRef<HTMLButtonElement | null>(null);

  // Helper functions for the modal
  function openModalWithContent(action: string, staleUsers: any) {
    if (action === 'clear') {
      setDangerModalContent({
        title: 'Clear Data',
        bodyText:
          "Are you sure you want to clear all data from the app? Upon selecting 'Clear Data', all data other than instructors will be cleared from the application.",
        onPrimaryAction: handleClearData,
      });
      handleShow('danger');
    }
    if (action === 'import') {
      setImportModalContent({
        title: 'Import Roster from CSV',
        staleUsers: staleUsers,
        onPrimaryAction: handleImport,
      });
      handleShow('import');
    }
    if (action === 'transfer') {
      handleShow('transfer');
    }
  }

  function handleCloseDanger() {
    setShowDangerModal(false);
  }

  function handleCloseImport() {
    setShowImportModal(false);
  }

  function handleCloseTransfer() {
    setShowTransferModal(false);
  }

  function handleShow(type: string) {
    if (type === 'danger') {
      setShowDangerModal(true);
    }
    if (type === 'import') {
      setShowImportModal(true);
    }
    if (type === 'transfer') {
      setShowTransferModal(true);
    }
  }

  async function handleImport() {
    const APICreationErrors = await addRosterFromCSV(CSVData);
    setCSVData([]);
    handleCloseImport();
    if (APICreationErrors.length) {
      addToast(
        'Roster import failed due to file format errors. Ensure your roster file has valid headers and values.',
        'danger'
      );
    } else {
      removeFileButton.current?.click();
      setEnableImportRoster(false);

      addToast('Roster was imported without errors.', 'success');
    }
  }

  async function handleClearData() {
    try {
      await callClearData();
      handleCloseDanger();
      addToast('All application data has been cleared.', 'success');
    } catch (error: any) {
      addToast('Failed to clear application data.', 'danger');
    }
  }

  useEffect(() => {
    if (user) {
      setUserId(user.user_id ?? UNDEFINED_USER);
    }
  }, [user]);

  useEffect(() => {
    if (user) {
      setUserType(user.type);
    }
  }, [user]);

  // Set the state of the email notifications switch on page load using the user's current setting
  useEffect(() => {
    if (userId !== UNDEFINED_USER) {
      getUser(userId).then(function (retrievedUser) {
        if (retrievedUser.receive_emails) {
          setReceiveEmails(retrievedUser.receive_emails);
          setExistingReceiveEmails(retrievedUser.receive_emails);
        }
      });
    }
  }, [userId]);

  function handleExportButtonClick() {
    try {
      ExportData();
      addToast('Application data has been exported.', 'success');
    } catch (error: any) {
      addToast('Failed to export application data.', 'danger');
    }
  }

  async function saveSettings() {
    // Disable Save Changes button immediately
    setEnableSaveSettings(false);
    setExistingReceiveEmails(receiveEmails);
    try {
      await updateUser(userId, { receive_emails: receiveEmails });
      addToast('Your email preferences have been updated.', 'success');
    } catch (error: any) {
      addToast('Failed to update email preferences.', 'danger');
    }
  }

  const handleEmailCheckboxChange = (
    option: 'on_deliveries' | 'always',
    checked: boolean
  ) => {
    let receiveSetting;
    if (option === 'always') {
      receiveSetting = checked ? 'always' : 'on_custom';
    } else if (option === 'on_deliveries') {
      if (checked) {
        receiveSetting = 'on_deliveries';
      } else {
        receiveSetting = 'on_custom';
      }
    }

    if (receiveSetting != undefined) {
      setReceiveEmails(receiveSetting);
    }

    if (existingReceiveEmails !== receiveSetting) {
      setEnableSaveSettings(true);
    } else {
      setEnableSaveSettings(false);
    }
  };

  return (
    <Fragment>
      <style>{fileInputStyles}</style>
      <ContentCard
        title='Settings'
        description={`Adjust individual user settings${userIsInstructor ? ' and manage application data' : ''}.`}
        fullPage
      >
        <div className='mb-3 border rounded p-3'>
          <h5>Notification Preferences</h5>
          <p>
            Toggle the switches below for each type of email notification. All
            notifications are delivered within the ShipME application,
            regardless of email preferences.
          </p>
          <hr />
          <div className='container-fluid'>
            <div className='row g-3 mb-3'>
              <div className='col-md-6'>
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    marginLeft: '1.25rem',
                    marginRight: '1.25rem',
                  }}
                >
                  <Form>
                    <Form.Check
                      type='checkbox'
                      label='Receive emails for all notifications'
                      checked={receiveEmails === 'always'}
                      disabled={user?.type !== 'student'}
                      onChange={(e) =>
                        handleEmailCheckboxChange('always', e.target.checked)
                      }
                      style={{ transform: 'scale(1.1)' }}
                      className='mb-1'
                    />
                    <Form.Check
                      type='checkbox'
                      label='Receive emails for delivered requests'
                      checked={
                        receiveEmails === 'on_deliveries' ||
                        receiveEmails === 'always'
                      }
                      disabled={user?.type !== 'student'}
                      onChange={(e) =>
                        handleEmailCheckboxChange(
                          'on_deliveries',
                          e.target.checked
                        )
                      }
                      style={{ transform: 'scale(1.1)' }}
                      className='mb-1'
                    />
                    <Form.Check
                      type='checkbox'
                      disabled
                      checked={true}
                      label='You will always receive emails for custom messages'
                      style={{ transform: 'scale(1.1)' }}
                    />
                  </Form>
                </div>
                <div className='mt-3'>
                  <Button
                    title='Save Settings'
                    variant='primary'
                    className='w-100'
                    disabled={!enableSaveSettings}
                    onClick={() => saveSettings()}
                  >
                    Save Changes
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>

        {userIsInstructor && (
          <div className='mb-3 p-3 border rounded'>
            <div>
              <h5>Administrative Features</h5>
              <p>
                Import a new student roster, export the current application
                data, or clear all application data.
              </p>
              <hr />
              <div className='container-fluid'>
                <div className='row g-3 mb-3'>
                  <div className='col-md-6'>
                    <p className='mb-2'>
                      Import/re-sync a student roster from a CSV file (
                      <a
                        href='/src/assets/import_template.csv'
                        download='import_template.csv'
                      >
                        download template
                      </a>
                      ):
                    </p>
                    <CSVReader
                      onUploadAccepted={(results: any) => {
                        setCSVData(results.data);
                        setEnableImportRoster(true);
                      }}
                      config={{ skipEmptyLines: true }}
                      accept='.csv'
                    >
                      {({
                        getRootProps,
                        acceptedFile,
                        getRemoveFileProps,
                      }: any) => (
                        <div>
                          <InputGroup className={`flex-nowrap`}>
                            <Button
                              variant='light border'
                              className='upload-button'
                              style={{ color: 'var(--bs-body-color)' }}
                              {...getRootProps()}
                            >
                              Browse...
                            </Button>
                            <Form.Control
                              className='bg-white'
                              style={{ color: 'var(--bs-body-color)' }}
                              value={
                                acceptedFile
                                  ? acceptedFile.name
                                  : 'No file selected.'
                              }
                              disabled
                            />
                            <Button
                              variant='primary'
                              disabled={!enableImportRoster}
                              onClick={() => {
                                getStaleUsers([...CSVData]).then(
                                  (staleUsers: any[]) => {
                                    openModalWithContent('import', staleUsers);
                                  }
                                );
                              }}
                            >
                              Import
                            </Button>
                          </InputGroup>
                          <Button
                            ref={removeFileButton}
                            className='d-none'
                            {...getRemoveFileProps()}
                          />
                        </div>
                      )}
                    </CSVReader>
                  </div>
                  <div className='col-md-6'>
                    <p className='mb-2'>
                      Export current application data (request/order statistics)
                      to a CSV file:
                    </p>
                    <Button
                      title='Export Data'
                      variant='primary'
                      className='w-100'
                      onClick={() => handleExportButtonClick()}
                    >
                      Export Data
                    </Button>
                  </div>
                  {user?.is_admin === 'true' && (
                    <Fragment>
                      <div className='col-md-6'>
                        <p className='mb-2'>
                          Transfer application ownership to another instructor:
                        </p>
                        <Button
                          title='Transfer Ownership'
                          variant={transferInitiated ? 'warning' : 'danger'}
                          className='w-100'
                          onClick={() => openModalWithContent('transfer', null)}
                        >
                          {transferInitiated
                            ? 'Cancel Ownership Transfer'
                            : 'Transfer Ownership'}
                        </Button>
                      </div>
                      <div className='col-md-6'>
                        <p className='mb-2'>
                          Clear and reset all application data (except
                          instructors):
                        </p>
                        <Button
                          title='Clear Data'
                          variant='danger'
                          className='w-100'
                          onClick={() => openModalWithContent('clear', null)}
                        >
                          Clear Data
                        </Button>
                      </div>
                    </Fragment>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}

        <div className='p-3 text-center'>
          <div className='mb-3'>
            <img
              src={imageDataURIs.ShipMeLogo}
              height='55'
              className='d-inline-block align-top'
              alt='ShipME logo'
            />
          </div>
          <p className='mb-0'>
            Created by{' '}
            <Link
              to='https://www.linkedin.com/in/cobyfoy/'
              target='_blank'
              style={{ textDecoration: 'none', color: 'black' }}
            >
              Coby Foy
            </Link>
            ,{' '}
            <Link
              to='https://www.linkedin.com/in/tim-koehler-greer/'
              target='_blank'
              style={{ textDecoration: 'none', color: 'black' }}
            >
              Tim Koehler
            </Link>
            ,{' '}
            <Link
              to='https://www.linkedin.com/in/isaiah-pham/'
              target='_blank'
              style={{ textDecoration: 'none', color: 'black' }}
            >
              Isaiah Pham
            </Link>
            , and{' '}
            <Link
              to='https://www.linkedin.com/in/sulliops/'
              target='_blank'
              style={{ textDecoration: 'none', color: 'black' }}
            >
              Owen Sullivan
            </Link>{' '}
            for use by the{' '}
            <Link
              to='https://www.clemson.edu/cecas/departments/me/'
              target='_blank'
              style={{ textDecoration: 'none', color: 'black' }}
            >
              Clemson University Department of Mechanical Engineering
            </Link>
            .
          </p>
        </div>

        {dangerModalContent && (
          <DangerModal
            show={showDangerModal}
            handleClose={handleCloseDanger}
            title={dangerModalContent.title}
            bodyText={dangerModalContent.bodyText}
            confirmButtonText='Clear Data'
            onPrimaryAction={dangerModalContent.onPrimaryAction}
          />
        )}
        {importModalContent && (
          <ImportRosterModal
            show={showImportModal}
            handleClose={handleCloseImport}
            title={importModalContent.title}
            staleUsers={importModalContent.staleUsers}
            onPrimaryAction={importModalContent.onPrimaryAction}
          />
        )}
        <TransferOwnershipModal
          show={showTransferModal}
          handleClose={handleCloseTransfer}
          setTransferInitiated={setTransferInitiated}
        />
      </ContentCard>
    </Fragment>
  );
};
