import React, { useState, useRef, useEffect } from "react";
import PropTypes from "prop-types";
import { Link, useLocation } from "react-router-dom";
import { Box, Tab, Tabs, Grid, Button, Typography, IconButton, Card, CardActions, CardContent, MenuItem, Select } from "@mui/material";
import { format } from "date-fns";
import { toast } from "react-toastify";
import Profile from "../../components/Profile.js";
import CallDetails from "../ActivityReports/CallDetails.js";
import EmployeeWorkingTime from "../ActivityReports/EmployeeWorkingTime.js";
import RunningApplicationDetails from "../ActivityReports/RunningApplicationDetails.js";
import SystemLoginDetails from "../ActivityReports/SystemLoginDetails.js";
import Screenshots from "../ActivityReports/Screenshots.js";
import CustomDateRangePicker from "../../components/DateRangePicker.js";
import SingleDatePicker from '../../components/SingleDatePicker.js';
import useApiService from "../../services/apiService.js";
import { getUserSummaryDetails } from "../../constants/apiEndPoints.js";
import secondToTimeConverter from "../../utils/secondToTime.js";
import BrowsingHistory from "../BrowsingHistory.js";
import UserLocation from "../../components/UserLocation.js";
import Loader from "../../components/Loader.js";
import WorkLogSvg from "../../assets/svg/profile-work-log.svg";
import CallLogSvg from "../../assets/svg/profile-calls.svg";
import AppLogSvg from "../../assets/svg/profile-apps.svg";
import BrowserLogSvg from "../../assets/svg/profile-browser.svg";
import LoginLogSvg from "../../assets/svg/profile-login-attempts.svg";
import LocationLogSvg from "../../assets/svg/profile-location.svg";
import BackSvg from "../../assets/svg/back.svg";
import { NavigateNext, FilterAltOff } from '@mui/icons-material/';
import ActivityTable from "../ActivityTable.js";
import { useUser } from "../../context/UserContext.js";
import { getTodayDateRange } from "../../constants/dateUtils.js";
import SystemActivity from "../ActivityReports/SystemActivityScreen.js";
import "./UserProfile.css";
import { permissionTypes } from "../../constants/userConstants.js";

function CustomTabPanel(props) {
  const { children, value, index, employeeId, ...other } = props;
  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box
          className="profile-acitivity-container activity-cont"
        >
          <div className="tab-data-container ">{children}</div>
        </Box>
      )}
    </div>
  );
}

CustomTabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.number.isRequired,
  value: PropTypes.number.isRequired,
  employeeId: PropTypes.string,
};

function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    "aria-controls": `simple-tabpanel-${index}`,
    className: "single-tab",
  };
}

const getTab = (tab, employeeId, filter) => {

  // eslint-disable-next-line default-case
  switch (tab) {
    case "call-details":
      return (
        <CallDetails
          summaryFilter={filter}
          title="userProfile"
          employeeId={employeeId}
        />
      );
    case "browsing-history":
      return (
        <BrowsingHistory
          summaryFilter={filter}
          title="userProfile"
          employeeId={employeeId}
        />
      );
    case "applications":
      return (
        <RunningApplicationDetails
          summaryFilter={filter}
          title="userProfile"
          employeeId={employeeId}
        />
      );
    case "system-activity":
      return (
        <ActivityTable
          summaryFilter={filter}
          title="userProfile"
          employeeId={employeeId}
        />
      );
    case "employee-activity":
      return (
        <EmployeeWorkingTime
          summaryFilter={filter}
          title="userProfile"
          employeeId={employeeId}
        />
      );
    case "login-details":
      return (
        <SystemLoginDetails
          summaryFilter={filter}
          title="userProfile"
          employeeId={employeeId}
        />
      );
    case "user-location":
      return (
        <UserLocation
          summaryFilter={filter}
          title="userProfile"
          employeeId={employeeId}
        />
      );
    case "screenshots":
      return (
        <Screenshots
          summaryFilter={filter}
          title="userProfile"
          employeeId={employeeId}
        />
      );
    default:
      return null;
  }
};

