import Company from "../models/Company";
import { useState, useEffect } from 'react';
import { Link, useParams } from "react-router-dom";
import DataService from '../services/DataService';
import Employee from '../models/Employee';
import Position from '../models/Position';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import ModalForm from './commons/ModalForm';
import styles from "./OneCompany.module.css";
import withAuth from './withAuth';

function OneCompany(props) { 
    const { id } = useParams();

    const url = '/company/id';
    const urlCompanyEmp = '/company/id/employees';
    const urlEmp = '/employee/free';
    const urlPos = '/position';
    const urlHire = '/company/id/hire';
    const urlDismiss = '/company/id/dismiss';
    const urlAddPos = '/employee/id/addPos';
    const urlDelPos = '/employee/id/delPos';
    const requestParamsPosition = '?position=posId';
    const requestParamsHire = '?employeeId=empId';

    const [company, setCompany] = useState(new Company());
    const [itemsEmpFree, setItemsEmpFree] = useState([]);
    const [itemsEmpCompany, setItemsEmpCompany] = useState([]);
    const [itemsPos, setItemsPos] = useState([]);

    const headersEmp = [
        {name: 'surname', label: "Фамилия"}, 
        {name: 'name', label: "Имя"}, 
        {name: 'positionsString', label: 'Должности'},
        {name: 'phoneNumber', label: "Номер телефона"}
    ];

    useEffect(() => {      
        loadCompany();
    }, []);

    function loadCompany() {       
        DataService.read(url.replace("id", id), (data) => new Company(data)).then((data) => setCompany(new Company(data)));
    }

    function loadItemsEmployees() {
        DataService.readAll(urlEmp, (data) => new Employee(data))
            .then(data => setItemsEmpFree(data));
    }
    
    function loadItemsPositions() {
        DataService.readAll(urlPos, (data) => new Position(data))
            .then(data => setItemsPos(data));
    }

    function loadItemsEmployeesCompany() {
        DataService.readAll(urlCompanyEmp.replace("id",  company.id), (data) => new Employee(data))
            .then(data => setItemsEmpCompany(data));
    }


    // логика для найма или увольнения
    const [isShowHire, setShowHire] = useState(false);

    function showModalFormHire() {  
        loadItemsEmployees();      
        setShowHire(true);
    }
    function unshowModalFormHire() {
        setShowHire(false);
    }

    const [isShowDismiss, setShowDismiss] = useState(false);

    function showModalFormDismiss(e) { 
        loadItemsEmployeesCompany();     
        setShowDismiss(true);
    }
    function unshowModalFormDismiss() {
        setShowDismiss(false);
    }
    const [employee, setEmployee] = useState(new Employee());

    function employeeChosenFree(e) {
        setEmployee(itemsEmpFree.filter((emp) => emp.id == e.target.value)[0]);
    }

    function employeeChosenBusy(e) {
        setEmployee(Array.from(company.employees).filter((emp) => emp.id == e.target.value)[0]);
    }

    function formHireSubmit() { 
        DataService.update(urlHire.replace("id",company.id) + requestParamsHire
                        .replace("empId", employee.id))
                        .then(() => loadCompany());
         
                    
        setEmployee(new Employee());
    }

    function formDismissSubmit() {
        DataService.update(urlDismiss.replace("id",company.id) + requestParamsHire
            .replace("empId", employee.id))
            .then(() => loadCompany());
        
        setEmployee(new Employee());
    }

    const [isShowChoosePosition, setShowChoosePosition] = useState(false);

    function showModalFormChoosePosition() { 
        loadItemsPositions();   
        loadItemsEmployeesCompany();     
        setShowChoosePosition(true);
    }
    function unshowModalFormChoosePosition() {
        setShowChoosePosition(false);
        setPositionEmp([]);
    }

    const [positionsChosen, setPositionEmp] = useState([]);
    function checkBoxChanged(e) {
        // если чекбокс был выбран, то дабавляем в массив должность
        if (e.target.checked) 
        {
            positionsChosen.push(e.target.value);
        } // если чекбокс был убран, то исключаем его значение из массива
        else 
        {
            let i = positionsChosen.indexOf(e.target.value);
            if(i >= 0) {
                positionsChosen.splice(i,1);
            }            
        }
    }

    function formChoosePositionsSubmit() {
        for (let i = 0; i < positionsChosen.length; i++) {
            DataService.update(urlAddPos.replace("id",employee.id) + requestParamsPosition
                        .replace("posId", positionsChosen[i]))
                        .then(() => loadCompany()); 
        }
        
        let positionsEmp = employee.positions;
     
        for (let i = 0; i < positionsEmp.length; i++) {
            if (positionsChosen.indexOf(''+positionsEmp[i].id) == -1) {
                // удаление должности
                DataService.update(urlDelPos.replace("id",employee.id) + requestParamsPosition
                        .replace("posId", positionsEmp[i].id))
                        .then(() => loadCompany()); 
            }
        }
    }

    const formHire = <Form onSubmit={formHireSubmit}>
                        <Form.Group className="mb-3" controlId="employee">                     
                            <Form.Label>Сотрудник</Form.Label>
                            <Form.Select name="employee_select" type="input"  onChange={employeeChosenFree} required>
                            <option selected disabled>Выберите сотрудника</option>
                            {
                                itemsEmpFree.map((e) => <option key={`emp_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>)
                            } 
                            </Form.Select>                 
                        </Form.Group>    
                    <Button variant="primary" type="submit">
                        Отправить
                    </Button>
                    </Form>;


     const formDismiss = <Form onSubmit={formDismissSubmit}>
                        <Form.Group className="mb-3" controlId="employee">                     
                            <Form.Label>Сотрудник</Form.Label>
                            <Form.Select name="employee_select" type="input" onChange={employeeChosenBusy} required>
                            <option selected disabled>Выберите сотрудника</option>
                            {
                                itemsEmpCompany.map((e) => <option key={`emp_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>)
                            } 
                            </Form.Select>                 
                        </Form.Group>                          
                    <Button variant="primary" type="submit">
                        Отправить
                    </Button>
                    </Form>;

    const formCheckBoxesPosition = <Form onSubmit={formChoosePositionsSubmit}>
          <Form.Group className="mb-3" controlId="employee">                     
                <Form.Label>Сотрудник</Form.Label>
                <Form.Select name="employee_select" type="input" onChange={employeeChosenBusy} required>
                    <option selected disabled>Выберите сотрудника</option>
                    {
                        itemsEmpCompany.map((e) => <option key={`emp_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>)
                    } 
                </Form.Select>                 
        </Form.Group>  
        <Form.Group className="mb-3" controlId="position">    
            <Form.Label>Должности</Form.Label>
            <div className={`${styles.prokrutka}`}>
                {
                    itemsPos.map((p) => <div style={{width: `150 px`}}>
                        <input type="checkbox"  key={`${p.id}`} value={`${p.id}`} onChange={checkBoxChanged}/>
                        {/* {!employeeHasPosition(p) && <input type="checkbox"  key={`${p.id}`} value={`${p.id}`} onChange={checkBoxChanged}/>}
                        {employeeHasPosition(p) && <input type="checkbox"  key={`${p.id}`} value={`${p.id}`} checked onChange={checkBoxChanged}/>} */}
                        {`${p.name}`}
                        </div>)
                }  
            </div>    
        </Form.Group>  
        <Button variant="primary" type="submit">
                Отправить
        </Button>
    </Form>

    if (!company) {
        return <div><h1>Компания не найдена</h1> 
                <Link to='/companies'>
                    <Button variant="info">Назад</Button>
                </Link>
        </div>
    }
    return <div className="container-lg pt-5 min-vh-100">
        <Link to='/companies'>
            <Button variant="info">Назад</Button>
        </Link>
        <h1>Название: {company.name}</h1> 
        <h2>Количество сотрудников: {company.countEmployees}</h2> 
        {localStorage.getItem("role") === "ADMIN" && <Button name="Найм" onClick={showModalFormHire} variant="success">Нанять сотрудника</Button>}
        {localStorage.getItem("role") === "ADMIN" && <Button name='Увольнение' onClick={showModalFormDismiss} variant="danger">Уволить сотрудника</Button>}
        {localStorage.getItem("role") === "ADMIN" && <Button name='Назначение должности' onClick={showModalFormChoosePosition} variant="info">Назначение должности</Button>}
        <div >
            <table className={`table table-hover`}>
            <thead>
                    <tr>
                        {
                        headersEmp.map((header) => <th key={header.name}>{header.label}</th>)
                        }
                    </tr>
            </thead>
            <tbody>
                    {
                    Array.from(company.employees).map((item, index) => <tr key={item.id}>
                         {
                            headersEmp.map((header) => <td key={`${header.name}_${item.id}`}>{item[header.name]}</td>)
                        }
                    </tr>)
                    }
            </tbody>
        </table>
        </div>
        <ModalForm show={isShowHire} onClose={unshowModalFormHire} modalTitle={"Найм"} form={formHire}></ModalForm> 
        <ModalForm show={isShowDismiss} onClose={unshowModalFormDismiss} modalTitle={"Увольнение"} form={formDismiss}></ModalForm> 
        <ModalForm show={isShowChoosePosition} onClose={unshowModalFormChoosePosition} modalTitle={"Управление должностями"} form={formCheckBoxesPosition}></ModalForm> 
  </div>
}

export default withAuth(OneCompany);