
'use client';
import { Table, Button, Form, Card, Drawer, Tooltip, Tabs, Tag } from 'antd';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import type { AppDispatch, RootState } from '@/store/store';
import { fetchAllLeads, fetchFilterLaunchList } from './slice';
import { ExportOutlined, PlusOutlined, LayoutOutlined, SettingOutlined } from '@ant-design/icons';
import SwitchComponent from '@/components/form/Switch';
import ScheduledCalendar from './components/ScheduledCalendar';
import ColumnHideShowModal from '@/components/commonModal/ColumnHideShowModal';
import InputSelect from '@/components/form/InputSelect';
import PageHeader from '@/components/pageHeader';
import {
  tabLabelMap,
  type ClearAllFiltersMethods,

  type ClearRadiosMethods,
  type Column,
  type LeadsPayload,
  type LeadsRecordI,
  type VisibleColumnsI,
  type filterI,
} from './interface';
import FilterLeads from './components/FilterLeads';
import { displayDate, displayTime, getRoleIdMap, hasPermission, removeEmptyKeys } from '@/utills/helper';
import { useRoles } from '@/hooks/useRoles';
import LeadsTabs from './components/LeadsTabs';
import { FILTERS, VISIBLE_COLUMNS, LEAD_TAGS } from './constant';
import { useSession } from 'next-auth/react';
import { LEADS_STATUS, PERMISSIONS } from '@/utills/constant';
import type { TabsProps } from 'antd';
import LeadDetailsPage from './view-lead/[id]/LeadDetailsPage';
import FormattedAmount, { FormattedBudget } from '@/components/amountFormat/AmountFormatter';
// import ProgressiveDropdowns from './components/ProgressiveDropdowns';
import AddEditLeads from './components/AddLead';
import { getExportLeads } from './service';
import { checkLeadMatchesTab, tableScrollToStart } from './common';
import { useRouter, useSearchParams, usePathname } from 'next/navigation';
import { fetchRoles } from '../role/slice';
import LeadImportModalBox from './components/LeadImportModal';
import DashboardProgressiveDropdownsTest from '../dashboard/components/DashboardProgressiveDropdownsTest';
import ReviveLeadModal from './components/ReviveLeadModal';
interface FilterMasterRolesBased {
  city_id?: string;
  reporting_manager_id?: string | number;
  // Add other fields if necessary
}
interface RecordType {
  id: number;
  scheduled_date: string; // or Date, depending on your data
  status_id: number; // or number, depending on your data
  team_stage: string;
  launch_name?: string;
  agreement_value: number;
  min_budget: number;
  max_budget: number;
  // Add other properties as necessary
}

