import React, { useEffect } from 'react';
import OrderActionModal from '../../../common/modals/order-action-modal/OrderActionModal';
import AssigneeDropdown from './AssigneeDropdown';
import { useCurrentAction } from '../store';
import { DatePickerWrap } from '../order-actions/actions/modalstyle';
import {
  ReferenceContainer,
  InnerContainer,
  ContentsContainer,
  Left,
  DateTimeContainer,
  Row,
  DetailedContainer,
  MiniContainer,
} from './reminder-styles';
import {
  useReminderRefId,
  useReminderById,
  useUpdateReminderData,
  useReminderNotiData,
} from '../order-actions/store';
import StatusIndicator from '../flags-action-modal/StatusIndicator';
import styled from 'styled-components';
// import { isValid } from 'date-fns';
import { DatePicker, notification } from 'antd';
import dayjs from 'dayjs';
import { ApiResponse } from '../types';
import { Label, useAxios } from '@bjsdistribution/dms-component-library';
import { useReminderData } from '../../store';

export interface IProps {
  callReminderApi: any;
}

const ViewReminderModal = (props: IProps) => {
  const [, setCurrentAction] = useCurrentAction();
  const [reminderDataById, setReminderByIdData] = useReminderById();
  const [reminderPayload, setReminderPayload] = useUpdateReminderData();
  const [reminderRefId] = useReminderRefId();
  const [, setReminderUpdatedData] = useReminderNotiData();
  const [, setReminderData] = useReminderData();

  const {
    data: fetchedReminderInitialData,
    fetchData: callReminderApiInitial,
    loading,
  } = useAxios<{
    data: any;
  }>({
    endpoint: `/v1/task/reminder/${reminderRefId}`,
    method: 'GET',
    pagination: { is_pagination: false },
    // filters: [{ field: 'order_id', op: '=', value: reminderRefId }],
  });

  useEffect(() => {
    if (fetchedReminderInitialData && fetchedReminderInitialData?.data) {
      const data = fetchedReminderInitialData?.data[0];
      setReminderByIdData(data);
      setReminderPayload(data);
    }
  }, [fetchedReminderInitialData, loading]);

  useEffect(() => {
    if (reminderRefId) {
      callReminderApiInitial();
    }
  }, [reminderRefId]);

  const handleDateChange = (date: any | null) => {
    if (date && date.isValid()) {
      const selectedDate = date.toISOString();

      setReminderPayload({
        ...reminderPayload,
        due_datetime: selectedDate,
      });
    } else {
    }
  };

  const { fetchData: callReminderEditAPI } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/v1/task/reminder/update/`,
    method: 'PUT',
  });

  const closeModal = () => {
    setCurrentAction(undefined);
  };

  const onChangeDetails = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    const newDescription = event.target.value;

    setReminderPayload({
      ...reminderPayload,
      description: newDescription,
    });
  };

  const handleStatusChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const isChecked = event.target.checked;
    setReminderPayload({
      ...reminderPayload,
      status: isChecked,
    });
  };

  const handleEditReminder = async () => {
    try {
      if (reminderDataById?.status === true) {
        notification.info({
          message: 'Info',
          description:
            'This flag has been set as resolved - changes are no longer permitted.',
        });
        return;
      }

      // Destructure to remove unwanted fields
      const {
        is_deleted,
        legacy_reminder_id,
        order_data,
        priority,
        reference,
        completed_at,
        completed_by,
        ...cleanedPayload
      } = reminderPayload;

      cleanedPayload.id = reminderRefId;
      cleanedPayload.order_id = reminderDataById?.order_id;

      const apiResponse = (await callReminderEditAPI({
        payload: [cleanedPayload],
      })) as {
        code: number | null;
        error?: string | null | undefined;
        data?: any;
        [key: string]: any;
      };

      if (apiResponse?.code === 200) {
        if (apiResponse && apiResponse?.data) {
          setReminderUpdatedData(apiResponse?.data);
          setReminderData(apiResponse?.data);
          props?.callReminderApi();
        }

        closeModal();
        notification.success({
          message: 'Success',
          description: apiResponse.message,
        });
      } else {
        notification.error({
          message: 'Failure',
          description:
            apiResponse?.error ||
            'An error occurred while updating the reminder.',
        });
      }
    } catch (error) {
      const err = error as any;
      const errMsg =
        err?.response?.data?.error ||
        err?.response?.data?.message ||
        err?.message ||
        'An unexpected error occurred.';

      notification.error({
        message: 'Request Failed',
        description: errMsg,
      });
    }
  };

  const hasReminderChanged = () => {
    if (!reminderDataById || !reminderPayload) return false;

    const original = {
      due_datetime: reminderDataById?.due_datetime,
      assigned_to: reminderDataById?.assigned_to,
      description: reminderDataById?.description?.trim(),
      department: reminderDataById?.department,
      status: reminderDataById?.status,
    };

    const updated = {
      due_datetime: reminderPayload?.due_datetime,
      assigned_to: reminderPayload?.assigned_to,
      description: reminderPayload?.description?.trim(),
      department: reminderPayload?.department,
      status: reminderPayload?.status,
    };

    const baseChanged =
      original?.due_datetime !== updated?.due_datetime ||
      original?.assigned_to !== updated?.assigned_to ||
      original?.description !== updated?.description ||
      original?.status !== updated?.status;

    const shouldCompareDept =
      original.department !== undefined && updated?.department !== undefined;

    const departmentChanged = shouldCompareDept
      ? original.department !== updated?.department
      : false;

    return baseChanged || departmentChanged;
  };

  const isDisabled =
    !reminderPayload?.assigned_to?.length ||
    !reminderPayload?.description?.trim() ||
    !reminderPayload?.due_datetime ||
    !hasReminderChanged() ||
    reminderDataById?.status === true;

  const additional =
    reminderDataById?.order_data?.order_recipient?.recipient_name +
    ' ' +
    reminderDataById?.order_data?.order_recipient?.postcode;

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

  return (
    <>
      {reminderDataById && (
        <OrderActionModal
          headerTitle="View Reminder"
          onCloseHeader={closeModal}
          onSubmit={handleEditReminder}
          submitBtnTitle="Save Details"
          infoText={additional || 'NA'}
          isSubmitDisabled={isDisabled || disabled}
          headerActions={
            <OuterDiv>
              {reminderDataById?.status === false && (
                <StyledWrapper>
                  <StyledLabel>
                    <StyledCheckbox>
                      <input
                        type="checkbox"
                        onChange={handleStatusChange}
                        checked={reminderPayload?.status || false}
                        disabled={disabled}
                      />
                      <RoundCheckbox />
                    </StyledCheckbox>
                    <StyledSpan>Mark As Complete</StyledSpan>
                  </StyledLabel>
                </StyledWrapper>
              )}
            </OuterDiv>
          }
        >
          <ReferenceContainer>
            <InnerContainer>
              <MiniContainer>
                <Label label="Reference" required />
                <LabelText>{reminderDataById?.reference || 'N/A'}</LabelText>
              </MiniContainer>
              <MiniContainer>
                <Label label="Status" />
                <LabelText>
                  {reminderDataById?.status === false ? (
                    <StatusIndicator text="Incomplete" status="AD" />
                  ) : (
                    <StatusIndicator
                      text={`Completed on ${reminderDataById?.completed_at} by ${reminderDataById?.completed_by}`}
                      status="SD"
                    />
                  )}
                </LabelText>
              </MiniContainer>
            </InnerContainer>
          </ReferenceContainer>

          <ContentsContainer>
            <Left>
              <AssigneeDropdown />
              <DateTimeContainer>
                <Label label="Due Date & Time" required />
                <Row>
                  <StyleContainer>
                    <DatePickerWrap>
                      <DatePicker
                        format="DD/MM/YYYY HH:mm A"
                        value={
                          reminderPayload?.due_datetime
                            ? dayjs(reminderPayload?.due_datetime)
                            : reminderDataById?.due_datetime
                            ? dayjs(reminderDataById?.due_datetime)
                            : null
                        }
                        onChange={handleDateChange}
                        placeholder="Select Date & Time"
                        showTime={{ defaultValue: dayjs('00:00', 'HH:mm') }}
                        disabledDate={current =>
                          current && current < dayjs().startOf('day')
                        }
                        disabledTime={date => getDisabledTime(date)}
                        disabled={disabled}
                      />
                    </DatePickerWrap>
                  </StyleContainer>
                </Row>
              </DateTimeContainer>
            </Left>

            <Right>
              <Label label="Details" required />
              <DetailedContainer
                placeholder="Enter Description..."
                name="text"
                required
                value={
                  reminderPayload?.description ||
                  reminderDataById?.description ||
                  ''
                }
                disabled={disabled}
                onChange={onChangeDetails}
              ></DetailedContainer>
            </Right>
          </ContentsContainer>
        </OrderActionModal>
      )}
    </>
  );
};

const getDisabledTime = (date: any) => {
  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: number) => {
        if (selectedHour === currentHour) {
          return Array.from({ length: 60 }, (_, i) => i).filter(
            minute => minute < currentMinute
          );
        }
        return [];
      },
    };
  }
  return {};
};

export const Right = styled.div`
  display: flex;
  height: 100%;
  gap: 15px;
  flex-direction: column;
  padding: 10px;
`;
const StyleContainer = styled.div`
  border-radius: 20px;
  background: #fff;
  width: 235px;
`;

const StyledWrapper = styled.div`
  display: flex;
  padding: 6px 10px;
  align-items: center;
  gap: 5px;
  border-radius: 30px;
  background: #fff;
`;

const StyledLabel = styled.label`
  cursor: pointer;
  display: flex;
`;

const StyledSpan = styled.span`
  color: #131313;
  font-family: 'Lato', sans-serif;
  font-style: normal;
  font-weight: normal;
  font-size: 14px;
  line-height: 17px;
  white-space: nowrap;
`;

const StyledCheckbox = styled.div`
  input[type='checkbox'] {
    display: none;
  }

  input[type='checkbox'] + span:before {
    width: 14px;
    height: 14px;
    border: 1.5px solid #3a3630;
    content: '';
    display: inline-block;
    margin: 0 8px 0 0;
    padding: 0;
    border-radius: 50%;
  }

  input[type='checkbox']:checked + span:before {
    background: #feba30;
    border: 1.5px solid #3a3630;
    box-shadow: inset 0px 0px 0px 1px #fff;
    color: #333;
    content: '';
    text-align: center;
    border-radius: 50%;
    display: flex;
    width: 14px;
    height: 14px;
  }

  input[type='checkbox']:focus + span::before {
    outline: 0;
  }
`;

const OuterDiv = styled.div`
  padding-left: 33%;
`;

const RoundCheckbox = styled.span``;

const LabelText = styled.span`
  color: var(--primary-dark-brown, #3a3630);
  font-family: Lato;
  font-size: 13px;
  font-style: normal;
  font-weight: 400;
  line-height: 16px;
`;

export default ViewReminderModal;
