import { Label, useAxios } from '@bjsdistribution/dms-component-library';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import {
  useDeptData,
  useReminderById,
  useUpdateReminderData,
} from '../order-actions/store';
import { Select } from 'antd';
import { ApiResponse } from '../types';

function AssigneeDropdown() {
  const [reminderData] = useReminderById();
  const [reminderPayload, setReminderPayload] = useUpdateReminderData();
  const [departmentData, setDepartmentData] = useDeptData();
  const [selectedDeptId, setSelectedDeptId] = useState<any | null>(null);
  const [, setFilteredUsers] = useState<typeof allUsers>([]);
  const [allUsers, setAllUsers] = useState<
    {
      fName: string;
      lName: string;
      id: string;
      username: string;
      deptId: number | null;
      legacyId: any;
    }[]
  >([]);

  const disabled = reminderData?.status === true;

  const handleSelectChange = (value: string[]) => {
    setReminderPayload((prev: any) => ({
      ...prev,
      assigned_to: value,
    }));
  };

  // Normalize legacyId to id when reminderData is first loaded
  useEffect(() => {
    if (
      reminderData?.assigned_to &&
      typeof reminderData.assigned_to === 'string'
    ) {
      const matched = allUsers.find(
        user => user.legacyId === reminderData?.assigned_to
      );

      if (matched) {
        const id = matched?.id;
        setReminderPayload((prev: any) => ({ ...prev, assigned_to: [id] }));
      }
    }
  }, [reminderData?.assigned_to, allUsers]);

  const deptData =
    departmentData?.map((item: any) => ({
      label: item?.label,
      value: item?.value,
    })) || [];

  const handleDepartmentChange = (value: string, option: { label: string }) => {
    setSelectedDeptId(value);

    setReminderPayload((prevState: any) => ({
      ...prevState,
      department: option?.label,
      assigned_to: null,
    }));
  };

  // SSO Departments
  const { fetchData: getSSOData, data: fetchData } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/sso/departments/`,
    method: 'GET',
  });

  useEffect(() => {
    const fetchAllSSOData = async () => {
      try {
        getSSOData();
      } catch (error) {
        console.error('Error fetching SSO data:', error);
      }
    };
    fetchAllSSOData();
  }, []);

  const { fetchData: getUsersData } = useAxios<{ data: any }>({
    endpoint: `/sso/users/`,
    method: 'GET',
  });

  useEffect(() => {
    const fetchAllPages = async () => {
      try {
        let page = 0;
        let usersList: any[] = [];
        let totalPages = 1;

        while (page < totalPages) {
          const res = (await getUsersData({
            endPointQuery: `?page=${page}&limit=500`,
          })) as { data: any };

          const data = res?.data;

          if (data) {
            usersList = [...usersList, ...(data?.users || [])];
            totalPages = data.pages || 1;
            page += 1;
          } else {
            break;
          }
        }

        setAllUsers(
          usersList?.map(user => ({
            id: user?.id,
            username: user?.username,
            deptId: user?.department_id,
            fName: user?.first_names,
            lName: user?.last_name,
            legacyId: user?.legacy_id,
          }))
        );
      } catch (error) {
        console.error('Error fetching paginated SSO data:', error);
      }
    };

    fetchAllPages();
  }, []);

  useEffect(() => {
    if (selectedDeptId !== null && allUsers?.length > 0) {
      const matchedUsers = allUsers?.filter(
        user => user?.deptId?.toString() === selectedDeptId?.toString()
      );
      setFilteredUsers(matchedUsers);
    } else {
      setFilteredUsers([]);
    }
  }, [selectedDeptId, allUsers]);

  useEffect(() => {
    if (fetchData && fetchData?.data) {
      const deptList =
        fetchData?.data?.map((item: any) => ({
          label: item?.name,
          value: item?.id,
        })) || [];
      setDepartmentData(deptList);
    }
  }, [fetchData]);

  const userOptions = allUsers?.map(user => ({
    label: `${user?.fName?.trim()} ${user?.lName?.trim()}`, // shown in dropdown
    value: user?.id, // used internally and stored
  }));

  return (
    <FormContainer>
      <Label label="Department" required />
      <StyledAntSelect
        disabled={disabled}
        options={deptData}
        placeholder="Select Department"
        onChange={handleDepartmentChange}
        style={{ width: '8vw' }}
        value={reminderPayload?.department || undefined}
        showSearch
        dis
      />
      <Label label="Assigned To" required htmlFor="assigneDropdown" />
      <StyledAntSelect
        disabled={disabled}
        options={userOptions}
        placeholder="Select User"
        onChange={handleSelectChange}
        style={{ width: '100%' }}
        value={reminderPayload?.assigned_to || []}
        showSearch
        filterOption={(input: any, option: any) =>
          (option?.label as string).toLowerCase().includes(input.toLowerCase())
        }
        mode="multiple"
      />
    </FormContainer>
  );
}

const FormContainer = styled.div`
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
  width: 325px;
`;

const StyledAntSelect: any = styled(Select)``;

export default AssigneeDropdown;
