import InputSelect from '@/components/form/InputSelect';
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchUserClusterDropdown, fetchUserDropdown, fetchUserPreSalesDropdown, fetchUserTeamLeadDropdown } from '@/app/enquiries/slice';
import type { RootState, AppDispatch } from '@/store/store';
import { useSession } from 'next-auth/react';
import { Form } from 'antd';
import { useWatch } from 'antd/es/form/Form';
import { useRoles } from '@/hooks/useRoles';
interface filterI {
    search: string
    tab_key: string
    city_id: string
    reporting_manager_id: string | number
    lead_user_city_id?: number | null
    lead_user_role_name?: string
    lead_user_id?: number | null
    veiw_data: string | number
}

interface valueI {
    id: number
    user_cities: { city_id: number; city_name: string }[];
    first_name: string
    last_name: string
    role_label: string
    value: number
    label: string
    cities: string
    role: string
}

interface DashboardProgressiveDropdownsProps {
    onUpdateFilters: (filterUpdates: Partial<filterI>) => void
    hideNextLevel?: boolean
    loading: boolean | undefined
    resetLaunchList: () => void
}

const DashboardProgressiveDropdowns: React.FC<DashboardProgressiveDropdownsProps> = ({ onUpdateFilters, hideNextLevel = false, loading, resetLaunchList }) => {
  const [form] = Form.useForm();
  const { config, isChildRole, getRoleByName } = useRoles();
  const filters = {
    search: '',
    tab_key: '',
    city_id: '',
    reporting_manager_id: '',
    veiw_data: '',
  };
  const dispatch: AppDispatch = useDispatch();

  // Retrieve data from Redux store
  const userList = useSelector((state: RootState) => state.allLeads.dropdownList);
  const clusterList = useSelector((state: RootState) => state.allLeads.clusterManList);
  const teamLeadList = useSelector((state: RootState) => state.allLeads.teamLeadList);
  const preSalesList = useSelector((state: RootState) => state.allLeads.preSalesList);
  // Define states for selected dropdown values
  const [cityHead, setCityHead] = useState<number | null>(null);
  const [clusterManager, setClusterManager] = useState<number | null>(null);
  const [teamHead, setTeamHead] = useState<number | null>(null);
  const [preSales, setPreSales] = useState(null);
  const veiw_data = useWatch('veiw_data', form);

  const { data: session } = useSession();
  const user = session?.user;

  useEffect(() => {
    fetchUsersDropdownList(filters);
    if (config.currentUserRole === getRoleByName('city_head')?.id) {
      fetchClusterDropdownList(filters, user?.cities?.[0]?.city_id ?? 0);
    }
    if (config.currentUserRole === getRoleByName('cluster_manager')?.id) {
      fetchTeamLeadDropdownList(filters, user?.cities?.[0]?.city_id ?? 0);
    }
    if (config.currentUserRole === getRoleByName('team_lead')?.id) {
      fetchSalesDropdownList(filters, user?.cities?.[0]?.city_id ?? 0);
    }
  }, []);


  const updateFilters = (newFilters: Partial<filterI>) => {
    onUpdateFilters(newFilters);
    resetLaunchList();
  };

  const salesStaticOptions = [
    { value: 'self_view', label: 'Self View' },
    { value: 'partner_view', label: 'Partner View' },
    { value: 'combine_view', label: 'Combine View' },
  ];

  // Map dropdown options from fetched data
  const cityListOptions = userList?.map((user: valueI) => ({
    value: user.id,
    label: `${user?.first_name} ${user?.last_name} (${user?.role_label}) - ${user?.user_cities[0]?.city_name}`,
    cities: user?.user_cities,
  }));

  const clusterListOptions = clusterList?.map((clust: valueI) => ({
    value: clust.id,
    label: `${clust.first_name} ${clust?.last_name} (${clust.role_label})`,
    cities: clust?.user_cities,
  }));

  const teamLeadListOptions = teamLeadList?.map((team: valueI) => ({
    value: team.id,
    label: `${team.first_name} ${team.last_name} (${team.role_label})`,
    cities: team?.user_cities,
  }));

  const preSalesListOptions = preSalesList?.map((pre: valueI) => ({
    value: pre.id,
    label: `${pre.first_name} ${pre.last_name} (${pre.role_label})`,
    cities: pre?.user_cities,
    role: pre?.role,
  }));

  const handleCityHeadChange = (event: number) => {
    const userCities = cityListOptions?.find((city: valueI) => city?.value === event);
    fetchClusterDropdownList(filters, userCities?.cities[0]?.city_id);
    if (userCities) {
      updateFilters({
        lead_user_city_id: userCities?.cities[0]?.city_id || null,
        lead_user_id: userCities?.value || null,
        lead_user_role_name: 'city_head',
      });
    } else {
      updateFilters({ lead_user_city_id: null, lead_user_role_name: '', lead_user_id: null });
    }
    setClusterManager(null);
    form.setFieldValue('cluster_manager', null);
    resetLaunchList();
    setTeamHead(null);
    setPreSales(null);
  };

  const handleClusterManagerChange = (event: number) => {
    const clusterCities = clusterListOptions?.find(
      (cluster: valueI) => cluster?.value === event
    );
    fetchTeamLeadDropdownList(filters, clusterCities);
    if (clusterCities) {
      updateFilters({
        lead_user_city_id: undefined,
        lead_user_role_name: 'cluster_manager',
        lead_user_id: clusterCities.value || null,
      });
    } else {
      const userCities = cityListOptions?.find((city: valueI) => city?.value === cityHead);
      if (userCities) {
        updateFilters({
          lead_user_city_id: userCities?.cities[0]?.city_id || null,
          lead_user_role_name: 'city_head',
          lead_user_id: userCities?.value || null,
        });
      } else {
        updateFilters({
          lead_user_city_id: undefined,
          lead_user_role_name: undefined,
          lead_user_id: null,
        });
      }
    }
    setTeamHead(null);
    form.setFieldValue('team_lead', null);
    resetLaunchList();
    setPreSales(null);
  };

  const handleTeamHeadChange = (event: number) => {
    const teamCities = teamLeadListOptions?.find((team: valueI) => team?.value === event);
    fetchSalesDropdownList(filters, teamCities);
    if (teamCities) {
      updateFilters({
        lead_user_city_id: undefined,
        lead_user_role_name: 'team_lead',
        lead_user_id: teamCities.value || null,
      });
    } else {
      const clusterCities = clusterListOptions?.find(
        (cluster: valueI) => cluster?.value === clusterManager
      );
      if (clusterCities) {
        updateFilters({
          lead_user_city_id: undefined,
          lead_user_role_name: 'cluster_manager',
          lead_user_id: clusterCities.value || null,
        });
      } else {
        updateFilters({
          lead_user_city_id: undefined,
          lead_user_role_name: undefined,
          lead_user_id: null,
        });
      }
    }
    setPreSales(null);
    form.setFieldValue('sales', null);
    resetLaunchList();
  };

  const handlePreSalesChange = (event: number) => {
    const sales = preSalesListOptions?.find((team: valueI) => team?.value === event);
    if (sales) {
      updateFilters({
        lead_user_city_id: undefined,
        lead_user_role_name: sales.role,
        lead_user_id: sales.value || null,
      });
    } else {
      const teamCities = teamLeadListOptions?.find((team: valueI) => team?.value === teamHead);
      if (teamCities) {
        updateFilters({
          lead_user_city_id: undefined,
          lead_user_role_name: 'team_lead',
          lead_user_id: teamCities.value || null,
        });
      } else {
        updateFilters({
          lead_user_city_id: undefined,
          lead_user_role_name: undefined,
          lead_user_id: null,
        });
      }
    }
    resetLaunchList();
  };

  // city head API dispatch
  const fetchUsersDropdownList = (filters: filterI) => {
    const obj = {
      ...filters,
      tab_key: 'city_head',
    };
    dispatch(fetchUserDropdown({ filters: obj }));
  };
  // cluster manager API dispatch
  const fetchClusterDropdownList = (filters: filterI, cityId: number) => {
    const obj = {
      ...filters,
      tab_key: 'cluster_manager',
      city_id: cityId,
    };
    dispatch(fetchUserClusterDropdown({ filters: obj }));
  };
  // team lead API dispatch
  const fetchTeamLeadDropdownList = (filters: filterI, city: any) => {
    const isCurrentUserClusterManager = config.currentUserRole === getRoleByName('cluster_manager')?.id;
    const obj = {
      ...filters,
      tab_key: 'team_lead',
      city_id: isCurrentUserClusterManager
        ? user?.cities?.[0]?.city_id
        : city?.cities?.[0]?.city_id,
      reporting_manager_id: isCurrentUserClusterManager ? user?.id : city?.value,
    };
    dispatch(fetchUserTeamLeadDropdown({ filters: obj }));
  };

  const fetchSalesDropdownList = (filters: filterI, city: any) => {
    const isCurrentUserTeamLead = config.currentUserRole === getRoleByName('team_lead')?.id;
    const obj = {
      ...filters,
      tab_key: 'both_sales',
      city_id: isCurrentUserTeamLead
        ? user?.cities?.[0]?.city_id
        : city?.cities?.[0]?.city_id,
      reporting_manager_id: isCurrentUserTeamLead ? user?.id : city?.value,
    };
    dispatch(fetchUserPreSalesDropdown({ filters: obj }));
  };

  return (
    <Form
      form={form}
      initialValues={{
        veiw_data: salesStaticOptions[2],
      }}
      className='page-header-left-extra'>
      {getRoleByName('city_head') && isChildRole(getRoleByName('city_head')!.id) && (
        <InputSelect
          options={cityListOptions}
          style={{ width: '200px' }}
          name="city_head"
          placeholder="City Head"
          isSearchable
          onSelect={(value) => {
            handleCityHeadChange(value);
            setCityHead(value);
          }}
          onClear={() => {
            setCityHead(null),
            setClusterManager(null),
            setTeamHead(null),
            setPreSales(null);
            resetLaunchList();
          }}
          disabled={loading}
        />
      )}
      {(!hideNextLevel && cityHead) || config.currentUserRole === getRoleByName('city_head')?.id ? (
        <InputSelect
          options={clusterListOptions}
          style={{ width: '200px' }}
          name="cluster_manager"
          placeholder="Cluster Manager"
          isSearchable
          onSelect={(value) => {
            handleClusterManagerChange(value);
            setClusterManager(value);
          }}
          onClear={() => {
            setClusterManager(null), setTeamHead(null), setPreSales(null);
            resetLaunchList();
          }}
          disabled={loading}
        />
      ) : (
        ''
      )}
      {(!hideNextLevel && clusterManager) || config.currentUserRole === getRoleByName('cluster_manager')?.id ? (
        <InputSelect
          options={teamLeadListOptions}
          style={{ width: '200px' }}
          name="team_lead"
          placeholder="Team Lead"
          isSearchable
          onSelect={(value) => {
            handleTeamHeadChange(value);
            setTeamHead(value);
          }}
          onClear={() => {
            setTeamHead(null), setPreSales(null), resetLaunchList();

          }}
          disabled={loading}
        />
      ) : (
        ''
      )}
      {(!hideNextLevel && teamHead) || config.currentUserRole === getRoleByName('team_lead')?.id ? (
        <InputSelect
          options={preSalesListOptions}
          style={{ width: '200px' }}
          name="sales"
          placeholder="Pre/Field Sales"
          isSearchable
          onSelect={(value) => {
            handlePreSalesChange(value);
            setPreSales(value);
            form.setFieldValue('veiw_data', null);
          }}
          onClear={() => {
            setPreSales(null);
            form.setFieldValue('veiw_data', null), resetLaunchList();

          }}
          disabled={veiw_data || loading}
        />
      ) : (
        ''
      )}
      {}
      {!hideNextLevel && getRoleByName('team_lead') && !isChildRole(getRoleByName('team_lead')!.id) ? (
          <InputSelect
            name="veiw_data"
            placeholder="View"
            options={salesStaticOptions}
            disabled={preSales || loading}
            defaultValue={{
              label: 'Combine View',
              value: 'combine_view',
            }}
            onSelect={(value) => {
              updateFilters({ veiw_data: value });
              form.setFieldValue('sales', null);
            }}
            style={{ width: '160px' }}
            onClear={() => {
              form.setFieldValue('sales', null);
              form.setFieldValue('veiw_data', null), resetLaunchList();
            }}
          />
        ) : (
          ''
        )}
    </Form>
  );
};

export default DashboardProgressiveDropdowns;
