import InputSelect from '@/components/form/InputSelect';
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  fetchUserAllLeadDropdown,
  fetchUserClusterAllLeadDropdown,
  fetchUserPreSalesAllLeadDropdown,
  fetchUserTeamLeadAllLeadDropdown,
} from '../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: any
    first_name: string
    last_name: string
    role_label: string
    value: number
    label: string
    cities: string
    role: string
}

interface ProgressiveDropdownsProps {
    onUpdateFilters: (filterUpdates: Partial<filterI>) => void
    hideNextLevel?: boolean
    status: boolean
    resetLaunchList: () => void
}

const ProgressiveDropdowns: React.FC<ProgressiveDropdownsProps> = ({ onUpdateFilters, hideNextLevel = false, status, 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();
  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);
  const [cityHead, setCityHead] = useState<any>(null);
  const [clusterManager, setClusterManager] = useState<any>(null);
  const [teamHead, setTeamHead] = useState<any>(null);
  const [preSales, setPreSales] = useState<any>(null);
  const veiw_data = useWatch('veiw_data', form);

  const { data: session } = useSession();
  const user = session?.user;
  // Fetch initial data on component mount
  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);
  };

  // Options for static sales views
  const salesStaticOptions = [
    { value: 'self_view', label: 'Self View' },
    { value: 'partner_view', label: 'Partner View' },
    { value: 'combine_view', label: 'Combine View' },
  ];

  // Map city list options
  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,
  }));

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

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

  // Map pre-sales list options
  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,
  }));

  // Handle city head change event
  const handleCityHeadChange = (event: any) => {
    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_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);
  };

  // Handle cluster manager change event
  const handleClusterManagerChange = (event: any) => {
    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: 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);
  };

  // Handle team lead change event
  const handleTeamHeadChange = (event: any) => {
    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();
  };

  // Handle pre-sales change event
  const handlePreSalesChange = (event: any) => {
    const sales = preSalesListOptions?.find((team: valueI) => team?.value === event);
    if (sales) {
      updateFilters({
        lead_user_city_id: undefined,
        lead_user_role_name: sales.role === 'team_lead' ? 'field_sales' : 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(fetchUserAllLeadDropdown({ filters: obj }));
  };
  // cluster manager API dispatch
  const fetchClusterDropdownList = (filters: filterI, cityId: number) => {
    const obj = {
      ...filters,
      tab_key: 'cluster_manager',
      city_id: cityId,
    };
    dispatch(fetchUserClusterAllLeadDropdown({ 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(fetchUserTeamLeadAllLeadDropdown({ 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(fetchUserPreSalesAllLeadDropdown({ 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={status === true}
        />
      )}
      {(!hideNextLevel && cityHead) || config.currentUserRole === getRoleByName('city_head')?.id ? (
        <InputSelect
          options={clusterListOptions}
          style={{ width: '200px' }}
          name="cluster_manager"
          placeholder="Cluster Manager"
          isSearchable
          onSelect={(value) => {
            // setFilters({ ...filters, reporting_manager_id: value })
            handleClusterManagerChange(value);
            setClusterManager(value);
          }}
          onClear={() => {
            setClusterManager(null), setTeamHead(null), setPreSales(null), resetLaunchList();
          }}
          disabled={status === true}
        />
      ) : (
        ''
      )}
      {(!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={status === true}
        />
      ) : (
        ''
      )}
      {(!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 || status == true}
        />
      ) : (
        ''
      )}
      {}
      {!hideNextLevel && getRoleByName('team_lead') && !isChildRole(getRoleByName('team_lead')!.id) ? (
          <InputSelect
            name="veiw_data"
            placeholder="View"
            options={salesStaticOptions}
            disabled={preSales || status == true}
            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 ProgressiveDropdowns;
