import React, {useEffect, useState} from "react";
import { useNavigate, useParams } from "react-router-dom";
import { AuthService, MessageService } from "../../services";
import { Spinner, Breadcrumb, BreadcrumbItem, Tabs, Tab } from "react-bootstrap";

const UpdateMessage = () => {
  const navigate = useNavigate();
  const params = useParams();
	const [messageGroup, setMessageGroup] = useState();
  const [messageName, setMessageName] = useState('');
  const [messageTitle, setMessageTitle] = useState('');
  const [messageBody, setMessageBody] = useState('');
  const [language, setLanguage] = useState('');
  const [currentMessage, setCurrentMessage] =  useState(undefined); 

  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`);
    }
    if (!currentMessage) {
      MessageService.getMessage(params.id).then(data => {
        setCurrentMessage(data.data);
      })
    }
  }, []);

  useEffect(() => {
    if (currentMessage) {
      setLanguage(currentMessage.language);
      setMessageBody(currentMessage.message_body);
      setMessageGroup(currentMessage.message_group);
      setMessageTitle(currentMessage.message_title);
      setMessageName(currentMessage.message_name);
    }
    
  }, [currentMessage])

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

	const validateMessage = () => {
      const errors = [];
      
      // Required fields validation
      if (!messageGroup || messageGroup === '') {
        errors.push('Message Group');
      }
      if (!messageName || messageName.trim() === '') {
        errors.push('Message Name');
      }
      
      if (errors.length > 0) {
        window.alert(`Please fill in the following required fields:\n${errors.join('\n')}`);
        return false;
      }
      return true;
    };

	const saveMessage = () => {
		if (!validateMessage()) {
			return;
		}
		
		const data = {
      message_group: messageGroup,
      message_title: messageTitle,
      message_body: messageBody,
      message_name: messageName,
      language: language
    };
		MessageService.updateMessage(params.id, data).then(() => redirectTo());
	}

  
  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>
            Update Message Template
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
           <h4>
             Update Message Template <button className="btn btn-link btn-sm" onClick={() => {redirectTo()}}>Back</button>
           </h4> 
        </div>
      </div>
      <div className="app-main-content-list-container">
				<div className="app-main-content-list-func-container">
					<Tabs defaultActiveKey="messageCreation" id="message-template-tab">
						<Tab eventKey="messageCreation" title="Update Message Template">
              <div className="app-main-content-fields-section">
								<div className="me-4">
									<div className="field-label">Message Group
										<span className="required">*</span>
									</div>
									<select value={messageGroup} onChange={e => setMessageGroup(e.target.value)} required>
                    <option value=""></option>
                    <option value={1}>1</option>
                    <option value={2}>2</option>
                    <option value={3}>3</option>
                  </select>
								</div>
                <div className="me-4">
									<div className="field-label">Message Name
										<span className="required">*</span>
									</div>
									<input type="text" value={messageName || ''} onChange={e => setMessageName(e.target.value)}/>
								</div>
              </div>
              <div className="app-main-content-fields-section">
								<div className="me-4">
									<div className="field-label">Language
									</div>
									<select value={language} onChange={e => setLanguage(e.target.value)}>
                    <option value=""></option>
                    <option value="English">English</option>
                    <option value="Chinese">Chinese</option>
                    <option value="Vietnamese">Vietnamese</option>
                    <option value="Korean">Korean</option>
                  </select>
								</div>
                <div className="me-4">
									<div className="field-label">Message Title
									</div>
									<input type="text" value={messageTitle || ''} onChange={e => setMessageTitle(e.target.value)}/>
								</div>
              </div>
              <div className="app-main-content-fields-section">
                <div className="me-4">
									<div className="field-label">Message Body
									</div>
									<textarea value={messageBody || ''} onChange={e => setMessageBody(e.target.value)}/>
								</div>
              </div>
              <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={() => saveMessage()}> Save </button>
								
							</div>
            </Tab>
          </Tabs>
        </div>
      </div>
    </>
  );
};

export default UpdateMessage;