'use client';
import React, { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import PageHeader from '@/components/pageHeader';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '@/store/store';
import { resetDashboardFilter, setDashboardFilter } from './slice';
import dynamic from 'next/dynamic';
// import WeekStatistics from './components/WeekStatistics';
import { useRouter } from 'next/navigation';
// import LeadsStatistics from './components/LeadsStatistics';
// import DashboardProgressiveDropdowns from './components/DashboardProgressiveDropdowns';
import { Form, Spin } from 'antd';
import InputSelect from '@/components/form/InputSelect';
import { fetchFilterLaunchList } from '../enquiries/slice';
import { fetchRoles } from '../role/slice';
import { useRoles } from '@/hooks/useRoles';
import DashboardProgressiveDropdownsTest from './components/DashboardProgressiveDropdownsTest';
const LeadsStatistics = dynamic(() => import('./components/LeadsStatistics'), {
  loading: () => <p className="visually-hidden">Loading Leads Statistics...</p>,
  ssr: false,
});
const WeekStatistics = dynamic(() => import('./components/WeekStatistics'), {
  loading: () => <p className="visually-hidden">Loading Week Statistics...</p>,
  ssr: false,
});
// SourceQuality and SourceEfficiency temporarily disabled
// const SourceQuality = dynamic(() => import('./components/SourceQuality'), {
//   loading: () => <p className="visually-hidden">Loading Source Quality...</p>,
//   ssr: false,
// });
// const SourceEfficiency = dynamic(() => import('./components/SourceEfficiency'), {
//   loading: () => <p className="visually-hidden">Loading Source Efficiency...</p>,
//   ssr: false,
// });
const SourceQualityOverall = dynamic(() => import('./components/SourceQualityOverall'), {
  loading: () => <p className="visually-hidden">Loading Source Quality Overall...</p>,
  ssr: false,
});
import EnvironmentBanner from '../enquiries/components/EnvironmentBanner';

const DashboardPage = () => {
  const { data } = useSession();
  const route = useRouter();
  const [form] = Form.useForm();
  const [filters, setFilters] = useState<any>({
    page: 1,
    sortColumn: 'sort_order',
  });
  const dispatch: AppDispatch = useDispatch();
  const { roles, status } = useSelector((state: RootState) => state.roles);
  const {
    statisticsStatus,
    sourceEfficiencyTeamLeadStatus,
    sourceEfficiencyStatus,
    sourceQualityTeamLeadStatus,
    dashboardSourceQualityStatus,
    weekStatisticsStatus,
    dashboardCallingStaticsStatus,
    dashboardFilter,
  } = useSelector((state: RootState) => state.dashboard);

  useEffect(() => {
    fetchProjectsList();
  }, [
    dashboardFilter.lead_user_city_id,
    dashboardFilter.lead_user_id,
    dashboardFilter.lead_user_role_name,
  ]);

  useEffect(() => {
    // handleGetRoles(filters);
    if (status === 'loading' || (status === 'succeeded' && roles?.length === 0)) {
      dispatch(fetchRoles(filters));
    }
  }, [])
  // const handleGetRoles = (filter: string): void => {
  // };

  const filterLaunchLList = useSelector((state: RootState) => state?.allLeads?.filterLaunchLList);
  const launchListOptions = filterLaunchLList?.map((project: { launch_id: string; launch_name: string; }) => ({
    value: project.launch_id,
    label: project.launch_name,
  }));

  const { getRoleByName, isLeafRole, config } = useRoles();
  // Build a legacy allRoles map for child components (SourceQuality, SourceEfficiency) that still expect it
  const allRoles: Record<string, number> = {};
  for (const r of config.roles) {
    allRoles[r.name] = r.id;
  }
  const [leadStatsLoaded, setLeadStatsLoaded] = useState(false);
  const [weekStatsLoaded, setWeekStatsLoaded] = useState(false);
  const [sourceQualityLoaded, setSourceQualityLoaded] = useState(false);
const [filtersReady, setFiltersReady] = useState(false);
  // Name of the user selected via the hierarchy dropdowns above, if any — passed
  // down to SourceQualityOverall so its report page can show "viewing as" the
  // actual person, not just the raw role/id already in dashboardFilter.
  const [selectedUserName, setSelectedUserName] = useState<string | null>(null);

useEffect(() => {
  if (data?.user?.role?.id != null) {
    setFiltersReady(isLeafRole(data.user.role.id));
  }
}, [data?.user?.role?.id]);
  // Only show loading spinner for the currently loading component
  let loading = false;

  /*====Original===*/
  // if (!leadStatsLoaded) {
  //   loading = true;
  // } else if (!weekStatsLoaded) {
  //   loading = true;
  // } else if (!sourceQualityLoaded && data?.user?.role?.id !== getRoleByName('pre_sales')?.id && data?.user?.role?.id !== getRoleByName('field_sales')?.id) {
  //   loading = true;
  // }

  // Gates only on leadStatsLoaded — SourceQuality (which used to gate a second
  // stage here via sourceQualityLoaded) was replaced by SourceQualityOverall,
  // which manages its own loading independently (see Step 5 below) and never
  // sets that flag, so the old second branch left this permanently stuck at
  // `true` for any non-leaf-role user once leadStatsLoaded flipped.
  if (filtersReady && !leadStatsLoaded) {
    loading = true;
  }

  const resetLaunchList = () => {
    form.resetFields(['launch_list']);
    dispatch(setDashboardFilter({ launch_id: null }));
  };

  const fetchProjectsList = (): void => {
    dispatch(fetchFilterLaunchList(dashboardFilter));
  };

  const handleProgressive = (values: string) => {
    dispatch(setDashboardFilter(values));
  };

  useEffect(() => {
    return () => {
      dispatch(resetDashboardFilter(dashboardFilter));
    };
  }, []);

  if (data?.user?.first_login !== 1 && data?.user?.role?.id === getRoleByName('human_resources')?.id) {
    return route.push('/employees');
  }

  let showCombineView = data?.user?.role?.id === getRoleByName('team_lead')?.id || data?.user?.role?.id === getRoleByName('field_sales')?.id || data?.user?.role?.id === getRoleByName('pre_sales')?.id;
  return (
    <>
      <div className="dashboard">
        {/* <EnvironmentBanner /> */}
        <PageHeader
          isBack={false}
          title="Dashboard Statistics"
          headerClass="dashboard-page-header"
          extra={
            <div className="dashboard-page-header-right">
              {!isLeafRole(data?.user?.role?.id ?? 0) ? (
                  <DashboardProgressiveDropdownsTest
                    onUpdateFilters={(value: any) => handleProgressive(value)}
                    onApply={(progressiveChanged) => {
                          setFiltersReady(true);
                      if (progressiveChanged) {
                        setLeadStatsLoaded(false);
                      }
                    }}
                    loading={loading}
                    resetLaunchList={resetLaunchList}
                    viewData={form.getFieldValue('veiw_data')}
                    showCombineView= {showCombineView}
                    forceEnableApply={!filtersReady}  // NEW
                    onSelectionChainChange={(chain) => {
                      const lastSelected = chain[chain.length - 1];
                      setSelectedUserName(lastSelected ? `${lastSelected.first_name} ${lastSelected.last_name}`.trim() : null);
                    }}
                  />
                ) : (
                  <div className="page-header-left-extra"></div>
                )}
              <Form
                form={form}
                initialValues={{ launch_list: null }}
              >
                <InputSelect
                  options={launchListOptions}
                  style={{ width: 200 }}
                  className="project-list-select"
                  name="launch_list"
                  placeholder="Launch List"
                  isSearchable
                  onSelect={(value) => {
                    form.setFieldsValue({ launch_list: value });
                    dispatch(setDashboardFilter({ launch_id: value }));
                  }}
                  onClear={() => {
                    form.resetFields(['launch_list']);
                    dispatch(setDashboardFilter({ launch_id: null }));
                  }}
                  disabled={loading}
                />
              </Form>
            </div>
          }
        />
        <Spin spinning={filtersReady && (!leadStatsLoaded || statisticsStatus === 'loading')}>
          {/* Step 1: LeadsStatistics - always render, loading only if not loaded yet */}
          <LeadsStatistics
            loading={!leadStatsLoaded && statisticsStatus === 'loading'}
            onLoaded={() => setLeadStatsLoaded(true)}
            filtersReady={filtersReady}
          />
        </Spin>
          {/* Step 2: WeekStatistics - render after LeadsStatistics loaded */}
          {leadStatsLoaded && (
          // <Spin spinning={!weekStatsLoaded || weekStatisticsStatus === 'loading'}>
              <WeekStatistics
                loading={!weekStatsLoaded && weekStatisticsStatus === 'loading'}
                onLoaded={() => setWeekStatsLoaded(true)}
              />
          // </Spin>
          )}
          {/* Step 3: SourceQuality - temporarily disabled */}
          {/* {leadStatsLoaded && !isLeafRole(data?.user?.role?.id ?? 0) && (
            <Spin spinning={!sourceQualityLoaded || (data?.user?.role?.id === getRoleByName('team_lead')?.id ? sourceQualityTeamLeadStatus === 'loading' : dashboardSourceQualityStatus === 'loading')}>
              <SourceQuality
                roles={{
                  roleId: data?.user?.role?.id,
                  defaultRoles: allRoles,
                }}
                onLoaded={() => setSourceQualityLoaded(true)}
                />
            </Spin>
          )} */}
          {/* Step 4: SourceEfficiency - temporarily disabled */}
          {/* {leadStatsLoaded && sourceQualityLoaded && !isLeafRole(data?.user?.role?.id ?? 0) && (
            <SourceEfficiency
              roles={{
                roleId: data?.user?.role?.id,
                defaultRoles: allRoles,
              }}
            />
          )} */}
          {/* Step 5: SourceQualityOverall - aggregate bar chart by source; manages its own loading/date filter independently */}
          {leadStatsLoaded && !isLeafRole(data?.user?.role?.id ?? 0) && (
            <SourceQualityOverall selectedUserName={selectedUserName} />
          )}
      </div>
    </>
  );
};

export default DashboardPage;