import React, {useEffect, useState} from "react";
import { useNavigate } from "react-router-dom";
import { AuthService, MessageService, CustomerService } from "../../services";
import Select from 'react-select';
import { Spinner, Breadcrumb, BreadcrumbItem, Tabs, Tab } from "react-bootstrap";
import { SendCheck } from "react-bootstrap-icons";

const SendMessage = () => {
  const navigate = useNavigate();
  const params = new URLSearchParams(window.location.search);
  useEffect(() => {
    if (!AuthService.canAddOrEditRoutes() && !AuthService.canViewRoutes() && !AuthService.canAccessLegacySystem()) {
      window.alert('You haven\'t login yet OR this user does not have access to this page. Please change a dispatcher or admin account to login.')
      AuthService.logout();
      navigate(`/login`);
    }
    CustomerService.getAllActiveCustomers().then(data => {
      const customers = data.data;
      setSeniorPhoneList(customers.filter(customer => customer.mobile_phone && customer.mobile_phone !== '' ))
    });
    MessageService.getMessages().then(data => setMessageTemplateList(data.data));
  }, []);
  const [contactPhone, setContactPhone] = useState('');
  const [contactSeniorPhone, setContactSeniorPhone] = useState('');
  const [messageTemplate, setMessageTemplate] = useState('');
  const [messageText, setMessageText] = useState('');
  const [seniorPhoneList, setSeniorPhoneList] = useState([]);
  const [messageTempateList, setMessageTemplateList] = useState([]);
  const [showSuccessInfo, setShowSuccessInfo] = useState(false);

  const redirectTo = () => {
    if (params.get('from') === 'medical') {
      navigate(`/medical/`);
    } else {
      navigate(`/admin/customer-report`)
    }
    
  }

  const redirectToList = () => {
    navigate(`/messages/list`)
  }

  const goToSentMessages = () => {
    navigate(`/messages/sent-messages/list`);
  }

  const sendMessage = () => {
    setShowSuccessInfo(false);
    const data = {
      messages: [{
        contactPhone: contactPhone,
        mode: 'AUTO',
        text: messageText
      }]
    };
	  MessageService.sendMessage(data).then(() => setShowSuccessInfo(true));
  }

  const onContactSeniorChange = (selectedData) => {
    setContactSeniorPhone(selectedData);
    setContactPhone(selectedData?.value);
  }

  
  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/">General</Breadcrumb.Item>
          <Breadcrumb.Item href="/messages/list">
            Messaging
          </Breadcrumb.Item>
          <Breadcrumb.Item active>
            Send Message
          </Breadcrumb.Item>
        </Breadcrumb>
				<div className="col-md-12 text-primary">
           <h4>Send Message <button className="btn btn-link btn-sm" onClick={() => {redirectToList()}}>Back</button></h4> 
        </div>
      </div>
      <div className="app-main-content-list-container">
				<div className="app-main-content-list-func-container">
					<Tabs defaultActiveKey="sendMessage" id="send-message-tab">
						<Tab eventKey="sendMessage" title="Send Message">
              <div className="app-main-content-fields-section">
								<div className="me-4">
									<div className="field-label">Type in Phone Number
										<span className="required">*</span>
									</div>
                  <input type="text" value={contactPhone || ''} onChange={e => setContactPhone(e.target.value)}/>
								</div>
                <div className="me-4">OR</div>
                <div className="me-4">
									<div className="field-label">Select From Participant Mobile Number List
										<span className="required">*</span>
									</div>
                  <Select styles={{
                    control: (baseStyles) => ({
                      ...baseStyles,
                      width: '350px',
                      borderRadius: '8px'
                    }),
                    indicatorSeparator: () => ({
                      display: 'none'
                    }),
                    dropdownIndicator: (baseStyles) => ({
                      ...baseStyles,
                      paddingRight: '8px',
                      color: '#333',
                      '&:hover': { color: '#000' }
                    }),
                    valueContainer: (baseStyles) => ({
                      ...baseStyles,
                      height: '43px',
                      padding: '0 8px',
                    }),
                    input: (baseStyles) => ({
                      ...baseStyles,
                      margin: '0px',
                      padding: '0px',
                      height: '30px',
                      width: '290px'
                    }),
                    placeholder: (baseStyles) => ({
                      ...baseStyles,
                      fontSize: '13px'
                    }),
                    singleValue: (baseStyles) => ({
                      ...baseStyles,
                      margin: '0px',
                      fontSize: '13px'
                    })
                  }} value={contactSeniorPhone || ''} onChange={selectedData => onContactSeniorChange(selectedData)} options={[{value: '', label: ''}, ...seniorPhoneList.map(senior => ({
                    value: senior?.mobile_phone || '',
                    label: `${senior?.name}(${senior?.name_cn}) - ${senior?.mobile_phone}` || '',
                  }))]}></Select>
                </div>
              </div>
              <div className="app-main-content-fields-section">
                <div className="me-4">
                  <div className="field-label">Select Message Template (Optional)</div>
                  <Select styles={{
                    control: (baseStyles) => ({
                      ...baseStyles,
                      width: '350px',
                      borderRadius: '8px'
                    }),
                    indicatorSeparator: () => ({
                      display: 'none'
                    }),
                    dropdownIndicator: (baseStyles) => ({
                      ...baseStyles,
                      paddingRight: '8px',
                      color: '#333',
                      '&:hover': { color: '#000' }
                    }),
                    valueContainer: (baseStyles) => ({
                      ...baseStyles,
                      height: '43px',
                      padding: '0 8px',
                    }),
                    input: (baseStyles) => ({
                      ...baseStyles,
                      margin: '0px',
                      padding: '0px',
                      height: '30px',
                      width: '290px'
                    }),
                    placeholder: (baseStyles) => ({
                      ...baseStyles,
                      fontSize: '13px'
                    }),
                    singleValue: (baseStyles) => ({
                      ...baseStyles,
                      margin: '0px',
                      fontSize: '13px'
                    })
                  }} value={messageTemplate || ''} onChange={selectedData => {setMessageTemplate(selectedData); setMessageText(selectedData.value)}} options={[{value: '', label: ''}, ...messageTempateList.map(template => ({
                    value: template.message_body || '',
                    label: template.message_body || '',
                  }))]}></Select>
                </div>
              </div>
              <div className="app-main-content-fields-section">
                <div className="me-4">
                  <div className="field-label">Message Content</div>
                  <textarea value={messageText || ''} onChange={e => setMessageText(e.target.value)}/>
                </div>
              </div>
              <div className="list row mb-5">
                <div className="col-md-12 col-sm-12 col-xs-12">
                  <button className="btn btn-default btn-sm float-right" onClick={() => redirectTo()}> Cancel </button>
                  <button className="btn btn-primary btn-sm float-right" onClick={() => sendMessage()}> Save </button>
                </div>
              </div>
              {showSuccessInfo && <div className="col-md-12 mb-4 alert alert-success" role="alert">
                Message Sent!
              </div>}
            </Tab>
          </Tabs>
          <div className="list-func-panel">
						<button className="btn btn-primary btn-sm" onClick={() => goToSentMessages()}><SendCheck size={16} className="me-2"></SendCheck>View All Sent Messages</button> 
					</div>
        </div>
      </div>
    </>
  );
};

export default SendMessage;