// ./src/app/employees/view-employee/page.tsx
'use client';
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter, useSearchParams } from 'next/navigation';
import { Button, Descriptions, notification, Tag, Space, Modal, Popconfirm } from 'antd';
import type { EmployeeCitiesData } from '../interface';
import { changePassword, deleteEmployeeData } from '../service';
import { displayDate, getRoleIdMap, hasPermission } from '@/utills/helper';
import { EditOutlined, LockOutlined, DeleteOutlined } from '@ant-design/icons';
import { useSession } from 'next-auth/react';
import { PERMISSIONS } from '@/utills/constant';
import ChangePasswordPage from '../components/ChangePasswordPage';
import type { AppDispatch, RootState } from '@/store/store';
import { fetchEmployee } from '../slice';
import PageHeader from '@/components/pageHeader';
import FormattedAmount from '@/components/amountFormat/AmountFormatter';
import { fetchRoles } from '@/app/role/slice';
import { useRoles } from '@/hooks/useRoles';
const EmployeeDetails: React.FC = () => {
  const searchParams = useSearchParams();
  const id = searchParams?.get('id');
  const dispatch: AppDispatch = useDispatch();
  const { data: session } = useSession();
  const user = session?.user;
  const router = useRouter();
  const [roleFilters, setRoleFilters] = useState<any>({
      page: 1,
      sortColumn: 'sort_order',
    });

  const [isChangePasswordModalVisible, setChangePasswordModalVisible] = useState<boolean>(false);
  const [selectedEmployeeId, setSelectedEmployeeId] = useState<number | null>(null);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const { roles } = useSelector((state: RootState) => state.roles);
  useEffect(() => {
    if(roles?.length === 0) {
      dispatch(fetchRoles(roleFilters));
    }
  }, [roles]);
  const allRoles = getRoleIdMap(roles);
  const { getRoleByName } = useRoles();

  const { employee, status } = useSelector((state: any) => {
    return {
      employee: state?.employees?.employee,
      status: state?.employees?.status,
    };
  });
  useEffect(() => {
    if (id) {
      dispatch(fetchEmployee({ id: Number(id) }));
    }
  }, [id]);

  // Handling loading and failed states
  if ((status == 'failed' && employee == null) || employee === undefined) {
    return <p>User does not exists.</p>;
  }

  if (status == 'loading' || employee == null) {
    return <p>Loading...</p>;
  }

  // Handle employee deletion
  const handleDeleteEmployee = (employeeId: number): void => {
    deleteEmployeeData(employeeId)
      .then((response) => {
        notification.success({
          message: 'Success',
          description: response?.message,
        });
        router.push('/employees');
      })
      .catch((error) => {
        notification.error({
          message: 'Error',
          description: error?.response?.data?.message,
        });
      });
  };

  // Show change password modal
  const showChangePasswordModal = async(employeeId: number | null) => {
    setSelectedEmployeeId(employeeId);
    await changePassword({ employeeId })
      .then((response) => {
        if (response?.status === 200) {
          notification.success({
            message: 'Success',
            description: response?.data?.message,
          });
        } else {
          notification.error({
            message: 'Error',
            description: 'Failed to Change Password',
          });
        }
      })
      .catch((error) => {
        const { message } = error?.response?.data || {};
        notification.error({
          message: 'Error',
          description: message,
        });
      });
    setSelectedEmployeeId(null);
  };

  // Cancel change password modal
  const handleCancelChangePassword = (): void => {
    setChangePasswordModalVisible(false);
    setSelectedEmployeeId(null);
  };

  // Ok change password modal
  const handleOkChangePassword = (): void => {
    setChangePasswordModalVisible(false);
    setSelectedEmployeeId(null);
  };

  return (
    <>
      <PageHeader
        title="Employee Information"
        extra={
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '5px' }}>
            <Space wrap>
              {user !== null &&
                                hasPermission(user, PERMISSIONS.EMPLOYEE_DELETE_ACCOUNT.name) && (
                <Button
                  type="primary"
                  size="middle"
                  danger
                  icon={<DeleteOutlined />}
                  onClick={() => {
                    setIsModalVisible(true);
                  }}>
                                        Delete Account
                </Button>
              )}
              {user !== null &&
                                hasPermission(user, PERMISSIONS.EMPLOYEE_CHANGE_PASSWORD.name) && (
                <Popconfirm
                  title="Are you sure you want to change the employee password?"
                  onConfirm={() => {
                    showChangePasswordModal(employee?.id);
                  }}
                  okText="Yes"
                  cancelText="No"
                  placement="topRight">
                  <Button
                    type="primary"
                    size="middle"
                    icon={<LockOutlined />}
                    loading={selectedEmployeeId == employee?.id}>
                                            Change Password
                  </Button>
                </Popconfirm>
              )}
              {isChangePasswordModalVisible && (
                <ChangePasswordPage
                  employeeId={selectedEmployeeId}
                  visible={isChangePasswordModalVisible}
                  onCancel={handleCancelChangePassword}
                  onOk={handleOkChangePassword}
                />
              )}
              <Button
                type="primary"
                size="middle"
                icon={<EditOutlined />}
                onClick={() => {
                  router.push(`/employees/edit-employee?id=${employee?.id}`);
                }}>
                                Edit Details
              </Button>
            </Space>
          </div>
        }
      />
      <div className="bg-white">
        <Descriptions
          column={{ sm: 1, md: 1, lg: 1, xl: 2, xxl: 2 }}
          colon={true}
          size="middle"
          className="custom-descriptions"
          bordered>
          <Descriptions.Item label="Name:">
            {employee?.first_name} {employee?.last_name}
          </Descriptions.Item>
          <Descriptions.Item label="Email:">{employee?.email}</Descriptions.Item>
          <Descriptions.Item label="Phone:">{employee?.phone}</Descriptions.Item>
          <Descriptions.Item label="City:">
            {employee?.user_cities &&
                            employee?.user_cities
                              ?.map((city: EmployeeCitiesData) => city?.city_name)
                              .join(', ')}
          </Descriptions.Item>
          <Descriptions.Item label="Role:">{employee?.role_label}</Descriptions.Item>
          <Descriptions.Item label="Designation:">
            {employee?.designation_name}
          </Descriptions.Item>
          {employee?.reporting_manager_name && (
            <Descriptions.Item label="Reporting Manager:">
              {employee?.reporting_manager_name
                ? employee.reporting_manager_name
                : '-'}{' '}
                            ({employee?.reporting_manager_role_label})
            </Descriptions.Item>
          )}

          <Descriptions.Item label="Account Created On:">
            {displayDate(employee?.created_at)}
          </Descriptions.Item>
          <Descriptions.Item label="Account Created By:">
            {employee?.created_by_name} ({employee?.created_by_role_label})
          </Descriptions.Item>
          <Descriptions.Item label="Status:" className="capitalize">
            <Tag
              color={employee?.status === 'active' ? 'green' : 'red'}
              className="capitalize">
              {employee?.status}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="Blocked:">
            <Tag color={employee?.is_blocked ? 'red' : 'green'}>
              {employee?.is_blocked ? 'Yes' : 'No'}
            </Tag>
          </Descriptions.Item>
          {user?.role?.id === getRoleByName('super_admin')?.id ||
                    user?.role?.id === getRoleByName('human_resources')?.id ? (
              <Descriptions.Item label="Salary:">
                <FormattedAmount amount={employee?.salary} />
              </Descriptions.Item>
            ) : (
              ''
            )}
        </Descriptions>
      </div>
      <Modal
        title={'Delete Account'}
        visible={isModalVisible}
        onOk={() => {
          handleDeleteEmployee(employee?.id);
          setIsModalVisible(false);
        }}
        onCancel={() => {
          setIsModalVisible(false);
        }}
        okText="Yes, Delete"
        cancelText="No, Cancel"
        className="custom-new-modal confirm-modal delete-modal">
        <p>
                    Are you sure you want to delete the account of employee {employee?.first_name}{' '}
          {employee?.last_name}?
        </p>
      </Modal>
    </>
  );
};

export default EmployeeDetails;
