import React, { useState, useEffect } from 'react';
import { Button, Card,Drawer,Form,Row,Col,Alert, DatePicker, Anchor,Spin} from 'antd';
import { useIntl, FormattedDate} from 'react-intl'
import { render } from 'react-dom';
import { UserCreateResponse,UserService,EmployeeService, ProjectMappingService} from '@gtpl/shared-services/attendance';
import {CreateUserDto,CreateUserDtoDefault,EmployeeDto, ProjectMappingDto} from '@gtpl/shared-models/gtpl';
import { UserGrid } from '@gtpl/pages/attendance-management/attendance-management-components/user-grid';
import { UserForm} from '@gtpl/pages/attendance-management/attendance-management-components/user-form';
import { AlertMessages} from '@gtpl/shared-utils/alert-messages';
import { EmployeeProjectsResponseDto } from 'libs/shared-models/gtpl/src/lib/project-mapping/employee-projects-response-dto';
export interface UserPagesProps {}
export const UserPages =( props:UserPagesProps) =>{
  const [drawerVisible, setdrawerVisible] = useState<boolean>(false);
  const [isNewForm, setisNewForm] = useState<boolean>(true);
  const [viewOnly, setViewOnly] = useState(true);
  const [EmployeeData, setEmployeeData] = useState<EmployeeDto[]>([])
  const [user, setUserData] = useState<CreateUserDto[]>([])
  const [selectedUser, setSelectedUser] = useState<any>(CreateUserDtoDefault)
  const [employeeProjectsData, setEmployeeProjectsData] = useState<any>([])

  const userService = new UserService;
  const service = new EmployeeService;
  const { Link } = Anchor;
  // const {formatMessage:fm}= useIntl()
  const OpenFormTocreateRecord = () => {
    const duplicatedState = JSON.parse(JSON.stringify(CreateUserDtoDefault));
    setisNewForm(true);
    setSelectedUser(duplicatedState);
    setdrawerVisible(true);
    setViewOnly(false);
  }
  useEffect(() => {getAllUser();getAllEmployees(); }, [])


  const projectMappingService = new ProjectMappingService;


  const getEmployeeAssignedProjects = (UserViewData) => {
    projectMappingService.getEmployeeAssignedProjectByEmployeeId(UserViewData).then(res => {
      console.log(res.data);
      if (res.status) {
        setEmployeeProjectsData(res.data);
      } else {
        if (res.intlCode) {
          setEmployeeProjectsData([]);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
      setEmployeeProjectsData([]);
    })
  }
  const getAllUser= () => {
    // console.log('users request');
    userService.getAllUser().then(res => {
      console.log('res.data = '+res.data);
      if (res.data) {
        console.log('users info');
        // console.log(res);
        setUserData(res.data);
        console.log(user);
      } else {
        if (res.intlCode) {
          setUserData([]);
          
            AlertMessages.getErrorMessage(res.internalMessage);
        } else {
         AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
      setUserData([]);
    })
  }
  const getAllEmployees= () => {
    service.getAllEmployees().then(res => {
      if (res.status) {setEmployeeData(res.data);
      } else {
        if (res.intlCode) {
          setEmployeeData([]);
            AlertMessages.getErrorMessage(res.internalMessage);
        } else {
         AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
      setEmployeeData([]);
    })
  }
  const viewUser= (UserViewData: CreateUserDto, viewOnly: boolean = true) => {
    console.log(UserViewData);
    setisNewForm(false);
    setSelectedUser(UserViewData);
    setdrawerVisible(true);
    setViewOnly(viewOnly);
    getEmployeeAssignedProjects(UserViewData.employeeId);
  }
  const deleteUser= (UserViewData: CreateUserDto) => {
    console.log(UserViewData);
    UserViewData.status=UserViewData.status?false:true;
    userService.ActivatedeActivateEmployee(UserViewData).then(res => {
      getAllUser();
      if (res.status) {
        getAllUser();
        AlertMessages.getSuccessMessage('Success');
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }

  const removeproject = (UserViewData: ProjectMappingDto) => {
    console.log(UserViewData);
    UserViewData.isActive=UserViewData.isActive?false:true;
    UserViewData.attenEligibility=UserViewData.attenEligibility?false:true;
    UserViewData.updatedUser=JSON.parse(localStorage.getItem('userid'));
    console.log(UserViewData);
    projectMappingService.updateemployeeProjectStatus(UserViewData).then(res => {
      if (res.status) {
        getEmployeeAssignedProjects(UserViewData.empId);
        AlertMessages.getSuccessMessage('Updated Successfully');
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }
  const updateUser = (UserData: CreateUserDto) => {
    console.log(UserData);
    // EmployeeData.stateId=3;
    // EmployeeData.createdUser=1;
    userService.updateUser(UserData).then(res => {
      if (res.success) {
        setdrawerVisible(false);
        getAllUser();
        AlertMessages.getSuccessMessage('Updated Successfully');
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }

  /**
   * To Save The State
   * @param UserData
   */
  const saveUser= (UserData: CreateUserDto) => {
    console.log('HHHHHHHHHHHHHHHHHHHHHHHHH');
    UserData.Id=0;
    UserData.createdUser=JSON.parse(localStorage.getItem('userid'));
    // console.log('UserData');    
    // console.log(UserData);
    userService.register(UserData).then(res => {
      console.log(res);
       if (res.success) {
         AlertMessages.getSuccessMessage('User created Successfully');
         setdrawerVisible(false);
       } else {
         if (res.intlCode) {
           AlertMessages.getErrorMessage(res.internalMessage);
         } else {
           AlertMessages.getErrorMessage(res.internalMessage);
         }
       }
     }).catch(err => {
       AlertMessages.getErrorMessage(err.message);
     })
   }
   const closeDrawer = () => { setdrawerVisible(false);}
   let viewPortwidth = window.innerWidth;
   const [loading, setLoading] = useState(true)

   useEffect(() => {
     setTimeout(() => setLoading(false), 1000)
   }, [])
   return (
     <>
      {loading === false ? (
     <><Anchor affix={false}>
           <Link href="#/dashboard" title="Dashboard" />
         </Anchor><Card bodyStyle={{ overflow: 'auto' }} title={'Users: ' + user.length + ', Active ' + user.filter(el => el.status).length + ' | In-Active ' + user.filter(el => el.status == false).length} extra={<Button type="primary" onClick={() => { OpenFormTocreateRecord(); } } style={{ float: 'right', display: "block" }}>Create</Button>}>
             <UserGrid viewuser={viewUser} deleteuser={deleteUser} userData={user} />
           </Card>
           <Drawer bodyStyle={{ paddingBottom: 80 }} title='User Creation Form ' width={viewPortwidth > 768 ? '50%' : '85%'}
             onClose={closeDrawer} visible={drawerVisible} closable={true}>
             <Card headStyle={{ textAlign: 'center', fontWeight: 500, fontSize: 16 }} title="User Creation Details" size='small'>
               <UserForm key={Date.now()}
                 userData={selectedUser}
                 saveUser={saveUser}
                 updateUser={updateUser}
                 removeproject={removeproject}
                 employeeData={EmployeeData}
                 employeeProjectsData= {employeeProjectsData}
                 viewOnly={viewOnly}
                 closeForm={closeDrawer}
                 isNewForm={isNewForm} />
             </Card>
           </Drawer>
           </>
   ): (
    <div className="spins">
    <Spin size="large"/>
    </div>
  )}
     </>
   )
  }
  export default UserPages;
