import { EyeFilled, EyeOutlined, UserOutlined } from "@ant-design/icons";
import { Avatar, Button, Divider, List, Popover, Select, Tooltip, Typography } from "antd";
import { useTranslation } from "react-i18next";
import EmployeeSearchSelectComponent from "../../components/employee-search-select/employee-search-select.component.jsx";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component.jsx";
import { BiSolidTrash } from "react-icons/bi";

const { Text } = Typography;

export default function JobWatcherToggleComponent({
  jobWatchers,
  isWatching,
  watcherLoading,
  adding,
  removing,
  open,
  setOpen,
  selectedWatcher,
  setSelectedWatcher,
  selectedTeam,
  bodyshop,
  Enhanced_Payroll,
  handleToggleSelf,
  handleRemoveWatcher,
  handleWatcherSelect,
  handleTeamSelect,
  isEmployee
}) {
  const { t } = useTranslation();

  const handleRenderItem = (watcher) => {
    // Check if watcher is defined and has user_email
    if (!watcher?.user_email) {
      return null; // Skip rendering invalid watchers
    }

    const employee = bodyshop?.employees?.find((e) => e.user_email === watcher.user_email);
    const displayName = employee ? `${employee.first_name} ${employee.last_name}` : watcher.user_email;

    return (
      <List.Item
        actions={[
          <Button
            type="default"
            danger
            key="remove"
            size="medium"
            icon={<BiSolidTrash />}
            onClick={() => handleRemoveWatcher(watcher.user_email)}
            disabled={adding || removing} // Optional: Disable button during mutations
          >
            {t("notifications.actions.remove")}
          </Button>
        ]}
      >
        <List.Item.Meta
          avatar={<Avatar icon={<UserOutlined />} />}
          title={<Text>{displayName}</Text>}
          description={watcher.user_email}
        />
      </List.Item>
    );
  };

  const popoverContent = (
    <div style={{ width: "30em" }}>
      <List>
        <List.Item
          actions={[
            <Tooltip
              key="notEmployeeToolTip"
              title={!isEmployee ? t("notifications.tooltips.not-employee") : ""}
              placement="top"
            >
              <span>
                <Button
                  type={isWatching ? "primary" : "default"}
                  danger={!isWatching}
                  icon={isWatching ? <EyeOutlined /> : <EyeFilled />}
                  size="medium"
                  onClick={handleToggleSelf}
                  loading={adding || removing}
                  disabled={!isEmployee || adding || removing}
                >
                  {isWatching ? t("notifications.labels.unwatch") : t("notifications.labels.watch")}
                </Button>
              </span>
            </Tooltip>
          ]}
        >
          <List.Item.Meta>
            <Text type="secondary" style={{ marginBottom: 8, display: "block" }}>
              {t("notifications.labels.watching-issue")}
            </Text>
            {!isEmployee && (
              <Text type="danger" style={{ marginBottom: 8, display: "block" }}>
                {t("notifications.tooltips.not-employee")}
              </Text>
            )}
          </List.Item.Meta>
        </List.Item>
      </List>
      {watcherLoading ? (
        <LoadingSpinner />
      ) : jobWatchers && jobWatchers.length > 0 ? (
        <List dataSource={jobWatchers} renderItem={handleRenderItem} />
      ) : (
        <Text type="secondary">{t("notifications.labels.no-watchers")}</Text>
      )}

      <Divider />
      <Text type="secondary">{t("notifications.labels.add-watchers")}</Text>
      <EmployeeSearchSelectComponent
        style={{ minWidth: "100%" }}
        options={
          bodyshop?.employees?.filter(
            (e) =>
              e.user_email && // Ensure user_email is not null or undefined
              e.active && // Ensure employee is active
              jobWatchers.every((w) => w.user_email !== e.user_email) // Ensure not already a watcher
          ) || []
        }
        placeholder={t("notifications.labels.employee-search")}
        value={selectedWatcher}
        showEmail={true}
        onChange={(value) => {
          setSelectedWatcher(value);
          handleWatcherSelect(value);
        }}
      />
      {Enhanced_Payroll && bodyshop?.employee_teams?.length > 0 && (
        <>
          <Divider />
          <Text type="secondary">{t("notifications.labels.add-watchers-team")}</Text>
          <Select
            showSearch
            style={{ minWidth: "100%" }}
            placeholder={t("notifications.labels.teams-search")}
            value={selectedTeam}
            onChange={handleTeamSelect}
            options={
              bodyshop?.employee_teams?.map((team) => {
                const teamMembers = team.employee_team_members
                  .map((member) => {
                    const employee = bodyshop?.employees?.find((e) => e.id === member.employeeid);
                    return employee?.user_email && employee?.active ? employee.user_email : null;
                  })
                  .filter(Boolean);
                return {
                  value: JSON.stringify(teamMembers),
                  label: team.name
                };
              }) || []
            }
          />
        </>
      )}
    </div>
  );

  return (
    <Popover placement="rightTop" content={popoverContent} trigger="click" open={open} onOpenChange={setOpen}>
      <Tooltip title={t("notifications.tooltips.job-watchers")}>
        <Button
          shape="circle"
          type={isWatching ? "primary" : "default"}
          icon={isWatching ? <EyeFilled /> : <EyeOutlined />}
          loading={watcherLoading}
        />
      </Tooltip>
    </Popover>
  );
}
