import React, { useState, useEffect } from 'react';
import {
  Card, CardContent, Typography, Button, Box, TextField, Checkbox, FormControlLabel
} from '@mui/material';
import AlertComponent from '../components/Alert';

const OtherSettings = () => {
  const [alertState, setAlertState] = useState({
    showAlert: false,
    msg: '',
    severity: 'success',
  });
  const [checkoutText, setCheckoutText] = useState('');
  const [suppressRateQuotes, setSuppressRateQuotes] = useState(false);
  const [saveLoading, setSaveLoading] = useState(false);

  useEffect(() => {
    
    const savedCheckoutText = localStorage.getItem('enitureSacCheckoutText');
    const savedSuppressQuotes = localStorage.getItem('enitureSacSuppressQuotes');
  
    if (savedCheckoutText !== null && savedSuppressQuotes !== null) {
      setCheckoutText(savedCheckoutText);
      setSuppressRateQuotes(savedSuppressQuotes === 'true');
    } else {
      
      fetch(`${eniture_sac.eniture_sac_rest_url}get-other-settings`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            const apiCheckoutText = data.checkoutText || '';
            const apiSuppressQuotes = data.suppressRateQuotes || false;
  
            setCheckoutText(apiCheckoutText);
            setSuppressRateQuotes(apiSuppressQuotes);
  
            localStorage.setItem('enitureSacCheckoutText', apiCheckoutText);
            localStorage.setItem('enitureSacSuppressQuotes', apiSuppressQuotes.toString());
          } else {
            setAlertState({
              showAlert: true,
              msg: 'Failed to fetch settings from the server: ' + data.message,
              severity: 'error',
            });
          }
        })
        .catch(error => {
          setAlertState({
            showAlert: true,
            msg: 'An error occurred while fetching settings from the server.',
            severity: 'error',
          });
        });
    }
  }, []);
  

  const handleSaveSettings = () => {
    if (checkoutText.length > 0 && checkoutText.length > 50) {
      setAlertState({
        showAlert: true,
        msg: 'Checkout text must be 50 characters or less',
        severity: 'error',
      });
      return;
    }    

    setSaveLoading(true);

    fetch(`${eniture_sac.eniture_sac_rest_url}save-other-settings`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        checkoutText,
        suppressRateQuotes,
      }),
    })
      .then(response => response.json())
      .then(data => {
        setSaveLoading(false);
        if (data.success) {
          
          localStorage.setItem('enitureSacCheckoutText', checkoutText);
          localStorage.setItem('enitureSacSuppressQuotes', suppressRateQuotes.toString());

          setAlertState({
            showAlert: true,
            msg: 'Settings saved successfully.',
            severity: 'success',
          });
        } else {
          setAlertState({
            showAlert: true,
            msg: 'Failed to save settings: ' + data.message,
            severity: 'error',
          });
        }
      })
      .catch(error => {
        setSaveLoading(false);
        setAlertState({
          showAlert: true,
          msg: 'An error occurred while saving settings.',
          severity: 'error',
        });
      });
  };

  return (
    <>
      <AlertComponent
        open={alertState.showAlert}
        setOpen={(showAlert) => setAlertState((prev) => ({ ...prev, showAlert }))}
        alertMsg={alertState.msg}
        severity={alertState.severity}
      />
      <Card sx={{ margin: '20px auto', padding: '20px' }}>
        <CardContent>
          <Typography variant="h5" component="div">
            Other Settings
          </Typography>

          {/* Checkout Checkbox Text */}
          <Box mt={3}>
            <TextField
              fullWidth
              label="Checkout Checkbox Text"
              value={checkoutText}
              onChange={(e) => setCheckoutText(e.target.value)}
              variant="standard"
              InputLabelProps={{ shrink: true }}
              inputProps={{ maxLength: 50, style: { padding: '10px' } }}
              helperText="If left empty, 'Do you want shipping billed to your shipping account?' will be shown."
            />
          </Box>

          {/* Suppress Rate Quotes */}
          <Box mt={3}>
            <FormControlLabel
              control={
                <Checkbox
                  checked={suppressRateQuotes}
                  onChange={(e) => setSuppressRateQuotes(e.target.checked)}
                />
              }
              label="Suppress rate quotes from other Eniture quoting products if the visitor chooses to bill-to their account."
            />
          </Box>

          {/* Save Button */}
          <Box mt={3} display="flex" justifyContent="flex-end">
            <Button
              variant="contained"
              color="primary"
              onClick={handleSaveSettings}
              disabled={saveLoading}
            >
              {saveLoading ? 'Saving...' : 'Save Settings'}
            </Button>
          </Box>
        </CardContent>
      </Card>
    </>
  );
};

export default OtherSettings;