export default function UserProfile(props) {
  const location = useLocation();
  const { permissions } = useUser();
  const pathSegments = location.pathname.split("/");
  const empCode = pathSegments[pathSegments?.length - 1];
  const inputRef = useRef(null);
  const [pickerVisible, setPickerVisible] = useState(false);
  
  const [selectedRange, setSelectedRange] = useState(getTodayDateRange());
  const [selectedDate, setSelectedDate] = useState(new Date());
  const { postApi } = useApiService();
  const [summaryData, setSummaryData] = useState({});
  const [selectedTab, setSelectedTab] = useState(0);
  const [loading, setLoading] = useState(false);

  const [summaryDataFilter, setSummaryDataFilter] = useState({
    PageNumber: 0,
    PageSize: 0,
    Filter: {
      EmpCode: empCode,
      CallDate: selectedRange,
      ResultsFor: "Today",
      Date: selectedDate ? format(selectedDate, 'yyyy-MM-dd') : null,
    },
  });

  const getSummaryData = async () => {
    setLoading(true);
    try {
      const prevSelectedTab = selectedTab;
      setSelectedTab(null);
      const filter = {
        PageNumber: 1,
        PageSize: 10,
        Filter: {
          EmpCode: empCode,
          StartedOn: selectedRange.startDate || null,
          EndedOn: selectedRange.endDate || null,
          ResultsFor: summaryDataFilter.Filter.ResultsFor || "Today",
        },
      };
      const response = await postApi(getUserSummaryDetails, filter, true);
      if (response.IsSuccess && response.Data?.Records?.length) {
        setSummaryData(response.Data?.Records[0]);
        setSelectedTab(prevSelectedTab);
      }
    } catch (error) {
      toast.error("Something went wrong", error.message);
    } finally {
      setLoading(false);
    }
  };

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

  const handleChange = (e, newValue) => {
    setSelectedTab(newValue);
  };

  const handleClose = () => {
    setPickerVisible(false);
  };

  const handleInputClick = () => {
    setPickerVisible(!pickerVisible);
  };
  const handleSelect = (date) => {
    setSelectedRange(date);
    setSummaryDataFilter({
      ...summaryDataFilter,
      Filter: { ...summaryDataFilter.Filter, CallDate: date },
    });
  };

  const handleApply = () => {
    if (inputRef.current) {
      inputRef.current.value = `${format(
        selectedRange.startDate,
        "MM/dd/yyyy"
      )} - ${format(selectedRange.endDate, "MM/dd/yyyy")}`;
    }
    setPickerVisible(false);
    setSummaryDataFilter({ ...summaryDataFilter, Filter: { ...summaryDataFilter.Filter, ResultsFor: "Select Results For" } })
  };

  const handleDateChange = (date) => {
    setSelectedDate(date);
  };

  const applyDateRange = () => {
    if (inputRef.current) {
      inputRef.current.value = `${format(selectedDate, 'yyyy-MM-dd')}`;
    }
    setPickerVisible(false);
    const updatedFilter = {
      ...summaryDataFilter,
      "Filter": {
        "EmployeeId": summaryDataFilter.Filter.EmpCode,
        "ResultsFor": "Select Results For",
        "Date": selectedDate ? format(selectedDate, 'yyyy-MM-dd') : null,
      }
    }
    setSummaryDataFilter(updatedFilter);
  };

  const formattedCurrentDate = `${format(selectedDate, "yyyy-MM-dd")}`;

  const clearAll = () => {
    const defaultRange = getTodayDateRange();
    setSelectedRange(defaultRange);
    setSummaryDataFilter({
      ...summaryDataFilter,
      Filter: {
        ResultsFor: "Today",
        CallDate: defaultRange,
      },
    });
    if (inputRef.current) {
      inputRef.current.value = null;
    }
    getSummaryData();
  };

  const tabData = [
    { key: 0, label: "Work Log", content: "employee-activity" },
    { key: 1, label: "Call Activity Log", content: "call-details" },
    { key: 2, label: "Applications", content: "applications" },
    { key: 3, label: "Browsing History", content: "browsing-history" },
    { key: 4, label: "Login Details", content: "login-details" },
    { key: 5, label: "User Location", content: "user-location" },
    { key: 6, label: "System Activity", content: "system-activity" },
  ];

  const subMenuItems = permissions.find((item) => item.SubMenuItems && item.SubMenuItems.length > 0)?.SubMenuItems || [];
  const permissionId = subMenuItems.find((item) => item.SubFeatureName === "Screenshots")?.Permission_Id;
  if (permissionId && Number.parseInt(permissionId) !== permissionTypes[2].key) {
    tabData.push({ key: 6, label: "Screenshots", content: "screenshots" });
  }


  const formatTime = (time) => {
    const [hours, minutes] = time.split(":");
    return `${hours}:${minutes}`;
  };

  const totalLogTime = formatTime(secondToTimeConverter(summaryData?.total_active_time || 0));
  const totalCallDuration = formatTime(secondToTimeConverter(summaryData?.total_call_duration || 0));
  const totalBrowsingTime = formatTime(secondToTimeConverter(summaryData?.total_browsing_time || 0));
  const totalApplicationTime = formatTime(secondToTimeConverter(summaryData?.total_application_count_time || 0));

  const renderFilters = () => (
      <>
        <div className="dropdown">
          <Select
            value={summaryDataFilter.Filter.ResultsFor}
            onChange={(e) => {
             setSelectedRange({startDate: null, endDate: null});
              if (inputRef.current) {
                inputRef.current.value = null;
              }
              setSummaryDataFilter({
                ...summaryDataFilter,
                Filter: {
                  ...summaryDataFilter.Filter,
                  ResultsFor: e.target.value,
                 CallDate : { StartedOn: null,EndedOn: null},
                  Date: null
                },
              });
            }}
            inputProps={{ "aria-label": "Without label" }}
            style={{
              width: "100%",
              height: "40px",
              backgroundColor: "white",
            }}
          >
            <MenuItem id="Select" value="Select Results For" disabled>
              Select Results For
            </MenuItem>
            <MenuItem id="Today" value="Today">
              Today
            </MenuItem>
            <MenuItem id="Week" value="Week">
              Current Week
            </MenuItem>
            <MenuItem id="Month" value="Month">
              Current Month
            </MenuItem>
          </Select>
        </div>
        {selectedTab !== 6 && (
          <div className="datepicker">
            <div className="date-picker-icon">
              <input
                ref={inputRef}
                type="text"
                placeholder="Select Date Range"
                onClick={handleInputClick}
                readOnly
                className="date-range-input calenderIcon"
                style={{ height: "40px" }}
              />
            </div>
            {pickerVisible && (
              <Box
                className="date-range-container"
                sx={{ boxShadow: 1, right: "12px" }}
              >
                <CustomDateRangePicker
                  onChange={handleSelect}
                  onApply={handleApply}
                  onClose={handleClose}
                  disableDefaultRange
                />
              </Box>
            )}
          </div>
        )}
        {selectedTab === 6 && (
          <div className="datepicker">
            <div className="date-picker-icon">
              <input
                ref={inputRef}
                type="text"
                placeholder={formattedCurrentDate || "Select Date"}
                onClick={handleInputClick}
                readOnly
                className="date-range-input calenderIcon"
                style={{ height: "40px" }}
              />
            </div>
            {pickerVisible && (
              <Box
                className="date-range-container"
                sx={{ boxShadow: 1, right: "12px" }}
              >
                <SingleDatePicker
                  onChange={handleDateChange}
                  onApply={applyDateRange}
                  onClose={handleClose}
                  selDate={selectedRange}
                />
              </Box>
            )}
          </div>
        )}
        <div className="profile-filter-actions">
          <Button
            variant="contained"
            onClick={getSummaryData}
          >
            Apply
          </Button>
          <Button
            variant="contained"
            onClick={clearAll}
          >
            <FilterAltOff />
          </Button>
        </div>
      </>
    )

  const renderProfileSummary = () => {
    const profileCards = [
      { "cardName": "WorkLog", "primaryText": `${totalLogTime} Hours`, "secondaryText": `${summaryData?.total_active_time === null ? 'No' : ''} Work Log`, "icon": <WorkLogSvg />, "hidePrimary": !summaryData?.total_active_time, "hideSecondary": false, isSpecialMenu: true },
      { "cardName": "CallLog", "primaryText": `${summaryData?.total_call_count || 'No'} Calls`, "secondaryText": `${totalCallDuration} Hours`, "icon": <CallLogSvg />, "hidePrimary": false, "hideSecondary": !summaryData.total_call_duration },
      { "cardName": "AppLog", "primaryText": `${summaryData?.total_application_count || 'No'} Apps`, "secondaryText": `${totalApplicationTime} Hours`, "icon": <AppLogSvg />, "hidePrimary": false, "hideSecondary": !summaryData.total_application_count_time },
      { "cardName": "BrowserLog", "primaryText": `${summaryData?.total_browsing_count || 'No'} Browsers used`, "secondaryText": `${totalBrowsingTime} Hours`, "icon": <BrowserLogSvg />, "hidePrimary": false, "hideSecondary": !summaryData.total_browsing_time },
      { "cardName": "LoginLog", "primaryText": `${summaryData?.total_login_count || 'No'} Login Attempts`, "secondaryText": "", "icon": <LoginLogSvg />, "hidePrimary": false, "hideSecondary": false },
      { "cardName": "LocationLog", "primaryText": `${summaryData?.total_location_count || 'No'} Locations`, "secondaryText": "", "icon": <LocationLogSvg />, "hidePrimary": false, "hideSecondary": false },
    ]
    return profileCards.map((item, index) => {
      const specialClass = item.hidePrimary && item.isSpecialMenu ? "special-class" : ""
      return (
        <Card key={`${item.cardName}`} className="profile-summary-cards">
          {item.icon && (
            <Box>
              {item.icon}
            </Box>
          )}
          <CardContent className="profile-card-content">
            {!item.hidePrimary &&
              <Typography className="profile-primary-text lato-text">
                {item.primaryText}
              </Typography>
            }
            {
              !item.hideSecondary &&
              <Typography className={`profile-secondary-text lato-text ${specialClass}`}>
                {item.secondaryText}
              </Typography>
            }
          </CardContent>
          <CardActions>
            <IconButton aria-label="more" onClick={(e) => {
              handleChange(e, index)
            }} >
              <NavigateNext className="profile-action-button" />
            </IconButton>
          </CardActions>
        </Card>)
    })
  }

  return (
    <>
      <Box className="user-profile">
        <div className="profile-summary-top">
          <div className="half-underline lato-text">
            {props?.title}
          </div>
          <div className="back-link lato-text">
            <Link to="/users"><BackSvg /> <span>Back to User List</span> </Link>
          </div>
        </div>
        <div className="profile-summary-section">
          <Grid container>
            <Grid item sx={{ width: "18%" }}>
              <Profile
                location={summaryData.Location}
                EmployeeName={summaryData.EmployeeName}
                employeeId={empCode}
              />
            </Grid>
            <Grid item sx={{ width: "82%" }}>
              <Box className="profile-cards-container">
                {renderFilters()}
                {renderProfileSummary()}
              </Box>
            </Grid>
          </Grid>
        </div>
      </Box>

      <Box className="profile-tab-section">
        <Tabs
          value={selectedTab}
          onChange={handleChange}
          aria-label="dynamic tabs example"
          className="top-bar"
        >
          {tabData.map((tab, index) => (
            <Tab key={tab.label} label={tab.label} {...a11yProps(index)} />
          ))}
        </Tabs>
        {tabData.map((tab, index) => (
          <CustomTabPanel
            key={tab.label}
            value={selectedTab}
            index={index}
            employeeId={empCode}
          >
            {getTab(tab.content, empCode, summaryDataFilter.Filter)}
          </CustomTabPanel>
        ))}
      </Box>
      {loading && <Loader />}
    </>
  );
}

UserProfile.propTypes = {
  title: PropTypes.string,
  initialTab: PropTypes.number,
  defaultFilter: PropTypes.object,
  onDataLoad: PropTypes.func,
};