import React, { useEffect, useState } from 'react';
import {
  useCreateReminderPayload,
  useDeptData,
  useStaticData,
} from '../../store';
import { priorityData } from '../../utils';
import {
  DoubleDropdownContainer,
  FormRow,
  SplitContainer,
  Wrapper,
} from './SharedComponents';
import { DatePickerWrap } from '../modalstyle';
import RadioButtonGroup from '../../../../../common/radio-group/RadioButtonGroup';
import styled from 'styled-components';
import { TextArea, useAxios } from '@bjsdistribution/dms-component-library';
import { DatePicker, notification, Select } from 'antd';
import dayjs from 'dayjs';
import { isValid } from 'date-fns';
import utc from 'dayjs/plugin/utc';
import { ApiResponse } from '../../../types';
dayjs.extend(utc);
dayjs.extend(isValid);

function CreateReminderModal() {
  const [selectedPriority, setPriority] = useState(null);
  const [reminderPayload, setReminderPayload] = useCreateReminderPayload();
  const [displayDate, setDisplayDate] = useState<Date | null>();
  const [staticData] = useStaticData();
  const [departmentData, setDepartmentData] = useDeptData();
  const [selectedDeptId, setSelectedDeptId] = useState<any | null>(null);
  const [allUsers, setAllUsers] = useState<
    {
      fName: string;
      lName: string;
      id: string;
      username: string;
      deptId: number | null;
    }[]
  >([]);
  const [, setFilteredUsers] = useState<typeof allUsers>([]);

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

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

  const getPriorityOptions = (staticData: any) => {
    return staticData?.[0]?.priorities?.map((option: any) => {
      const colorMatch = priorityData?.find(p => p.id === option.id);
      return {
        label: option.name,
        value: option.id,
        color: colorMatch?.color || '#ccc',
      };
    });
  };
  const priorityOptions = getPriorityOptions(staticData);

  //subcategory change
  const handleDepartmentChange = (value: string, option: { label: string }) => {
    setSelectedDeptId(value);
    setReminderPayload((prevState: any) => ({
      ...prevState,
      department: option?.label,
      assigned_to: null,
    }));
  };

  const handleDateChange = (date: any | null) => {
    if (date && isValid(date?.$d)) {
      const formattedDateTime = dayjs(date).toISOString();
      setDisplayDate(date?.$d?.toISOString());
      setReminderPayload((prevState: any) => ({
        ...prevState,
        due_datetime: formattedDateTime,
      }));
    } else {
      setDisplayDate(null);
      setReminderPayload((prevState: any) => ({
        ...prevState,
        due_datetime: null,
      }));
    }
  };

  //handlePriority change
  const handlePriorityChange = (event: any) => {
    const newValue = event.target.value;
    setPriority(newValue);
    setReminderPayload(prevState => ({
      ...prevState,
      priority: +newValue,
    }));
  };

  //description change
  const handleChange = (event: any) => {
    const desc = event.target.value;
    setReminderPayload(prevState => ({
      ...prevState,
      description: desc,
    }));
  };

  // sso Data get
  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,
            // userId: user?.user_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);
    } else {
      setDepartmentData([]);
    }
  }, [fetchData]);

  const userOptions = allUsers?.map((user: any) => ({
    label: `${user.fName} ${user.lName}`,
    value: user.id,
  }));

  const handleAssignToMe = () => {
    let storedUserID: string | null = null;

    const storedUserJSON = localStorage.getItem('User_iD');
    if (storedUserJSON) {
      try {
        const parsed = JSON.parse(storedUserJSON);
        storedUserID = parsed.user_id || null;
      } catch (e) {
        console.error('Failed to parse stored user ID', e);
      }
    }

    if (!storedUserID) return;
    console.log(allUsers, 'allUsersallUsersallUsers');
    const matchedUser: any = allUsers?.find(user => user?.id === storedUserID);

    console.log(storedUserID, 'storedUserID');
    console.log(matchedUser, 'matchedUser');

    const deptMatched =
      departmentData?.find((dept: any) => dept.value === matchedUser?.deptId)
        ?.label || null;

    if (!deptMatched) {
      notification.info({
        message: 'Info',
        description: `Department is not assigned to the user`,
      });
      return;
    }

    setReminderPayload((prevState: any) => ({
      ...prevState,
      assigned_to: [matchedUser?.id],
      department: deptMatched,
    }));

    matchedUser && setSelectedDeptId(matchedUser?.department_id);
  };

  return (
    <Wrapper>
      <SplitContainer>
        <FormRow label="Department" required>
          <DoubleDropdownContainer>
            <StyledAntSelect
              options={deptData}
              style={{ width: '10vw' }}
              placeholder="Select Department"
              onChange={handleDepartmentChange}
              value={reminderPayload?.department || undefined}
              showSearch
            />
          </DoubleDropdownContainer>
        </FormRow>
        <FormRow label="Assigned To" required>
          <StyledAntSelect
            options={userOptions}
            placeholder="Select User"
            onChange={handleSelectUser}
            style={{ width: 'max-content' }}
            value={reminderPayload?.assigned_to || []}
            showSearch
            mode="multiple"
            filterOption={(input: string, option?: { label: string }) =>
              option?.label.toLowerCase().includes(input.toLowerCase())
            }
          />
        </FormRow>

        <StyledLink onClick={handleAssignToMe}>Assign to me</StyledLink>

        <FormRow label="Priority" required>
          <RadioButtonGroup
            heading=""
            options={priorityOptions}
            onChange={handlePriorityChange}
            direction="horizontal"
            selectedValue={selectedPriority || 3}
            required={false}
          />
        </FormRow>
        <FormRow label="Due Date & Time" required>
          <StyleContainer>
            <DatePickerWrap>
              <DatePicker
                format="DD/MM/YYYY HH:mm A"
                value={displayDate ? dayjs(displayDate) : null}
                onChange={handleDateChange}
                placeholder="Select Date & Time"
                showTime={{ defaultValue: dayjs('00:00', 'HH:mm') }}
                disabledDate={current =>
                  current && current < dayjs().startOf('day')
                }
                disabledTime={date => {
                  if (date && date.isSame(dayjs(), 'day')) {
                    const currentHour = dayjs().hour();
                    const currentMinute = dayjs().minute();
                    return {
                      disabledHours: () =>
                        Array.from({ length: 24 }, (_, i) => i).filter(
                          hour => hour < currentHour
                        ),
                      disabledMinutes: selectedHour => {
                        if (selectedHour === currentHour) {
                          return Array.from({ length: 60 }, (_, i) => i).filter(
                            minute => minute < currentMinute
                          );
                        }
                        return [];
                      },
                    };
                  }
                  return {};
                }}
              />
            </DatePickerWrap>
          </StyleContainer>
        </FormRow>
      </SplitContainer>
      <SplitContainer>
        <Label>
          Description{' '}
          <span style={{ color: 'red', fontSize: '20px' }}> * </span>
        </Label>
        <StyledTextArea
          placeholder="Add Description"
          required
          onChange={handleChange}
        />
      </SplitContainer>
    </Wrapper>
  );
}

const StyleContainer = styled.div`
  border-radius: 20px;
  background: var(--Flowkit-White, #fff);
`;
const Label = styled.label`
  color: #6a7378;
  font-family: 'Lato', sans-serif;
  font-size: 14px;
  font-weight: 500;
`;

export const StyledAntSelect: any = styled(Select)`
  .ant-select-selector {
    width: 20vw;
    border-radius: 22px;
  }
`;

const StyledTextArea = styled(TextArea)`
  display: flex;
  padding: 12px;
  align-items: flex-start;
  gap: 4px;
  align-self: stretch;
  border-radius: 10px;
  border: 1px solid var(--Neutral-Gray-Gray-100, #e0e2e7);
  background: var(--Flowkit-White, #fff);
  resize: none;
  height: 100px;
`;

const StyledLink = styled.div`
  color: var(--contextual-blue, #6396e5);
  font-family: Lato;
  font-size: 13px;
  font-style: normal;
  font-weight: 400;
  line-height: 16px;
  cursor: pointer;
`;

export default CreateReminderModal;
