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

const UpdateCenterPhone = () => {
  const navigate = useNavigate();
	const [phoneTitle, setPhoneTitle] = useState('');
	const [phoneNumber, setPhoneNumber] = useState('');
  const [activated, setActivated] = useState(false);
  const [currentPhone, setCurrentPhone] = useState(undefined);
  const urlParams = useParams();

  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 an Dispatcher or admin account to login.')
      AuthService.logout();
      navigate(`/login`);
    }
    if (!currentPhone) {
      CenterPhoneService.getCenterPhone(urlParams.id).then(data => setCurrentPhone(data.data))
    }
  }, []);

  useEffect(() => {
    if (currentPhone) {
      setPhoneNumber(currentPhone.phone_number);
      setPhoneTitle(currentPhone.phone_title);
      setActivated(currentPhone.activated);
    }
    
  }, [currentPhone])

  const redirectTo = () => {
    navigate('/center-phones/list')
  }

	const validatePhone = () => {
		const errors = [];
		
		// Required fields validation
		if (!phoneTitle || phoneTitle.trim() === '') {
			errors.push('Phone Title');
		}
		if (!phoneNumber || phoneNumber.trim() === '') {
			errors.push('Phone Number');
		}
		
		if (errors.length > 0) {
			window.alert(`Please fill in the following required fields:\n${errors.join('\n')}`);
			return false;
		}
		return true;
	};

	const savePhone = () => {
		if (!validatePhone()) {
			return;
		}
		
		const data = {
			phone_title: phoneTitle,
      phone_number: phoneNumber,
      activated: activated
		};
		CenterPhoneService.updateCenterPhone(urlParams.id, data).then(() => redirectTo())
	}
  
  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/">General</Breadcrumb.Item>
          <Breadcrumb.Item href="/center-phones/list">
            Center Phone 
          </Breadcrumb.Item>
          <Breadcrumb.Item active>
            Update Center Phone
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
           <h4>
             Update Center Phone <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="updatePhone" id="update-phone-tab">
						<Tab eventKey="updatePhone" title="Update Center Phone">
              <div className="app-main-content-fields-section">
								<div className="me-4">
									<div className="field-label">Phone Title
										<span className="required">*</span>
									</div>
									<input type="text" value={phoneTitle || ''} onChange={e => setPhoneTitle(e.target.value)}/>
								</div>
                <div className="me-4">
									<div className="field-label">Phone Number
										<span className="required">*</span>
									</div>
									<input type="text" value={phoneNumber || ''} onChange={e => setPhoneNumber(e.target.value)}/>
								</div>
                <div className="me-4">
									<div className="field-label">Activated
									</div>
									<input type="checkbox" value={activated} checked={activated === true} onChange={e => setActivated(!activated)}/>
								</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={() => savePhone()}> Save </button>
								
							</div>
            </Tab>
          </Tabs>
        </div>
      </div>
    </>
  );
};

export default UpdateCenterPhone;