/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable spellcheck/spell-checker */
'use client';
import React, { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { Form, Button, notification, Spin, Card, Row, Col, Space, Typography, Modal, Switch, Collapse, Checkbox } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import EmployeeResolvePair from './EmployeeResolvePair';
import EmployeeLaunchTransfer from './EmployeeLaunchTransfer';
import ConfirmUpdateModal from './ConfirmUpdateModal';
import ConfirmTransferModal from './ConfirmTransferModal';
const { Panel } = Collapse;
import type { Employee } from '../interface';
import InputText from '@/components/form/InputText';
import InputSelect from '@/components/form/InputSelect';
import ModalBox from '@/app/designations/component/modal';
import MasterRoles from '@/components/masterDropdowns/MasterRoles';
import MasterCities from '@/components/masterDropdowns/MasterCities';
import { addEmployee, getEmployee, updateEmployeeData, checkTransferValidation, getSubstitutes, resolvePair, transferSelfLeads, getLeadTransferPreview, getLeadTransferConfirmPreview, getInactiveValidation } from '../service';
import MasterEmployees from '@/components/masterDropdowns/MasterEmployees';
import MasterDesignations from '@/components/masterDropdowns/MasterDesignations';
import { useSession } from 'next-auth/react';
import {
  salaryValidator,
  userEmailValidator,
  userEmployeePhoneNoValidator,
  userNameValidator
} from '@/utills/validator';
import { convertToShorthand, getManagerAndSubordinates, getRoleIdMap } from '@/utills/helper';
import { RootState, AppDispatch } from '@/store/store';
import { useSelector, useDispatch } from 'react-redux';
import { fetchRoles } from '@/app/role/slice';
import { fetchFilterLaunchList } from '@/app/enquiries/slice';
import ReAssignEmployee from '@/components/masterDropdowns/ReAssignEmployee';
import { FILTERS } from '@/app/enquiries/constant';
import { filterI } from '@/app/enquiries/interface';
import { getFilterLaunchList } from '@/app/enquiries/service';
import { transformLabel } from '@/utills/helper';
import { DefaultRoles } from '@/utills/constant';
import { useRoles } from '@/hooks/useRoles';
type SelectItem = { value: string | number; label: string };

interface FilterLaunchParams {
  lead_user_role_name: string;
  lead_user_id: string | number;
  lead_user_city_id: string | number | undefined;
}
interface IAddEditEmployeeProps {
  id?: number | undefined
}
interface dropdownProps {
  map: any
  label: string
  value: number | string
}
interface City {
  city_id: number;
  city_name: string;
}

interface TransferValidationItem {
  launch_id: number;
  launch_name: string;
  show_for_pair_resolve: boolean;
  show_for_self_transfer: boolean;
  launch_sales_id?: number;
  partner_name?: string;
}

const AddEditEmployee: React.FC<IAddEditEmployeeProps> = ({ id }) => {
  const router = useRouter();
  const { data: session } = useSession();
  const userCities = session?.user?.cities;
  const user = session?.user;
  const dispatch: AppDispatch = useDispatch();
  const { roles } = useSelector((state: RootState) => state.roles);
  const filterLaunchLList = useSelector((state: RootState) => state?.allLeads?.filterLaunchLList);
  const [form] = Form.useForm();
  const city_id_watch = Form.useWatch('city_id', form);
  const salary_watch = Form.useWatch('salary', form);
  const managerOfWatch = Form.useWatch('manager_of_id', form);
  const status_watch = Form.useWatch('status', form);
  const reportingManagerWatch = Form.useWatch('reporting_manager_id', form);

  const [loading, setLoading] = useState<boolean>(false);
  const [formChange, setFormChange] = useState<boolean>(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [roleId, setRoleId] = useState<string | number>(0);
  const [originalRoleId, setOriginalRoleId] = useState<string | number>(0);
  const [fsTlLaunchSelected, setFsTlLaunchSelected] = useState(false);
  const [submitionLoading, setSubmitionLoading] = useState(false);
  const [showReportingToField, setShowReportingToField] = useState<string | null>(null);
  const [showManagerOfField, setShowManagerOfField] = useState<string | null>(null);
  const [reportingId, setReportingId] = useState<string | number | undefined>()
  // New-employee-only escape hatch: a placeholder hire created ahead of a
  // promotion that will assign their manager (e.g. a brand-new gm_sales seat
  // for someone who isn't growth_head yet). Keeps Reporting Manager required
  // for ordinary hiring — this only opts out when explicitly checked.
  const [noReportingManagerYet, setNoReportingManagerYet] = useState(false);
  const [previousReportingMangerId, setPreviousReportingManagerId] = useState<number | null>(null)
  const [showLaunchDropdown, setShowLaunchDropdown] = useState(false);
  const [roleFilters, setRoleFilters] = useState<any>({
    page: 1,
    sortColumn: 'sort_order',
  });
  const [filters, setFilters] = useState<filterI>(FILTERS);
  const [transferValidationData, setTransferValidationData] = useState<any[]>([]);
  const [showTransferPanels, setShowTransferPanels] = useState<boolean>(false);
  const [substitutes, setSubstitutes] = useState<any>({}); // launch_id -> substitutes[]
  const [selectedSubstitutes, setSelectedSubstitutes] = useState<any>({}); // launch_sales_id -> substitute_user_id
  const [launchPreviewCounts, setLaunchPreviewCounts] = useState<any>({}); // launch_id -> { tab_counts, to_transfer, to_die }
  const [previewLoading, setPreviewLoading] = useState<any>({}); // launch_id -> boolean
  const [transferPanelKey, setTransferPanelKey] = useState(0);
  const [activeCollapseKeys, setActiveCollapseKeys] = useState<string[]>([]);
  const [invalidPairLaunchIds, setInvalidPairLaunchIds] = useState<number[]>([]);
  const [invalidTransferLaunchIds, setInvalidTransferLaunchIds] = useState<number[]>([]);
  const [pairResolvingStatus, setPairResolvingStatus] = useState<{ active: boolean; total: number }>({ active: false, total: 0 });
  const [leadTransferringStatus, setLeadTransferringStatus] = useState<{ active: boolean; total: number }>({ active: false, total: 0 });
  const [isConfirmUpdateOpen, setIsConfirmUpdateOpen] = useState(false);
  const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false);
  const [launchReplacementLocked, setLaunchReplacementLocked] = useState(false);
  const [launchReplacementDefaultOption, setLaunchReplacementDefaultOption] = useState<{ value: number; label: string } | null>(null);
  const [projectReplacementLocked, setProjectReplacementLocked] = useState(false);
  const [projectReplacementDefaultOption, setProjectReplacementDefaultOption] = useState<{ value: number; label: string } | null>(null);
  const [inactiveValidation, setInactiveValidation] = useState<{ launchRequired: boolean; projectRequired: boolean }>({
    launchRequired: false,
    projectRequired: false,
  });

  const [confirmModalData, setConfirmModalData] = useState<any>({
    pairResolutions: [],
    transferDetails: [],
    pairsToResolve: [],
    transferLeads: [],
    updateData: {},
  });

  useEffect(() => {
    if (roles?.length === 0) {
      dispatch(fetchRoles(roleFilters));
    }
  }, [roles]);
  const allRoles = getRoleIdMap(roles);
  const { getRoleByName } = useRoles();
  const isEmailFieldDisabled = !(user?.role?.id === getRoleByName('super_admin')?.id) && (id !== undefined && id !== null);
  const currentReportingManagerIdForReplacement = typeof reportingManagerWatch === 'object' ? reportingManagerWatch?.value : reportingManagerWatch;
  const currentDate = new Date();
  const currentMonth = currentDate.getMonth();

  const reportingToField = useRef<any>(null);
  const managerOfField = useRef<any>(null);
  const currentCity = useRef<any>(null);
  const designationRef = useRef<any>(null);

  // Generate city options
  const cityOptions = userCities?.map((city: City) => ({
    value: city.city_id,
    label: city.city_name,
  }));

  useEffect(() => {
    // Fetch employee data if editing
    if (id !== undefined && id !== null) {
      setLoading(true);
      getEmployee(id)
        .then((res) => {
          const employeeData = res?.data;
          const data = { ...employeeData };
          const cityData = data?.user_cities?.map((city: { city_id: number; city_name: string; }) => ({
            value: city.city_id,
            label: city.city_name,
          }));

          let obj = {
            'lead_user_role_name': data?.role,
            'lead_user_id': data?.id,
            'lead_user_city_id': data.user_cities[0]?.city_id,
          }
          setFilters(obj as unknown as filterI);
          dispatch(fetchFilterLaunchList(obj));
          form.setFieldsValue({
            ...data,
            city_id: cityData,
            designation_id: {
              value: data?.designation_id,
              label: data?.designation_name,
            },
            role_id: { value: data?.role_id, label: data?.role_label },
            reporting_manager_id: {
              value: data?.reporting_manager_id,
              label: data?.reporting_manager_name,
            },

            manager_of_id: data?.managerOf,
          });
          handleRoleChange(data?.role_id, false, cityData, data?.reporting_manager_role_id);
          setRoleId(data?.role_id);
          setOriginalRoleId(data?.role_id);
          setShowLaunchDropdown(true);
          setPreviousReportingManagerId(data?.reporting_manager_id)
          if (data?.status === 'inactive') {
            if (data?.launch_replacement_user_id) {
              const launchDefaultOption = {
                value: data.launch_replacement_user_id,
                label: data.launch_replacement_user_name,
              };
              setLaunchReplacementDefaultOption(launchDefaultOption);
              setLaunchReplacementLocked(true);
              form.setFieldsValue({ launch_replacement_user_id: launchDefaultOption });
            }
            if (data?.project_replacement_user_id) {
              const projectDefaultOption = {
                value: data.project_replacement_user_id,
                label: data.project_replacement_user_name,
              };
              setProjectReplacementDefaultOption(projectDefaultOption);
              setProjectReplacementLocked(true);
              form.setFieldsValue({ project_replacement_user_id: projectDefaultOption });
            }
            getInactiveValidation(id)
              .then((res) => {
                setInactiveValidation({
                  launchRequired: !!res?.launch?.required,
                  projectRequired: !!res?.project?.required,
                });
              })
              .catch(() => {
                // Non-fatal: dropdowns already pre-populated from saved values above.
              });
          }
          setLoading(false);
        })
        .catch((error) => {
          notification.error({
            message: 'Error',
            description: error?.response?.data?.message,
          });
          setLoading(false);
        });
    }
  }, []);

  // Re-trigger reporting manager dropdown when roles load after employee data
  // On hard refresh, roles may load after the employee fetch completes,
  // causing handleRoleChange to get null from getManagerAndSubordinates
  useEffect(() => {
    if (id && roles?.length > 0 && roleId) {
      const cityData = form.getFieldValue('city_id') || [];
      handleRoleChange(roleId, false, Array.isArray(cityData) ? cityData : [cityData]);
    }
  }, [roles, roleId]);

  // When an admin flips an existing employee's status to Inactive, ask the
  // backend which replacement dropdown(s) are required (launch mapping and/or
  // project/seller mapping) so we can show only the ones that apply.
  useEffect(() => {
    if (id && status_watch === 'inactive') {
      getInactiveValidation(id)
        .then((res) => {
          setInactiveValidation({
            launchRequired: !!res?.launch?.required,
            projectRequired: !!res?.project?.required,
          });
        })
        .catch(() => {
          notification.error({
            message: 'Error',
            description: 'Could not verify launch/project replacement requirements for this employee.',
          });
        });
    } else if (status_watch !== 'inactive') {
      setInactiveValidation({ launchRequired: false, projectRequired: false });
    }
  }, [id, status_watch]);

  // check if the fields should be disabled
  const areFieldsDisabled = (): boolean => {
    return (currentMonth === 3 || currentMonth === 9) && id !== undefined && id !== null;
  };

  // Handle click event for adding new designation
  const handleAddDesignationClick = (): void => {
    setIsModalOpen(true);
  };
  const handleOk = (): void => {
    setIsModalOpen(false);
    designationRef.current.reload({ role_id: roleId });
  };

  // Handle close event for modal
  const handleCloseModal = (): void => {
    setIsModalOpen(false);
  };

  // Options for status dropdown
  const statusOptions = [
    { value: 'active', label: 'Active' },
    { value: 'inactive', label: 'Inactive' },
  ];

  // Handle change in role dropdown
  const handleRoleChange = (
    value: number | string,
    resetFieldValue = true,
    cityData: any = [],
    reportingManagerRoleId?: number
  ): void => {
    let { manager_role_id, manager_of_role_ids } = getManagerAndSubordinates(value, roles);
    let reportingTo: React.SetStateAction<string | null> = `${manager_role_id as unknown as React.SetStateAction<string | null>}`;
    let managerOf: React.SetStateAction<string | null> = `${manager_of_role_ids as unknown as React.SetStateAction<string | null>}`
    /* for manager of dropdown */

    if (reportingTo || managerOf) {
      setTimeout(() => {
        reportingToField.current?.reload({
          role_id: reportingTo,
          city_id:
            cityData.length > 0
              ? cityData[0]?.value
              : city_id_watch?.length
                ? city_id_watch[0]?.value
                : city_id_watch?.value,
        });
        currentCity.current?.reload({
          city_id:
            cityData.length > 0
              ? cityData[0]?.value
              : city_id_watch?.length
                ? city_id_watch[0]?.value
                : city_id_watch?.value,
        });
        managerOfField.current?.reload({
          role_id: managerOf,
          city_id:
            cityData.length > 0
              ? cityData[0]?.value
              : city_id_watch?.length
                ? city_id_watch[0]?.value
                : city_id_watch?.value,
        });
      }, 1000);
    }
    if (resetFieldValue) {
      form.setFieldsValue({ reporting_manager_id: null });
    }
    setShowReportingToField(reportingTo);
    setShowManagerOfField(managerOf ? managerOf : reportingManagerRoleId as unknown as React.SetStateAction<string | null>)
  };

  //get team mates of the same launch
  const handleClickLaunchSelect = async (launch_id: []) => {
    let updatedFilter = { ...filters, 'launch_id': launch_id?.join(',') }
    // dispatch(fetchFilterLaunchList(updatedFilter));
    await getFilterLaunchList(updatedFilter)
      .then((res) => {
        const formatData = res?.launchTeamMates?.map((users: { user_id: number; first_name: string, last_name: string, role_name: string; }) => ({
          value: users?.user_id,
          label: `${users?.first_name} ${users?.last_name} (${users?.role_name})`,
        }));
        const selectedTeamMates = formatData
          ?.filter((item: any) => item.value !== previousReportingMangerId) // remove the manager from here
          .map((item: any) => item.value);

        form.setFieldsValue({ manager_of_id: selectedTeamMates });

      })
      .catch((error) => {
        notification.error({
          message: error?.message,
          description: error?.response?.data?.message,
        });
      });

    // const userIds: number[] = launchTeamMates?.map((user: any) => user.user_id);
    // form.setFieldValue({ manager_of_id: userIds })
  };
  // Handle form submission
  const onFinish = async (formData: Employee): Promise<void> => {

    setSubmitionLoading(true);
    if (id !== undefined && id !== null) {
      // Update employee data
      try {
        const city = formData?.city_id as unknown as dropdownProps;
        const designation = formData?.designation_id as unknown as dropdownProps;
        const reportingManager = formData?.reporting_manager_id as unknown as dropdownProps;
        const role = formData?.role_id as unknown as dropdownProps;
        const managerOf = formData?.manager_of_id?.join(',') as unknown as dropdownProps;
        const reAssignTo = formData?.re_assign_to_id as unknown as dropdownProps;
        const launchReplacement = formData?.launch_replacement_user_id as unknown as dropdownProps;
        const projectReplacement = formData?.project_replacement_user_id as unknown as dropdownProps;
        const launchIds = formData?.launches?.join(',')
        const currentRoleId = Number(role?.value);
        const cityValues = Array.isArray(city)
          ? city?.map((city: { value: string; }) => city?.value)
          : [city?.value];
        if (cityValues.filter((ct: number) => ct === undefined).length > 0) {
          Modal.error({
            title: 'An error occurred in the city field.',
            content: 'Kindly remove the empty cities as they appear to be inactive.',
          });
          setSubmitionLoading(false);
          return;
        }

        // Validate pair resolution and lead transfer for TL, Pre Sales, Field Sales
        const isSalesRole = currentRoleId === getRoleByName('field_sales')?.id ||
          currentRoleId === getRoleByName('pre_sales')?.id ||
          currentRoleId === getRoleByName('team_lead')?.id;

        // FS→TL promotion: skip self lead transfer and launch selection validation
        // (unless user has manually selected a launch, in which case transfer should work normally)
        const isFStoTLPromotion = Number(originalRoleId) === getRoleByName('field_sales')?.id &&
          currentRoleId === getRoleByName('team_lead')?.id &&
          !fsTlLaunchSelected;

        const newReportingManagerId = Number(
          typeof reportingManager === 'object' ? reportingManager.value : reportingManager
        );
        const reportingManagerHasChanged = previousReportingMangerId !== null &&
          newReportingManagerId !== Number(previousReportingMangerId);

        if (isSalesRole && reportingManagerHasChanged) {
          // Collect all validation errors in one pass — no early returns — so every
          // broken panel is highlighted and opened simultaneously.
          let validationFailed = false;
          const newCollapseKeys = [...activeCollapseKeys];

          // 1. Launch selection required (skipped for FS→TL promotion)
          if (!launchIds && !isFStoTLPromotion) {
            notification.error({
              message: 'Launch Required',
              description: 'Please select at least one launch to transfer the employee.',
            });
            validationFailed = true;
          }

          // 2. Pair resolution validation
          if (transferValidationData && transferValidationData.length > 0) {
            const unresolvedPairs = transferValidationData.filter((l: TransferValidationItem) => l.show_for_pair_resolve);
            if (unresolvedPairs.length > 0) {
              const unconfiguredPairs = unresolvedPairs.filter((l: TransferValidationItem) => !selectedSubstitutes[l.launch_sales_id!]);
              if (unconfiguredPairs.length > 0) {
                unconfiguredPairs.forEach((l: { launch_id: number }) => fetchSubstitutes(l.launch_id, originalRoleId));
                setInvalidPairLaunchIds(unconfiguredPairs.map((l: TransferValidationItem) => l.launch_id));
                newCollapseKeys.push('pair_resolution');
                notification.error({
                  message: 'Resolve Pair Resolution',
                  description: 'One Or More Launch is Missing a Substitute.',
                });
                validationFailed = true;
              }
            }

            // 3. Lead transfer validation (skipped for FS→TL promotion)
            const launchesWithLeads = !isFStoTLPromotion
              ? transferValidationData.filter((l: TransferValidationItem) => l.show_for_self_transfer)
              : [];
            if (launchesWithLeads.length > 0) {
              const transfers = (formData as any).transfers || {};
              const selectedLaunchIds = (formData.launches || []).map(Number);

              const unconfiguredLaunches = launchesWithLeads.filter((l: TransferValidationItem) => {
                const t = transfers?.[String(l.launch_id)];
                return !t || !t.new_launch_id || !t.tab_status?.length;
              });

              const sameSourceTargetLaunches = launchesWithLeads.filter((l: TransferValidationItem) => {
                const t = transfers?.[String(l.launch_id)];
                return t && t.new_launch_id && Number(t.new_launch_id) === Number(l.launch_id);
              });

              const invalidTargetLaunches = launchesWithLeads.filter((l: TransferValidationItem) => {
                const t = transfers?.[String(l.launch_id)];
                if (t && t.new_launch_id && !selectedLaunchIds.includes(Number(t.new_launch_id))) {
                  return true;
                }
                return false;
              });

              if (unconfiguredLaunches.length > 0) {
                setInvalidTransferLaunchIds(unconfiguredLaunches.map((l: TransferValidationItem) => l.launch_id));
                newCollapseKeys.push('lead_transfer');
                notification.error({
                  message: 'Lead Transfer Details Required',
                  description: 'One Or More Launches Leads Are Missing Transfer Details.',
                });
                validationFailed = true;
              } else if (sameSourceTargetLaunches.length > 0) {
                setInvalidTransferLaunchIds(sameSourceTargetLaunches.map((l: TransferValidationItem) => l.launch_id));
                newCollapseKeys.push('lead_transfer');
                notification.error({
                  message: 'Invalid Target Launch',
                  description: 'Transfer To Launch cannot be the same as the current launch. Please select a different target launch.',
                });
                validationFailed = true;
              } else if (invalidTargetLaunches.length > 0) {
                setInvalidTransferLaunchIds(invalidTargetLaunches.map((l: TransferValidationItem) => l.launch_id));
                newCollapseKeys.push('lead_transfer');
                notification.error({
                  message: 'Invalid Target Launch',
                  description: 'The selected launch for lead transfer must be one of the launches currently assigned to the employee.',
                });
                validationFailed = true;
              } else {
                // Check that mark_remaining_dead is confirmed wherever dieing_leads > 0
                const unconfirmedDeadLaunches = launchesWithLeads.filter((l: TransferValidationItem) => {
                  const t = transfers?.[String(l.launch_id)];
                  const preview = launchPreviewCounts[l.launch_id];
                  const dyingCount = preview?.dieing_leads ?? 0;
                  return dyingCount > 0 && !t?.mark_remaining_dead;
                });
                if (unconfirmedDeadLaunches.length > 0) {
                  setInvalidTransferLaunchIds(unconfirmedDeadLaunches.map((l: TransferValidationItem) => l.launch_id));
                  newCollapseKeys.push('lead_transfer');
                  notification.error({
                    message: 'Dead Lead Confirmation Required',
                    description: 'Please confirm that remaining leads should be marked as Dead for all launches before proceeding.',
                  });
                  validationFailed = true;
                }
              }
            }
          }

          if (validationFailed) {
            setShowTransferPanels(true);
            setActiveCollapseKeys([...new Set(newCollapseKeys)]);
            setSubmitionLoading(false);
            return;
          }
        }

        // 1. Collect Resolve Pairs
        const pairsToResolve = transferValidationData
          .filter((l: TransferValidationItem) => l.show_for_pair_resolve && selectedSubstitutes[l.launch_sales_id!])
          .map((l: TransferValidationItem) => ({
            launch_sales_id: l.launch_sales_id,
            current_user_id: id,
            substitute_user_id: selectedSubstitutes[l.launch_sales_id!],
            role_id: currentRoleId,
          }));

        // 2. Collect Lead Transfers
        const transferLeads: any[] = [];
        const formTransfers = (formData as any).transfers;
        console.log(formTransfers, 'formTransfers_formTransfers');
        if (formTransfers) {
          Object.keys(formTransfers || {}).forEach((launchId) => {
            const transfer = formTransfers[launchId];
            if (
              transfer &&
              transfer.new_launch_id &&
              Array.isArray(transfer.tab_status) &&
              transfer.tab_status.length > 0
            ) {
              transferLeads.push({
                user_id: id,
                old_launch_id: Number(launchId),
                new_launch_id: transfer.new_launch_id,
                tab_statuses: transfer.tab_status,
                current_statuses: transfer.current_status || [],
                role_id: currentRoleId,
                mark_remaining_dead: transfer.mark_remaining_dead === true,
              });
            }
          });
        }

        // 3. Construct Update Payload (Original - without transfer_lead)
        const updateData = {
          first_name: formData?.first_name,
          last_name: formData?.last_name,
          phone: formData?.phone,
          email: formData.email,
          designation_id: designation?.value,
          city_id: cityValues,
          role_id: role?.value,
          reporting_manager_id:
            typeof reportingManager === 'object' ? reportingManager.value : reportingManager,
          status: formData?.status,
          salary: formData?.salary,
          is_update: user?.id == id ? false : formChange,
          manager_of_ids: managerOf ? managerOf : null,
          re_assign_to: reAssignTo ? reAssignTo : null,
          launch_ids: launchIds ? launchIds : null,
          is_blocked: formData?.is_blocked ? true : false,
          bypass_pair_check: showTransferPanels,
          launch_replacement_user_id: formData?.status === 'inactive'
            ? (typeof launchReplacement === 'object' ? launchReplacement?.value : launchReplacement)
            : undefined,
          project_replacement_user_id: formData?.status === 'inactive'
            ? (typeof projectReplacement === 'object' ? projectReplacement?.value : projectReplacement)
            : undefined,
        };

        // 4. Prepare Modal Data
        const pairModalDetails: any[] = [];
        pairsToResolve.forEach((p: any) => {
          const launch = transferValidationData.find((l: any) => l.launch_sales_id === p.launch_sales_id);
          const subs = substitutes[launch?.launch_id] || [];
          const substitute = subs.find((s: any) => s.id === p.substitute_user_id);
          if (launch && substitute) {
            pairModalDetails.push({
              launchName: launch.launch_name,
              substituteName: `${substitute.first_name} ${substitute.last_name}`,
            });
          }
        });

        const transferModalDetails: any[] = [];
        transferLeads.forEach((t: any) => {
          const launch = transferValidationData.find((l: any) => l.launch_id === t.old_launch_id);
          const preview = launchPreviewCounts[t.old_launch_id];
          if (launch && preview) {
            transferModalDetails.push({
              launchName: launch.launch_name,
              transferringLeads: preview.transferring_leads ?? 0,
              dieingLeads: preview.dieing_leads ?? 0,
              excludedLeads: preview.excluded_counts?._total_unique ?? 0,
            });
          }
        });



        // 5. Check if confirmation is needed
        if (pairModalDetails.length > 0 || transferModalDetails.length > 0) {
          // Open the in-app confirmation modal first.
          // The preview modal opens only after the user confirms this step.
          setSubmitionLoading(false);
          setConfirmModalData({
            pairResolutions: pairModalDetails,
            transferDetails: transferModalDetails,
            pairsToResolve,
            transferLeads,
            updateData,
          });
          setIsConfirmUpdateOpen(true);


        } else {
          // No transfers/resolutions, proceed immediately
          handleExecuteUpdate(pairsToResolve, transferLeads, updateData);
        }
      } catch (error) {
        console.error('error: ', error);
        setSubmitionLoading(false);
      }
    } else {
      try {
        const city = formData?.city_id as unknown as dropdownProps;
        const designation = formData?.designation_id as unknown as dropdownProps;
        const reportingManager = formData?.reporting_manager_id as unknown as dropdownProps;
        const role = formData?.role_id as unknown as dropdownProps;
        const managerOf = formData?.manager_of_id?.join(',') as unknown as dropdownProps;
        const defaultValuesRole = roleId === getRoleByName('human_resources')?.id;
        const cityValues = defaultValuesRole
          ? city?.map((c: { value: string; }) => c?.value)
          : [city?.value];
        const addEmployeeData = {
          first_name: formData.first_name,
          last_name: formData.last_name,
          phone: formData.phone,
          email: formData.email,
          designation_id: designation.value,
          role_id: role?.value,
          city_id: cityValues,
          // Joi's schema for this field has no .allow(null) — an explicit
          // null would fail validation, so the key must be omitted entirely
          // (undefined) rather than nulled out for the "no manager yet" case.
          reporting_manager_id: noReportingManagerYet
            ? undefined
            : (typeof reportingManager === 'object' ? reportingManager.value : reportingManager),
          status: formData.status,
          manager_of_ids: managerOf ? managerOf : null,
          salary: formData?.salary,
          is_blocked: formData?.is_blocked ? true : false,
        };

        addEmployee(addEmployeeData)
          .then((el) => {
            notification.success({
              message: 'Success',
              description: el?.message,
            });
            router.push('/employees');
            setSubmitionLoading(false);
          })
          .catch((error) => {
            notification.error({
              message: 'Error',
              description: error?.response?.data?.message,
            });
            setSubmitionLoading(false);
          });
      } catch (error) {
        console.error('error: ', error);
      }
    }
  };



  // handle fetch launch after reporting manager change
  const handleFetchLaunch = (
    value: string | number,
    item: SelectItem | SelectItem[],
    form: any,
    dispatch: (action: any) => void,
    fetchFilterLaunchList: (params: FilterLaunchParams) => any
  ) => {
    let role_name = '';
    const city = form.getFieldValue('city_id')?.[0]?.value;

    if (!Array.isArray(item)) {
      const match = item.label.match(/\(([^)]+)\)/);
      if (match) {
        const role = match[1];
        const method = 'convert';
        role_name = transformLabel(role, method);
      }
    }

    const obj: FilterLaunchParams = {
      lead_user_role_name: role_name,
      lead_user_id: value,
      lead_user_city_id: city,
    };

    dispatch(fetchFilterLaunchList(obj));
  };

  const fetchSubstitutes = async (launchId: number | string, roleId: number | string) => {
    try {
      if (id && roleId) {
        const res = await getSubstitutes(id, launchId, roleId);
        if (res.success) {
          setSubstitutes((prev: any) => ({ ...prev, [launchId]: res.data }));
        }
      }
    } catch (error) {
      console.error('Error fetching substitutes:', error);
    }
  };

  const fetchPreviewCounts = async (launchId: number | string, tabStatuses: string[], currentStatuses?: number[]) => {
    if (!id || !launchId || tabStatuses.length === 0) {
      setLaunchPreviewCounts((prev: any) => ({ ...prev, [launchId]: null }));
      return;
    }
    const roleId = form.getFieldValue('role_id')?.value;
    setPreviewLoading((prev: any) => ({ ...prev, [launchId]: true }));
    try {
      const res = await getLeadTransferPreview(id, launchId, roleId, tabStatuses, currentStatuses);
      if (res.success) {
        // Fetch confirm preview (transfer/dead counts) automatically
        const tabCounts = res.data?.tab_counts || {};
        const confirmRes = await getLeadTransferConfirmPreview(id, launchId, roleId, tabCounts);

        setLaunchPreviewCounts((prev: any) => ({
          ...prev,
          [launchId]: {
            ...res.data,
            ...(confirmRes.success ? confirmRes.data : {}),
          },
        }));
      }
    } catch (e) {
      console.error('Preview fetch error:', e);
    } finally {
      setPreviewLoading((prev: any) => ({ ...prev, [launchId]: false }));
    }
  };

  const handleExecuteUpdate = async (pairsToResolve: any[], transferLeads: any[], updateData: any) => {
    setSubmitionLoading(true);
    try {
      if (pairsToResolve.length > 0) {
        setPairResolvingStatus({ active: true, total: pairsToResolve.length });
        const pairRes = await resolvePair({ pair: pairsToResolve });
        setPairResolvingStatus({ active: false, total: 0 });
        if (!pairRes.success) {
          notification.error({ message: 'Pair Resolution Error', description: pairRes.message });
          setSubmitionLoading(false);
          return;
        }
      }

      if (transferLeads.length > 0) {
        setLeadTransferringStatus({ active: true, total: transferLeads.length });
        const transferRes = await transferSelfLeads({ transfer_leads: transferLeads });
        setLeadTransferringStatus({ active: false, total: 0 });
        if (!transferRes.success) {
          notification.error({ message: 'Lead Transfer Error', description: transferRes.message });
          setSubmitionLoading(false);
          return;
        }

        if (Array.isArray(transferRes.summary) && transferRes.summary.length > 0) {
          const getLaunchName = (launchId: number) =>
            filterLaunchLList?.find((l: any) => Number(l.launch_id) === Number(launchId))?.launch_name
            || transferValidationData.find((l: any) => Number(l.launch_id) === Number(launchId))?.launch_name
            || `Launch #${launchId}`;

          const description = transferRes.summary.map((s: any) => {
            const parts = [`${s.transferred} transferred`];
            if (s.marked_dead > 0) parts.push(`${s.marked_dead} marked Dead`);
            if (s.excluded > 0) parts.push(`${s.excluded} protected (skipped)`);
            return `${getLaunchName(s.old_launch_id)} → ${getLaunchName(s.new_launch_id)}: ${parts.join(', ')}`;
          }).join('\n');

          notification.success({
            message: 'Lead Transfer Summary',
            description: <div style={{ whiteSpace: 'pre-line' }}>{description}</div>,
            duration: 8,
          });
        }
      }

      const res = await updateEmployeeData(id!, updateData);
      if (res.success) {
        notification.success({
          message: 'Success',
          description: res?.message,
        });
        setIsConfirmModalOpen(false);
        router.push('/employees');
      } else {
        notification.error({
          message: 'Update Error',
          description: res?.message,
        });
      }
    } catch (error: any) {
      notification.error({
        message: 'Error',
        description: error?.response?.data?.message || 'Something went wrong while saving.',
      });
    } finally {
      setSubmitionLoading(false);
    }
  };

  const handleRefreshTransferValidation = () => {

    // Re-fetch validation data
    checkTransferValidation(id!).then(res => {
      if (res.success) {
        setTransferValidationData(res.data);
        const isFStoTLPromotion = Number(originalRoleId) === getRoleByName('field_sales')?.id &&
          Number(roleId) === getRoleByName('team_lead')?.id &&
          !fsTlLaunchSelected;
        const actionable = res.data.filter((l: any) => l.show_for_pair_resolve || (!isFStoTLPromotion && l.show_for_self_transfer));
        // Hide section if no actionable launches
        if (actionable.length === 0) {
          setShowTransferPanels(false);
        }
        // Reset all transfer form fields and preview counts for actionable launches
        actionable.forEach((l: any) => {
          form.setFieldValue(['transfers', String(l.launch_id), 'new_launch_id'], undefined);
          form.setFieldValue(['transfers', String(l.launch_id), 'tab_status'], undefined);
          form.setFieldValue(['transfers', String(l.launch_id), 'current_status'], undefined);
        });
        setLaunchPreviewCounts({});
        // Clear invalid states and reset active keys
        setInvalidPairLaunchIds([]);
        setInvalidTransferLaunchIds([]);
        const hasPair = res.data.some((l: any) => l.show_for_pair_resolve);
        const hasTransfer = !isFStoTLPromotion && res.data.some((l: any) => l.show_for_self_transfer);
        setActiveCollapseKeys(hasPair ? ['pair_resolution'] : hasTransfer ? ['lead_transfer'] : []);
        setTransferPanelKey(prev => prev + 1);
      }
    });
  };

  return (
    <div>
      {id && loading ? (
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100vh',
          }}>
          <Spin size="large" />
        </div>
      ) : (
        <Form
          onValuesChange={() => {
            setFormChange(true);
          }}
          form={form}
          onFinish={onFinish}
          initialValues={{ status: 'Active', is_blocked: false }}
          layout="vertical"
        >
          <Card title={'Employee Detail'}
            // extra={
            //   <Form.Item
            //     name="is_blocked"
            //     valuePropName="checked"
            //     noStyle
            //   >
            //     <Switch
            //       checkedChildren="Blocked"
            //       unCheckedChildren="Unblocked"
            //       className="blocked-switch"
            //     />
            //   </Form.Item>
            // }
          >
            <Row gutter={24}>
              <Col span={24} sm={12}>
                <InputText
                  name="first_name"
                  label="First Name"
                  rules={[
                    { required: true, validator: userNameValidator('First') },
                  ]}
                  placeholder="First Name"
                />
              </Col>
              <Col span={24} sm={12}>
                <InputText
                  name="last_name"
                  label="Last Name"
                  rules={[
                    { required: true, validator: userNameValidator('Last') },
                  ]}
                  placeholder="Last Name"
                />
              </Col>
              <Col span={24} sm={12}>
                <InputText
                  name="phone"
                  label="Phone No. "
                  rules={[
                    { required: true, validator: userEmployeePhoneNoValidator(' ') },
                  ]}
                  placeholder="Phone Number"
                  extra={'Phone No. must be a Whatsapp No.'}
                />
              </Col>
              <Col span={24} sm={12}>
                <InputText
                  name="email"
                  label="Email"
                  disabled={isEmailFieldDisabled}
                  rules={[{ required: true, validator: userEmailValidator(' ') }]}
                  placeholder="Email"
                />
              </Col>
              {/* City DropDown */}
              <Col span={24} sm={12}>
                {cityOptions && cityOptions?.length > 0 ? (
                  <InputSelect
                    onChange={(value, item) => {
                      form.setFieldsValue({ city_id: item });
                      const role_id = form.getFieldValue('role_id')?.value;
                      handleRoleChange(role_id, true, [item]);
                    }}
                    label="City"
                    placeholder="City"
                    rules={[
                      { required: true, message: 'Please Select a City' },
                    ]}
                    disabled={areFieldsDisabled() || (id !== undefined && id !== null)}
                    mode={
                      roleId === getRoleByName('human_resources')?.id
                        ? 'multiple'
                        : undefined
                    }
                    options={cityOptions}
                    name={'city_id'}
                  />
                ) : (
                  <MasterCities
                    filter={{
                      status: 'active',
                    }}
                    onChange={(value, item) => {
                      form.setFieldsValue({ city_id: item });
                      const role_id = form.getFieldValue('role_id')?.value;
                      handleRoleChange(role_id, true, [item]);
                    }}
                    label="City"
                    rules={[
                      {
                        required: true,
                        message: 'Please Select a City',
                      },
                    ]}
                    disabled={areFieldsDisabled() || (id !== undefined && id !== null)}
                    mode={
                      roleId === getRoleByName('human_resources')?.id
                        ? 'multiple'
                        : undefined
                    }
                  />
                )}
              </Col>
              {/* Role DropDown */}
              <Col span={24} sm={12}>
                <MasterRoles
                  forwardRef={currentCity}
                  disabled={id !== undefined && id !== null}
                  filter={{
                    exclude_id: getRoleByName('super_admin')?.id,
                    city_id: city_id_watch?.length
                      ? city_id_watch[0].value
                      : city_id_watch?.value,
                  }}
                  onChange={(value, item) => {
                    form.setFieldsValue({ role_id: item });
                    let currentCity = form.getFieldValue('city_id');
                    setRoleId(value);
                    setShowLaunchDropdown(true)
                    form.setFieldsValue({
                      designation_id: null,
                      city_id: currentCity ? currentCity : undefined,
                    });
                    designationRef.current.reload({
                      role_id: value,
                    });
                    handleRoleChange(value);
                  }}
                  label="Role"
                  rules={[{ required: true, message: 'Please Select a Role' }]}
                />
              </Col>
              {/*  Designation Dropdown */}
              <Col span={24} sm={12}>
                <MasterDesignations
                  filter={{
                    status: 'active',
                    role_id: `${roleId}`,
                  }}
                  onChange={(value, item) => {
                    form.setFieldsValue({ designation_id: item });
                  }}
                  label="Designation"
                  rules={[
                    { required: true, message: 'Please Select a Designation' },
                  ]}
                  forwardRef={designationRef}
                  extra={
                    id === undefined && (
                      <Typography.Link onClick={handleAddDesignationClick}>
                        Click here to add new designation
                      </Typography.Link>
                    )
                  }
                />
              </Col>

              <ModalBox
                isModalOpen={isModalOpen}
                data={null}
                handleOk={handleOk}
                handleClose={handleCloseModal}
              />
              {/* Reporting Manager Dropdown */}
              {showReportingToField && (
                <Col span={24} sm={12}>
                  {id === undefined && (
                    <Checkbox
                      checked={noReportingManagerYet}
                      style={{ marginBottom: 8 }}
                      onChange={(e) => {
                        const checked = e.target.checked;
                        setNoReportingManagerYet(checked);
                        if (checked) {
                          form.setFieldsValue({ reporting_manager_id: undefined, manager_of_id: [] });
                          setReportingId(undefined);
                        }
                      }}
                    >
                      No manager yet — will be assigned via a promotion
                    </Checkbox>
                  )}
                  {!noReportingManagerYet && (
                  <MasterEmployees
                    forwardRef={reportingToField}

                    onSelect={(value, item) => {

                      handleFetchLaunch(
                        value,
                        item,
                        form,
                        dispatch,
                        fetchFilterLaunchList
                      );

                  

                      form.setFieldsValue({ reporting_manager_id: value });
                      setReportingId(value);
                      setShowLaunchDropdown(true);
                      form.setFieldsValue({ manager_of_id: [], launches: [] });

                      // Trigger transfer validation if editing a FS/PS or TL
                      const currentRoleId = form.getFieldValue('role_id')?.value;
                      const isSameManager = Number(value) === Number(previousReportingMangerId);
                      if (isSameManager) {
                        // Same manager re-selected — no transfer needed, clear any panels
                        setShowTransferPanels(false);
                        setTransferValidationData([]);
                        setSelectedSubstitutes({});
                        setLaunchPreviewCounts({});
                        setInvalidPairLaunchIds([]);
                        setInvalidTransferLaunchIds([]);
                      } else if (id && (
                        Number(currentRoleId) === getRoleByName('field_sales')?.id ||
                        Number(currentRoleId) === getRoleByName('pre_sales')?.id ||
                        Number(currentRoleId) === getRoleByName('team_lead')?.id
                      )) {
                        checkTransferValidation(id).then(res => {
                          if (res.success) {
                            setTransferValidationData(res.data);
                            // For FS→TL promotion, skip self lead transfer panel
                            const isFStoTLPromotion = Number(originalRoleId) === getRoleByName('field_sales')?.id &&
                              Number(currentRoleId) === getRoleByName('team_lead')?.id;
                            // Only show panels if there are launches that require action
                            const actionable = res.data.filter((l: TransferValidationItem) =>
                              l.show_for_pair_resolve || (!isFStoTLPromotion && l.show_for_self_transfer));
                            if (actionable.length > 0) {
                              setShowTransferPanels(true);
                              const hasPair = res.data.some((l: TransferValidationItem) => l.show_for_pair_resolve);
                              const hasTransfer = !isFStoTLPromotion && res.data.some((l: TransferValidationItem) => l.show_for_self_transfer);
                              setActiveCollapseKeys(hasPair ? ['pair_resolution'] : hasTransfer ? ['lead_transfer'] : []);
                              setInvalidPairLaunchIds([]);
                              setInvalidTransferLaunchIds([]);
                            } else {
                              setShowTransferPanels(false);
                            }
                            // Pre-fetch substitutes for each launch that has a pair
                            res.data.forEach((l: TransferValidationItem) => {
                              if (l.show_for_pair_resolve) {
                                fetchSubstitutes(l.launch_id, originalRoleId);
                              }
                            });

                            // Auto-select first launch if only one actionable exists
                            if (actionable.length === 1) {
                              form.setFieldsValue({ transfer_old_launch: actionable[0].launch_id });
                            }

                          }
                        });
                      }

                      //after setting reportingId, reload managerOfField.
                      // For editing an existing employee the 2-hop reporting_to filter
                      // finds their current team. For a NEW employee the chain doesn't
                      // exist yet (no one reports to them), so skip that filter and
                      // show all employees of the subordinate role in the city.
                      managerOfField.current?.reload({
                        reporting_to: id ? value : undefined,
                        city_id: city_id_watch?.length
                          ? city_id_watch[0].value
                          : city_id_watch?.value,
                        role_id: showManagerOfField,
                      });
                    }}
                    name="reporting_manager_id"
                    label="Reporting Manager"
                    placeholder="Please Select Reporting Manager"
                    rules={[
                      {
                        required: true,
                        message: 'Please Select a Reporting Manager',
                      },
                    ]}
                    filter={{
                      role_id: showReportingToField,
                      city_id: city_id_watch?.length
                        ? city_id_watch[0].value
                        : city_id_watch?.value,
                      reporting_to: reportingId,
                    }}
                    onClear={() => {
                      setReportingId(undefined);
                      form.setFieldsValue({ manager_of_id: [] });
                      //reload managerOfField to clear data — no reporting_to since it was cleared
                      managerOfField.current?.reload({
                        reporting_to: undefined,
                        city_id: city_id_watch?.length
                          ? city_id_watch[0].value
                          : city_id_watch?.value,
                        role_id: showManagerOfField,
                      });
                    }}
                  />
                  )}
                </Col>

              )}

              {showLaunchDropdown && filterLaunchLList &&
                (Number(roleId) === getRoleByName('team_lead')?.id ||
                Number(roleId) === getRoleByName('field_sales')?.id ||
                Number(roleId) === getRoleByName('pre_sales')?.id) && <Col span={24} sm={12}>
                <InputSelect
                  className="capitalize"
                  name="launches"
                  label="Launches"
                  placeholder="Choose Launches"
                  mode="multiple"
                  isSearchable
                  options={filterLaunchLList?.map((item: any) => ({
                    label: item.launch_name,
                    value: item.launch_id,
                  }))}
                  // rules={[{ required: true, message: 'Please select at least one launch' }]}
                  onSelect={(value) => {
                    form.setFieldsValue({ launches: value });
                    handleClickLaunchSelect(value);
                    // FS→TL: show self lead transfer panel when a launch is selected
                    const isFS = Number(originalRoleId) === getRoleByName('field_sales')?.id;
                    const isTL = Number(roleId) === getRoleByName('team_lead')?.id;
                    if (isFS && isTL) {
                      const hasLaunches = Array.isArray(value) && value.length > 0;
                      setFsTlLaunchSelected(hasLaunches);
                      if (hasLaunches) {
                        const hasSelfTransfer = transferValidationData.some((l: any) => l.show_for_self_transfer);
                        if (hasSelfTransfer) {
                          setShowTransferPanels(true);
                          setActiveCollapseKeys((prev) => [...new Set([...prev, 'lead_transfer'])]);
                        }
                      } else {
                        // No launches selected — hide self transfer
                        const hasPair = transferValidationData.some((l: any) => l.show_for_pair_resolve);
                        if (!hasPair) setShowTransferPanels(false);
                        setActiveCollapseKeys((prev) => prev.filter((k) => k !== 'lead_transfer'));
                      }
                    }
                  }}
                  onClear={() => {
                    form.setFieldsValue({ manager_of_id: [] });
                    // FS→TL: hide self transfer panel when launches are cleared
                    const isFS = Number(originalRoleId) === getRoleByName('field_sales')?.id;
                    const isTL = Number(roleId) === getRoleByName('team_lead')?.id;
                    if (isFS && isTL) {
                      setFsTlLaunchSelected(false);
                      const hasPair = transferValidationData.some((l: any) => l.show_for_pair_resolve);
                      if (!hasPair) setShowTransferPanels(false);
                      setActiveCollapseKeys((prev) => prev.filter((k) => k !== 'lead_transfer'));
                    }
                  }}
                />
              </Col>}
              {/* Manager Of drop down */}
              {/* {((showManagerOfField && showManagerOfField.length > 0 && reportingId) || (currentlyManagerOf.length > 0)) &&( */}
              {showManagerOfField && showManagerOfField.length > 0 && reportingId && (
                <Col span={24} sm={12}>
                  <MasterEmployees
                    mode="multiple"
                    value={Array.isArray(managerOfWatch) ? managerOfWatch : []}
                    forwardRef={managerOfField}
                    onChange={(value) => {
                      if (Array.isArray(value)) {
                        form.setFieldsValue({ manager_of_id: value });
                      } else {
                        form.setFieldsValue({ manager_of_id: [value] });
                      }
                    }}
                    name="manager_of_id"
                    label={`Manager Of`}
                    placeholder="Please Select Subordinates"
                    rules={[
                      {
                        required: false,
                        message: '',
                      },
                    ]}
                    filter={{
                      role_id: showManagerOfField!,
                      city_id: city_id_watch?.length
                        ? city_id_watch[0].value
                        : city_id_watch?.value,
                      // For an existing employee the 2-hop chain filter shows their
                      // current team. For a new employee the chain doesn't exist yet
                      // so omit it and show all subordinate-role employees in the city.
                      reporting_to: id ? reportingId : undefined,
                      userId: id ? id : null,
                      pageSize: 300,
                    }}
                    disabled={!reportingId}
                  />
                </Col>
              )}

              {/* Reassign To dropdown */}
              {showManagerOfField && showManagerOfField.length > 0 && reportingId && id !== undefined && (
                <Col span={24} sm={12} key={`index_of_${reportingId}`}>
                  <ReAssignEmployee
                    onSelect={(value) => {
                      form.setFieldsValue({ re_assign_to_id: value });
                    }}
                    name="re_assign_to_id"
                    label={`Reassign To`}
                    placeholder="Please Select Subordinates"
                    rules={[
                      {
                        required: false,
                        message: '',
                      },
                    ]}
                    filter={{
                      reporting_manager_id: previousReportingMangerId!,
                      userId: id,
                      role_id: showManagerOfField!,
                    }}
                    disabled={!reportingId}
                  />
                </Col>
              )}

              <Col span={24} sm={12}>
                <InputSelect
                  className="capitalize"
                  name="status"
                  label="Status"
                  placeholder="Status"
                  rules={[{ required: true, message: 'Please Select a Status' }]}
                  options={statusOptions}
                  onSelect={(value) => {
                    form.setFieldsValue({ status: value });
                  }}
                />
              </Col>
                {status_watch === 'inactive' && (inactiveValidation.launchRequired || launchReplacementLocked) && (
                  <Col span={24} sm={12}>
                    <MasterEmployees
                      name="launch_replacement_user_id"
                      label="Launch User Replacement"
                      placeholder="Please Select Launch User Replacement"
                      disabled={launchReplacementLocked}
                      defaultOption={launchReplacementDefaultOption}
                      rules={[
                        {
                          required: true,
                          message: 'Please select a Launch User Replacement before marking this employee as Inactive.',
                        },
                      ]}
                      filter={{
                        role_id: roleId,
                        reporting_manager_id: currentReportingManagerIdForReplacement,
                        status: 'active',
                        is_blocked: false,
                        userId: id ?? null,
                        // Field Sales replacement pool also includes their Team Leader (reporting manager)
                        include_user_ids:
                          Number(roleId) === DefaultRoles.field_sales.id && currentReportingManagerIdForReplacement
                            ? String(currentReportingManagerIdForReplacement)
                            : undefined,
                      }}
                      onChange={(value, item) => {
                        form.setFieldsValue({ launch_replacement_user_id: item });
                      }}
                    />
                  </Col>
                )}
                {status_watch === 'inactive' && (inactiveValidation.projectRequired || projectReplacementLocked) && (
                  <Col span={24} sm={12}>
                    <MasterEmployees
                      name="project_replacement_user_id"
                      label="Project Replacement User"
                      placeholder="Please Select Project Replacement User"
                      disabled={projectReplacementLocked}
                      defaultOption={projectReplacementDefaultOption}
                      rules={[
                        {
                          required: true,
                          message: 'Please select a Project Replacement User before marking this employee as Inactive.',
                        },
                      ]}
                      filter={{
                        city_id: city_id_watch?.length ? city_id_watch[0]?.value : city_id_watch?.value,
                        status: 'active',
                        is_blocked: false,
                        userId: id ?? null,
                      }}
                      onChange={(value, item) => {
                        form.setFieldsValue({ project_replacement_user_id: item });
                      }}
                    />
                  </Col>
                )}
              <Col span={24} sm={12}>
                <InputText
                  name="salary"
                  label="Salary"
                  addonAfter={convertToShorthand(Number(salary_watch) || 0)}
                  rules={[
                    {
                      required: true,
                      validator: salaryValidator(),
                    },
                  ]}
                  placeholder="Salary"
                />
              </Col>

              {showTransferPanels && (() => {
                const isFStoTLPromotion = Number(originalRoleId) === getRoleByName('field_sales')?.id &&
                  Number(roleId) === getRoleByName('team_lead')?.id &&
                  !fsTlLaunchSelected;
                const hasPairResolve = transferValidationData.some((l: any) => l.show_for_pair_resolve);
                const hasSelfTransfer = !isFStoTLPromotion && transferValidationData.some((l: any) => l.show_for_self_transfer);
                return (
                  <Col span={24}>
                    <div style={{ width: '100%' }}>
                      <Collapse
                        key={transferPanelKey}
                        className="custom-collapse"
                        style={{ marginTop: 24, marginBottom: 24 }}
                        activeKey={activeCollapseKeys}
                        onChange={(keys) => setActiveCollapseKeys(Array.isArray(keys) ? keys : [keys])}
                      >
                        {hasPairResolve && (
                          <Panel header="Pair Resolution" key="pair_resolution">
                            <EmployeeResolvePair
                              transferValidationData={transferValidationData}
                              substitutes={substitutes}
                              setSelectedSubstitutes={setSelectedSubstitutes}
                              invalidLaunchIds={invalidPairLaunchIds}
                              selectedSubstitutes={selectedSubstitutes}
                            />
                          </Panel>
                        )}
                        {hasSelfTransfer && (
                          <Panel
                            header="Self Lead Transfer To New Launch"
                            key="lead_transfer"
                            extra={
                              <Button
                                icon={<ReloadOutlined />}
                                onClick={handleRefreshTransferValidation}
                                size="small"
                                type="dashed"
                              >
                                Refresh
                              </Button>
                            }
                          >
                            <EmployeeLaunchTransfer
                              transferValidationData={transferValidationData}
                              launchPreviewCounts={launchPreviewCounts}
                              previewLoading={previewLoading}
                              filterLaunchLList={filterLaunchLList}
                              form={form}
                              fetchPreviewCounts={fetchPreviewCounts}
                              invalidLaunchIds={invalidTransferLaunchIds}
                              roleId={roleId}
                            />
                          </Panel>
                        )}
                      </Collapse>
                    </div>
                  </Col>
                );
              })()}

              {/* Issue #3 & #4: Fixed modal using selectedTransferLaunch context + showing transfer/dead counts */}
              {/* Modal for lead transfer confirmation removed per user request */}
            </Row>
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
              <Space direction="horizontal" align="end">
                <Button
                  type="default"
                  onClick={() => {
                    router.push('/employees');
                  }}>
                  Cancel
                </Button>
                <Button type="primary" htmlType="submit" loading={submitionLoading}>
                  {id !== undefined && id !== null
                    ? 'Update & Save'
                    : 'Save & Create'}
                </Button>
              </Space>
            </div>
            <ConfirmUpdateModal
              open={isConfirmUpdateOpen}
              onCancel={() => {
                setIsConfirmUpdateOpen(false);
                setSubmitionLoading(false);
              }}
              onConfirm={() => {
                setIsConfirmUpdateOpen(false);
                setIsConfirmModalOpen(true);
              }}
            />
            <ConfirmTransferModal
              open={isConfirmModalOpen}
              loading={submitionLoading}
              pairResolvingActive={pairResolvingStatus.active}
              leadTransferringActive={leadTransferringStatus.active}
              onCancel={() => {
                setIsConfirmModalOpen(false);
                setSubmitionLoading(false);
              }}
              onConfirm={() => {
                handleExecuteUpdate(
                  confirmModalData.pairsToResolve,
                  confirmModalData.transferLeads,
                  confirmModalData.updateData
                );
              }}
              pairResolutions={confirmModalData.pairResolutions}
              transferDetails={confirmModalData.transferDetails}
            />
         
          </Card>
        </Form>
      )}
    </div>
  );
};

export default AddEditEmployee;