const AllLeadsPage: React.FC = () => {
  const [form] = Form.useForm();
  const [showHideColumnModal, setShowHideColumnModal] = useState<boolean>(false);
  const [showLeadsCalendar, setShowLeadsCalendar] = useState<boolean>(false);
  const urlParams = new URLSearchParams(window.location.search);
  const tabkey = urlParams.get('tabkey');
  const urlStartDate = urlParams.get('start_date');
  const urlEndDate = urlParams.get('end_date');
  const urlUserId = urlParams.get('lead_user_id');
  const urlUserRole = urlParams.get('lead_user_role_name');
  const urlAncestorIds = urlParams.get('ancestor_ids')
    ? urlParams.get('ancestor_ids')!.split(',').map(Number).filter(Boolean)
    : [];

  const [selectedMenuItem, setSelectedMenuItem] = useState(tabkey || 'all_leads');
  const [filters, setFilters] = useState<filterI>({
    ...FILTERS,
    ...(urlStartDate && urlEndDate
      ? {
          start_date: `${urlStartDate} 00:00:00`,
          end_date: `${urlEndDate} 23:59:59`,
        }
      : {}),
    ...(urlUserId ? { lead_user_id: parseInt(urlUserId, 10) } : {}),
    ...(urlUserRole ? { lead_user_role_name: urlUserRole } : {}),
    // When coming from analytics Cancellations click (tabkey=dead + date range),
    // pre-apply "Booking Cancel" (id=19) so only cancelled bookings are shown.
    ...(tabkey === 'dead' && urlStartDate && urlEndDate ? { status_id: [LEADS_STATUS.bookingCancelled.id] } : {}),
  });
  const [roleFilters, setRoleFilters] = useState<any>({
      page: 1,
      sortColumn: 'sort_order',
    });
  const [visibleColumns, setVisibleColumns] = useState<VisibleColumnsI>({ ...VISIBLE_COLUMNS });
  const { allLeads, leadsMeta, status } = useSelector((state: RootState) => state.allLeads);
  const { roles } = useSelector((state: RootState) => state.roles);
  const filterLaunchLList = useSelector((state: RootState) => state?.allLeads?.filterLaunchLList);
  const launchListOptions = filterLaunchLList?.map((project: any) => ({
    value: project.launch_id,
    label: project.launch_name,
  }));
  const [leadDetailsPage, setLeadDetailsPage] = useState<number | null>(null);
  const [addLeadPage, setAddLeadPage] = useState<boolean>(false);
  const [tabChanging, setTabChanging] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [reviveLeadModalVisible, setReviveLeadModalVisible] = useState(false);
  const [selectedReviveLeadId, setSelectedReviveLeadId] = useState<number | null>(null);

  const clearAllFilters = useRef<ClearAllFiltersMethods | null>(null);
  const clearRadiosOnTabChange = useRef<ClearRadiosMethods | null>(null);
  const dispatch: AppDispatch = useDispatch();
  const { data: session } = useSession();
  const user = session?.user;
  const userCities = session?.user?.cities;
  const userRoleId = session?.user?.role?.id;

  const isCreatable = hasPermission(user, PERMISSIONS.LEAD_CREATE.name);
  const router = useRouter();
  const params = useSearchParams();
  const pathname = usePathname();

  const id: any = params.get('id');

  // Fetch lead details when 'id' changes
  useEffect(() => {
    showLeadDetailDrawer(id);
  }, [id]);

  // Fetch visible columns from local storage on component mount
  useEffect(() => {
    if (window) {
      const cols = window.localStorage.getItem('leadsColumns');
      if (cols) {
        setVisibleColumns(JSON.parse(cols));
      }
    }
  }, []);

  // Fetch projects list when role or relevant filters change
  useEffect(() => {
     dispatch(fetchFilterLaunchList(filters));
  }, [userRoleId, filters.cluster_manager_id, filters.city_head_id, filters.lead_user_city_id, filters.veiw_data, filters.lead_user_id, filters.lead_user_role_name]);

  useEffect(() => {
    if(roles?.length === 0) {
      dispatch(fetchRoles(roleFilters));
    }
  }, [roles]);
  // Function to fetch leads data based on filters and tab key
  const fetchLeads = async(filters: filterI, tabKey = selectedMenuItem): Promise<void> => {
    setTabChanging(true);
    const table = filters.filterTabs[tabKey as keyof typeof filters.filterTabs];
    let obj = {
      filters: {
        ...filters,
        ...table,
      },
      tabKey,
    };
    await dispatch(fetchAllLeads(obj));
    setFilters(obj.filters);
    setTabChanging(false);
  };

  let allRoles = getRoleIdMap(roles)
  const { getRoleByName, isLeafRole } = useRoles();

const leadTabMap = useMemo(() => {
  const map: Record<string, string> = {};

  allLeads?.forEach((lead: LeadsRecordI) => {
    for (const key of Object.keys(visibleColumns)) {
      if (key === 'all_leads') continue;
      if (checkLeadMatchesTab(key, lead)) {
        map[lead.id] = key;
        break; // assign to first matching tab
      }
    }
  });

  return map;
}, [allLeads]);

const columns = visibleColumns[selectedMenuItem]
  ?.filter((col: Column) => col.isVisible)
  .map((col: Column) => {
    if (col.key === 'stage') {
      return {
        ...col,
        render: (_value: string, record: LeadsRecordI) => {
          if (selectedMenuItem === 'all_leads') {
            const tabKey = leadTabMap[record.id];
            return <>{tabLabelMap[tabKey] || 'Not in other tabs'}</>;
          }

          return record.stage;
        },
      };
    }
    if (col.key === 'customer_name') {
      col.render = (text: string, record: LeadsRecordI) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span>{text}</span>
          {record.is_transferred === 1 && (
            <Tooltip
              title={
                <div>
                  {record.transfer_type === 'self_transfer' ? (
                    <>
                      <div style={{ fontWeight: 600, marginBottom: 4 }}>Self Transfer</div>
                      <div>From {record.transferred_from_launch_name || 'Unknown'} to {record.launch_name || 'Unknown'}</div>
                    </>
                  ) : (
                    <>
                      <div style={{ fontWeight: 600, marginBottom: 4 }}>Lead Transfer</div>
                      <div>From {record.transferred_from_employee_name || 'Unknown'} to {record.transferred_to_employee_name || 'Unknown'}</div>
                    </>
                  )}
                  {record.transferred_at && <div>Transfer Date: {displayDate(record.transferred_at)}</div>}
                  {record.transfer_remark && <div>Remark: {record.transfer_remark}</div>}
                </div>
              }
            >
              <Tag color="orange" style={{ fontSize: 10, lineHeight: '16px', padding: '0 4px', margin: 0, cursor: 'pointer' }}>Transferred</Tag>
            </Tooltip>
          )}
        </div>
      );
    }
    // Render logic for isDate
    if (col.isDate) {
      col.render = (text: string) => displayDate(text);
    } else if (col?.isDateTime) {
      col.render = (text: string, record: RecordType) => {
        if (
          ['today_follow_up', 'overdue'].includes(selectedMenuItem) &&
                    [
                      LEADS_STATUS.scheduled_sv.id,
                      LEADS_STATUS.scheduled_vc.id,
                      LEADS_STATUS.scheduled_obm.id,
                    ].includes(record.status_id)
        ) {
          return `${displayDate(record.scheduled_date)} ${displayTime(
            record.scheduled_date
          )}`;
        } else {
          return `${displayDate(text)} ${displayTime(text)}`;
        }
      };
    } else if (col?.dataIndex === 'remark') {
      col.render = (text: string) => {
      return (
      <div className="remark-text-length">
          <Tooltip
            destroyTooltipOnHide={true}
            title={text}>
            {text}
          </Tooltip>
        </div>)
      };
    }
    if (col.key === 'project_name') {
      col.render = (text: string, record: RecordType) => {
        return selectedMenuItem && record.launch_name ? (
          <div id={`project_name_${record.id}`}>
            <Tooltip
              key={`project_name_${record.id}`}
              getPopupContainer={() => {
                const element = document.getElementById(`project_name_${record.id}`);
                return element || document.body; // If not found, use a default element
              }}
              destroyTooltipOnHide={true}
              title={record.launch_name}>
              {text}
            </Tooltip>
          </div>
        ) : (
          text
        );
      };
    }
    if (['booked'].includes(selectedMenuItem)) {
      if (col.key === 'agreement_value') {
        col.render = (text: string, record: RecordType) => (
          <>
            <FormattedAmount amount={record.agreement_value} />
          </>
        );
      }
    } else  if (col.key === 'min_budget') {
      col.render = (text: string, record: RecordType) => (
        <>
          <FormattedBudget minAmount={record.min_budget} maxAmount={record.max_budget} />
        </>
      );
    }
    if (col.key === 'tag') {
      col.render = (text: string) => {
        const tag = LEAD_TAGS.find(t => t.value === text);
        return tag ? tag.label : text || '-';
      };
    }
    if (col.key === 'action') {
      col.render = (_text: string, record: LeadsRecordI) => {
        if (selectedMenuItem === 'dead') {
          return (
            <Button
              type="primary"
              size="small"
              onClick={(e) => {
                e.stopPropagation();
                setSelectedReviveLeadId(record.id);
                setReviveLeadModalVisible(true);
              }}
            >
              Revive
            </Button>
          );
        }
        return null;
      };
    }

    // Default return if no customization
    return col;
  });

  const handleTabClick = (key: string) => {
    // Prepare filters based on selected tab
    if (filters.status_id) {
      if (key === 'scheduled') {
        switch (Number(filters.status_id)) {
        case LEADS_STATUS?.scheduled_sv?.id:
        case LEADS_STATUS?.scheduled_obm?.id:
        case LEADS_STATUS?.scheduled_vc?.id:
          break;
        default:
          filters.status_id = null;
          break;
        }
      }
      if (key === 'visited') {
        switch (Number(filters.status_id)) {
        case LEADS_STATUS?.visit_sv?.id:
        case LEADS_STATUS?.visit_obm?.id:
        case LEADS_STATUS?.visit_vc?.id:
          break;
        default:
          filters.status_id = null;
          break;
        }
      }
    }
    let newFilters: filterI = filters;
    const shouldResetDates = (key !== 'visited' && key !== 'token_done' && key !== 'booked' && key!== 'dead' && key !== 'all_leads');
    if (shouldResetDates) {
      newFilters = { ...filters, start_date: '', end_date: '' }
    }
    // Clear status_history when leaving the overdue tab (it's overdue-only)
    if (key !== 'overdue') {
      newFilters = { ...newFilters, status_history: undefined } as any;
    }
    setFilters(newFilters);
    setShowLeadsCalendar(false);
    setSelectedMenuItem(key);
    fetchLeads(JSON.parse(JSON.stringify(newFilters)), key);
    if (key === 'scheduled' || key === 'visited') {
      setShowLeadsCalendar(false);
    }
    tableScrollToStart();
    router.push('/enquiries');
  };

  const handleSwitchChange = (checked: boolean): void => {
    setShowLeadsCalendar(checked);
  };

  const handleCloseModal = (): void => {
    setShowHideColumnModal(false);
  };

  // Function to handle table column sorting, pagination, and filtering
  const handleTableChange = (
    pagination: LeadsPayload,
    filters: filterI,
    sorter: filterI
  ): void => {
    const fiData = filters.filterTabs[selectedMenuItem as keyof typeof filters.filterTabs];
    fiData.page = pagination?.current;
    fiData.pageSize = pagination?.pageSize;

    if (sorter?.order === 'ascend') {
      fiData.sortOrder = 'asc';
      fiData.sortColumn = sorter?.field ?? '';
    } else if (sorter?.order === 'descend') {
      fiData.sortOrder = 'desc';
      fiData.sortColumn = sorter?.field ?? '';
    } else {
      fiData.sortOrder = '';
      fiData.sortColumn = '';
    }

    // Update filters and fetch leads
    const newFilters: filterI = {
      ...filters,
      filterTabs: {
        ...filters.filterTabs,
        [selectedMenuItem as keyof typeof filters.filterTabs]: fiData,
      },
    };
    setFilters(newFilters);
    fetchLeads(newFilters);
  };

  // Function to set row click behavior
  const onRow = (record: LeadsRecordI) => {
    if(selectedMenuItem === 'all_leads') {
      return {
        onClick: () => {
            console.log('clicked')
          },
          style: { cursor: 'pointer' },
        };
    } else {
      return {
        onClick: () => {
            showLeadDetailDrawer(record.id);
          },
          style: { cursor: 'pointer' },
        };
    }
  };

  // Determine filter values based on user role
  let filterMasterRolesBased: FilterMasterRolesBased = {};

  if (userCities && userCities.length > 0) {
    filterMasterRolesBased.city_id = `${userCities[0]}`;
  }
  if (user?.role) {
    switch (user?.role.id) {
    case getRoleByName('cluster_manager')?.id:
    case getRoleByName('team_lead')?.id:
      filterMasterRolesBased.reporting_manager_id = user.id;
      break;
            // Add more cases for other roles if needed
    }
  }

  function showLeadDetailDrawer(id: number) {
    if (id === null) {
      setLeadDetailsPage(null);
    } else {
      // Add CSS to the html and body tags when Drawer is open
      document.documentElement.style.overflow = 'hidden';
      document.body.style.overflow = 'hidden';
    }
    setLeadDetailsPage(id);
  }

  const onLeadDetailClose = () => {
    setLeadDetailsPage(null);
    // Remove CSS when Drawer is closed
    document.documentElement.style.overflow = '';
    document.body.style.overflow = '';
    router.push(pathname);
  };
  const onSuccessLeadDetailClose = () => {
    onLeadDetailClose();
    fetchLeads(filters);
  };

  const showAddLeadDrawer = () => {
    setAddLeadPage(true);
    // Add CSS to the html and body tags when Drawer is open
    document.documentElement.style.overflow = 'hidden';
    document.body.style.overflow = 'hidden';
  };

  const onAddLeadClose = () => {
    setAddLeadPage(false);
    // Remove CSS when Drawer is closed
    document.documentElement.style.overflow = '';
    document.body.style.overflow = '';
  };

  const onSuccessAddLeadClose = () => {
    onAddLeadClose();
    fetchLeads(filters);
  };

  const updateFilters = (filterUpdates: Partial<filterI>): void => {
    const fiData = filters.filterTabs[selectedMenuItem as keyof typeof filters.filterTabs];
    fiData.page = 1;

    const newFilters = {
      ...filters,
      ...filterUpdates,

      filterTabs: {
        ...filters.filterTabs,
        [selectedMenuItem as keyof typeof filters.filterTabs]: fiData,
      },
    };
    setFilters(newFilters);
    fetchLeads(newFilters);
  };

  const handleLeadExport = () => {
    const queryString = removeEmptyKeys({
      ...filters,
      ...filters.filterTabs[selectedMenuItem as keyof typeof filters.filterTabs],
    });
    if (allLeads.length) {
      getExportLeads(queryString, selectedMenuItem);
    }
  };

  const resetLaunchList = () => {
    form.resetFields(['launch_list']);
    setFilters({ ...filters, launch_id: '' });
  };

  const items: TabsProps['items'] = [
    {
      key: 'all_leads',
      label: `All Leads ${
        selectedMenuItem === 'all_leads' && tabChanging === false
          ? `(${leadsMeta?.total !== undefined ? leadsMeta?.total : 0})`
          : ''
      }`,
      children: null,
      disabled: tabChanging === true,
    },
    {
      key: 'today_follow_up',
      label: `Today's Follow Up ${
        selectedMenuItem === 'today_follow_up' && tabChanging === false
          ? ` (${leadsMeta?.total !== undefined ? leadsMeta?.total : 0})`
          : ''
      }`,
      children: null,
      disabled: tabChanging === true,
    },
    {
      key: 'fresh_lead',
      label: `Fresh Leads ${
        selectedMenuItem === 'fresh_lead' && tabChanging === false
          ? ` (${leadsMeta?.total !== undefined ? leadsMeta?.total : 0})`
          : ''
      }`,
      children: null,
      disabled: tabChanging === true,
    },
    {
      key: 'active',
      label: `Active Leads ${
        selectedMenuItem === 'active' && tabChanging === false
          ? ` (${leadsMeta?.total !== undefined ? leadsMeta?.total : 0})`
          : ''
      }`,
      children: null,
      disabled: tabChanging === true,
    },
    {
      key: 'overdue',
      label: `Overdue Leads ${
        selectedMenuItem === 'overdue' && tabChanging === false
          ? `(${leadsMeta?.total !== undefined ? leadsMeta?.total : 0})`
          : ''
      }`,
      children: null,
      disabled: tabChanging === true,
    },
    {
      key: 'scheduled',
      label: `Scheduled Leads ${
        selectedMenuItem === 'scheduled' && tabChanging === false
          ? ` (${leadsMeta?.total !== undefined ? leadsMeta?.total : 0})`
          : ''
      }`,
      children: null,
      disabled: tabChanging === true,
    },
    {
      key: 'visited',
      label: `Visited Leads ${
        selectedMenuItem === 'visited' && tabChanging === false
          ? `(${leadsMeta?.total !== undefined ? leadsMeta?.total : 0})`
          : ''
      }`,
      children: null,
      disabled: tabChanging === true,
    },
    {
      key: 'token_done',
      label: `Token Done Leads ${
        selectedMenuItem === 'token_done' && tabChanging === false
          ? `(${leadsMeta?.total !== undefined ? leadsMeta?.total : 0})`
          : ''
      }`,
      children: null,
      disabled: tabChanging === true,
    },
    {
      key: 'booked',
      label: `Booked Leads ${
        selectedMenuItem === 'booked' && tabChanging === false
          ? `(${leadsMeta?.total !== undefined ? leadsMeta?.total : 0})`
          : ''
      }`,
      children: null,
      disabled: tabChanging === true,
    },
    {
      key: 'dead',
      label: `Dead Leads  ${
        selectedMenuItem === 'dead' && tabChanging === false ? ` (${leadsMeta?.total !== undefined ? leadsMeta?.total : 0})` : ''
      }`,
      children: null,
      disabled: tabChanging === true,
    },
  ];

  const handleLeadImportModalOpen = (): void => {
    setIsModalOpen(true);
  };

  const handleLeadImportModalClose = (): void => {
    setIsModalOpen(false);
  };
  let showCombineView = userRoleId === getRoleByName('team_lead')?.id || userRoleId === getRoleByName('field_sales')?.id || userRoleId === getRoleByName('pre_sales')?.id;

  return (
    <div>
      <PageHeader
        title="All Leads"
        isBack={false}
        headerClass="all-leads-page-header"
        leftExtra={
          <>
            {/* <ProgressiveDropdowns
              onUpdateFilters={updateFilters}
              loading={tabChanging}
              resetLaunchList={resetLaunchList}
            /> */}
            <DashboardProgressiveDropdownsTest
              onUpdateFilters={updateFilters}
              onApply={() => {
                // fetchLeads is already called inside updateFilters with the correct merged filters.
                // Do NOT call fetchLeads(filters) here — `filters` is stale state at this point.
              }}
              loading={tabChanging}
              resetLaunchList={resetLaunchList}
              viewData={form.getFieldValue('veiw_data')}
              showCombineView= {showCombineView}
              initialUserId={urlUserId ? parseInt(urlUserId, 10) : null}
              initialUserRole={urlUserRole || null}
              initialAncestorIds={urlAncestorIds.length ? urlAncestorIds : undefined}
            />
          </>
        }
        extra={
          <Form form={form} initialValues={{ launch_list: null }}>
            <div className="leads-right-filter">

              <Form.Item
                label="Showing Data For:"
                className="label-showing-data-for"></Form.Item>
              <InputSelect
                options={launchListOptions}
                className="project-list-select"
                name="launch_list"
                placeholder="Launch List"
                isSearchable
                onSelect={(value) => {
                  Object.keys(filters.filterTabs).map((item: string) => {
                    filters.filterTabs[
                                            item as keyof typeof filters.filterTabs
                    ] = {
                      ...filters.filterTabs[
                                                item as keyof typeof filters.filterTabs
                      ],
                      page: 1,
                    };
                  });
                  setFilters({ ...filters, launch_id: value });
                  fetchLeads({ ...filters, launch_id: value });
                }}
                onClear={() => {
                  resetLaunchList();
                }}
                disabled={tabChanging === true}
              />
              {isCreatable ? (
                <Button
                  type="primary"
                  // icon={<PlusOutlined />}
                  onClick={handleLeadImportModalOpen}
                  className="add-lead-btn">
                                Import
                </Button>
              ) : null}
              {isCreatable ? (
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={showAddLeadDrawer}
                  className="add-lead-btn">
                                Add Lead
                </Button>
              ) : null}
              {/* Access given to city head for Lead exports as well as super admin*/}
              {(userRoleId === getRoleByName('super_admin')?.id || userRoleId === getRoleByName('city_head')?.id) && selectedMenuItem != 'all_leads' && (
                <Button
                  onClick={handleLeadExport}
                  disabled={!allLeads?.length}
                  type="primary"
                  ghost
                  icon={<ExportOutlined />}
                  className="export-btn">
                                Export Data
                </Button>
              )}
            </div>
          </Form>
        }
      />
      {(selectedMenuItem === 'scheduled' || selectedMenuItem === 'visited') && (
        <div className="switch-calendar-list">
          <h4>List</h4>
          <SwitchComponent
            unCheckedChildren="List"
            checkedChildren="Calendar"
            checked={showLeadsCalendar}
            onChange={handleSwitchChange}
          />
          <h4>Calendar</h4>
        </div>
      )}
      <div>
        <div>
          <div>
            {!showLeadsCalendar && (
              <Tabs
                defaultActiveKey={selectedMenuItem}
                items={items}
                className="all-leads-tabs"
                onChange={handleTabClick}
              />
            )}

            {!showLeadsCalendar && (
              <Card
                size="small"
                className="mb-3"
                style={{
                  borderTop: 'none',
                  padding: 0,
                  borderRadius: '0 0 8px 8px',
                }}>
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'flex-start',
                    gap: '16px',
                  }}>
                  <FilterLeads
                    forwardRef={clearAllFilters}
                    onSearch={(filter) => {
                      fetchLeads({ ...filter });
                    }}
                    showLeadsCalendar={showLeadsCalendar}
                    selectedMenuItem={selectedMenuItem}
                    setFilters={setFilters}
                    filters={filters}
                    initialDateRange={
                      urlStartDate && urlEndDate
                        ? [urlStartDate, urlEndDate]
                        : null
                    }
                  />

                  <Button
                    icon={
                      <div className="column-layout-icon">
                        <LayoutOutlined />
                        <SettingOutlined />
                      </div>
                    }
                    onClick={() => {
                      setShowHideColumnModal(true);
                    }}
                    className="column-layout-btn"
                  />
                </div>
              </Card>
            )}
            <ColumnHideShowModal
              visibleColumns={visibleColumns}
              setVisibleColumns={setVisibleColumns}
              selectedMenuItem={selectedMenuItem}
              showHideColumnModal={showHideColumnModal}
              handleCloseModal={handleCloseModal}
            />

            {selectedMenuItem === 'all_leads' && (
              <Table
                columns={columns}
                dataSource={allLeads}
                bordered
                rowKey="id"
                onRow={onRow}
                rowClassName={(record: LeadsRecordI) => record.lead_status_name === 'Interested' ? 'custom-error-row' : ''}
                tableLayout="fixed"
                scroll={{ x: true }}
                className="table-layout-fixed"
                loading={tabChanging === true}
                pagination={{
                  current: leadsMeta?.current_page,
                  pageSize: leadsMeta?.per_page,
                  total: leadsMeta?.total,
                  showSizeChanger: true,
                  pageSizeOptions: ['10', '20', '50', '100'],
                  defaultPageSize: 10,
                  showTotal: (total, range) =>
                    `${range[0]}-${range[1]} of ${total} entries`,
                }}
                onChange={(pagination: any, tableFilters: any, sorter: any) => {
                  const myTableFilter = {
                    ...tableFilters,
                    ...filters,
                  };
                  handleTableChange(pagination, myTableFilter, sorter);
                }}
              />
            )}

            {selectedMenuItem === 'today_follow_up' && (
              <Table
                columns={columns}
                dataSource={allLeads}
                bordered
                rowKey="id"
                onRow={onRow}
                rowClassName={(record: LeadsRecordI) => record.lead_status_name === 'Interested' ? 'custom-error-row' : ''}
                tableLayout="fixed"
                scroll={{ x: true }}
                className="table-layout-fixed"
                loading={tabChanging === true}
                pagination={{
                  current: leadsMeta?.current_page,
                  pageSize: leadsMeta?.per_page,
                  total: leadsMeta?.total,
                  showSizeChanger: true,
                  pageSizeOptions: ['10', '20', '50', '100'],
                  defaultPageSize: 10,
                  showTotal: (total, range) =>
                    `${range[0]}-${range[1]} of ${total} entries`,
                }}
                onChange={(pagination: any, tableFilters: any, sorter: any) => {
                  const myTableFilter = {
                    ...tableFilters,
                    ...filters,
                  };
                  handleTableChange(pagination, myTableFilter, sorter);
                }}
              />
            )}

            {showLeadsCalendar === true && (
              <ScheduledCalendar
                filters={filters}
                onShowTask={showLeadDetailDrawer}
                selectedMenuItem={selectedMenuItem}
              />
            )}
            {(selectedMenuItem === 'active' ||
                        selectedMenuItem === 'fresh_lead' ||
                            selectedMenuItem === 'overdue' ||
                            (selectedMenuItem === 'scheduled' && !showLeadsCalendar) ||
                            (selectedMenuItem === 'visited' && !showLeadsCalendar) ||
                            selectedMenuItem === 'token_done' ||
                            selectedMenuItem === 'booked' ||
                            selectedMenuItem === 'dead') && (
              <LeadsTabs
                selectedMenuItem={selectedMenuItem}
                status={status}
                forwardRef={clearRadiosOnTabChange}
                filters={filters}
                columns={columns}
                showLeadsCalendar={showLeadsCalendar}
                allLeads={allLeads}
                handleTableChange={handleTableChange}
                leadsMeta={leadsMeta}
                onRow={onRow}
                rowClassName={(record: LeadsRecordI) => record.lead_status_name === 'Interested' ? 'custom-error-row' : ''}
                loading={tabChanging}
              />
            )}
          </div>
        </div>
      </div>

      <Drawer
        title="Lead Detail"
        width={'calc(100vw - 235px)'}
        onClose={onLeadDetailClose}
        open={leadDetailsPage !== null}
        className="lead-detail-drawer">
        {leadDetailsPage && (
          <LeadDetailsPage
            params={{ id: `${leadDetailsPage}` }}
            getLeads={() => fetchLeads(filters)}
            onClose={onLeadDetailClose}
            onSuccess={onSuccessLeadDetailClose}
          />
        )}
      </Drawer>
      <Drawer
        title="Create New Lead"
        width={'calc(100vw - 235px)'}
        onClose={onAddLeadClose}
        open={addLeadPage === true}>
        {addLeadPage && (
          <AddEditLeads
            launchId={null}
            onSuccess={onSuccessAddLeadClose}
            onClose={onAddLeadClose}
          />
        )}
      </Drawer>
      <LeadImportModalBox
        isModalOpen={isModalOpen}
        // data={EditValue}
        handleOk={handleLeadImportModalClose}
        handleClose={handleLeadImportModalClose}
      />
      <ReviveLeadModal
        visible={reviveLeadModalVisible}
        onClose={() => setReviveLeadModalVisible(false)}
        onSuccess={() => fetchLeads(filters)}
        leadId={selectedReviveLeadId!}
      />
    </div>
  );
};

export default AllLeadsPage;

