import React, { useState, useEffect } from "react";
import EmpProfile from "../../components/Employee/EmpProfile";
import axios from "axios";
import Breadcrumb from "../../components/common/Breadcrumb";
import EmployeeNav from "../../components/Employee/EmployeeNav";
import { useSearchParams, useParams } from "react-router-dom";
import { getCachedData } from "../../slices/apiDataManager";
import {
  useEmployeeProfile,
  useEmployees,
  useEmployeesByProject,
} from "../../hooks/useEmployees";
import { useProfile } from "../../hooks/useProfile";

import { useSelector } from "react-redux";
import EmployeeRepository from "../../repositories/EmployeeRepository";
import { ComingSoonPage } from "../Misc/ComingSoonPage";
import { useNavigate } from "react-router-dom";
import Avatar from "../../components/common/Avatar";
import AttendancesEmployeeRecords from "./AttendancesEmployeeRecords";
import ManageEmployee from "../../components/Employee/ManageEmployee";
import { useChangePassword } from "../../components/Context/ChangePasswordContext";

const EmployeeProfile = () => {
  const { profile } = useProfile();

  const projectID = useSelector((store) => store.localVariables.projectId);
  const { employeeId } = useParams();
  // const {employee,loading} = useEmployeeProfile(employeeId)
  const [loading, setLoading] = useState(true);

  const [SearchParams] = useSearchParams();
  const tab = SearchParams.get("for");
  const [activePill, setActivePill] = useState(tab);
  const [currentEmployee, setCurrentEmployee] = useState();
  const [showModal, setShowModal] = useState(false);

  const handlePillClick = (pillKey) => {
    setActivePill(pillKey);
  };

  const closeModal = () => {
    setShowModal(false);
    fetchEmployeeProfile(employeeId);
  };
  const handleShow = () => setShowModal(true);

  const fetchEmployeeProfile = async (employeeID) => {
    try {
      const resp = await EmployeeRepository.getEmployeeProfile(employeeID);
      setCurrentEmployee(resp.data);
      setLoading(false);
    } catch (err) {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (employeeId) {
      fetchEmployeeProfile(employeeId);
    }
  }, [employeeId]);

  const navigate = useNavigate();
  const renderContent = () => {
    if (loading) return <div>Loading</div>;
    switch (activePill) {
      case "attendance": {
        return (
          <>
            <AttendancesEmployeeRecords employee={employeeId} />
          </>
        );
      }
      case "dcoument": {
        return (
          <>
            <ComingSoonPage />
          </>
        );
        break;
      }
      case "activities": {
        return (
          <>
            <ComingSoonPage />
          </>
        );
        break;
      }

      default:
        return (
          <>
            <ComingSoonPage />
          </>
        );
    }
  };

  if (loading) {
    return <div>Loading...</div>;
  }
  const { openChangePassword } = useChangePassword();
  return (
    <>
      {" "}
      {showModal && (
        <div
          className={`modal fade ${showModal ? "show" : ""} `}
          tabIndex="-1"
          role="dialog"
          style={{ display: showModal ? "block" : "none" }}
          aria-hidden={!showModal}
        >
          <div className="modal-dialog modal-xl modal-dialog-centered ">
            <div
              className="modal-content overflow-y-auto overflow-x-hidden"
              style={{ maxHeight: "90vh" }}
            >
              <ManageEmployee employeeId={employeeId} onClosed={closeModal} />
            </div>
          </div>
        </div>
      )}
      <div className="container-fluid">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Employees", link: "/employees" },
            { label: "Profile", link: null },
          ]}
        ></Breadcrumb>

        <div className="row">
          <div className="col-12 col-md-8 col-lg-4 order-1 order-lg-1">
            <div className="row">
              <div className="col-12 mb-4">
                <div className="card">
                  <div className="card-body">
                    <div className="d-flex flex-row flex-lg-column">
                      <div className="d-flex flex-column justify-content-center align-items-center text-center">
                        <Avatar
                          firstName={`${currentEmployee?.firstName}`}
                          lastName={`${currentEmployee?.lastName}`}
                          size={"lg"}
                        />
                        <div className="py-2">
                          <p className="h6">{`${currentEmployee?.firstName} ${currentEmployee?.lastName}`}</p>
                        </div>
                      </div>
                      <div className="w-100 d-flex flex-column justify-content-start">
                        <div className="mt-3 w-100">
                          <h6 className="mb-2 text-muted text-start">
                            Employee Info
                          </h6>
                          <table className="table table-borderless mb-3">
                            <tbody>
                              <tr>
                                <td className="fw-medium text-start">Email:</td>
                                <td className="text-start">
                                  {currentEmployee?.email || <em>NA</em>}
                                </td>
                              </tr>
                              <tr>
                                <td className="fw-medium text-start">
                                  Phone Number:
                                </td>
                                <td className="text-start">
                                  {currentEmployee?.phoneNumber || <em>NA</em>}
                                </td>
                              </tr>
                              <tr>
                                <td className="fw-medium text-start">
                                  Emergency Contact Person:
                                </td>
                                <td className="text-start">
                                  {currentEmployee?.emergencyContactPerson || (
                                    <em>NA</em>
                                  )}
                                </td>
                              </tr>
                              <tr>
                                <td className="fw-medium text-start">
                                  Emergency Contact Number:
                                </td>
                                <td className="text-start">
                                  {currentEmployee?.emergencyPhoneNumber || (
                                    <em>NA</em>
                                  )}
                                </td>
                              </tr>

                              <tr>
                                <td className="fw-medium text-start">
                                  Gender:
                                </td>
                                <td className="text-start">
                                  {currentEmployee?.gender || <em>NA</em>}
                                </td>
                              </tr>
                              <tr>
                                <td className="fw-medium text-start">
                                  Birth Date:
                                </td>
                                <td className="text-start">
                                  {currentEmployee?.birthDate ? (
                                    new Date(
                                      currentEmployee.birthDate
                                    ).toLocaleDateString()
                                  ) : (
                                    <em>NA</em>
                                  )}
                                </td>
                              </tr>

                              <tr>
                                <td className="fw-medium text-start">
                                  Joining Date:
                                </td>
                                <td className="text-start">
                                  {currentEmployee?.joiningDate ? (
                                    new Date(
                                      currentEmployee.joiningDate
                                    ).toLocaleDateString()
                                  ) : (
                                    <em>NA</em>
                                  )}
                                </td>
                              </tr>
                              <tr>
                                <td className="fw-medium text-start">
                                  Job Role:
                                </td>
                                <td className="text-start">
                                  {currentEmployee?.jobRole || <em>NA</em>}
                                </td>
                              </tr>
                              <tr>
                                <td className="fw-medium text-start">
                                  Address:
                                </td>
                                <td className="text-start">
                                  {currentEmployee?.currentAddress || (
                                    <em>NA</em>
                                  )}
                                </td>
                              </tr>
                            </tbody>
                          </table>
                        </div>
                        <button
                          className="btn btn-primary btn-block"
                          onClick={() => handleShow()}
                        >
                          Edit Profile
                        </button>
                        {currentEmployee?.id == profile?.employeeInfo?.id && (
                          <button
                            className="btn btn-outline-primary btn-block mt-2"
                            onClick={() => openChangePassword()}
                          >
                            Change Password
                          </button>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="col-12 col-lg-8 order-2 order-lg-2 mb-4">
            <div className="row">
              <EmployeeNav
                onPillClick={handlePillClick}
                activePill={activePill}
              />
            </div>
            <div className="card">
              <div className="row row-bordered g-0">{renderContent()}</div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default EmployeeProfile;
