import React from 'react';
import { useCreateTaskPayload, useStaticData } from '../../store';
import {
  FormRow,
  SplitContainer,
  StyledAntSelect,
  Wrapper,
} from './SharedComponents';
import RadioButtonGroup from '../../../../../common/radio-group/RadioButtonGroup';
import styled from 'styled-components';
import { isValid } from 'date-fns';
import { TextArea } from '@bjsdistribution/dms-component-library';
import { DatePicker } from 'antd';
import dayjs from 'dayjs';
import { DatePickerWrap } from '../modalstyle';
import { priorityData } from '../../utils';

function CreateTaskModal() {
  const [staticData] = useStaticData();
  const [apiPayload, setApiPayload] = useCreateTaskPayload();
  const taskTypeOptions = getTaskTypeOptions(staticData);
  const priorityOptions = getPriorityOptions(staticData);

  const handleTaskTypeChange = (value: any) => {
    const selectedType = staticData?.[0]?.order_flag_types?.find(
      (type: any) => type.id === value
    )?.type;

    setApiPayload(prev => ({
      ...prev,
      flag_type: selectedType || '',
    }));
  };

  const handlePriorityChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(e.target.value, 10);
    setApiPayload((prev: any) => ({
      ...prev,
      priority: value,
    }));
  };

  const handleDescriptionChange = (
    e: React.ChangeEvent<HTMLTextAreaElement>
  ) => {
    const val = e.target.value;
    setApiPayload(prev => ({
      ...prev,
      description: val,
    }));
  };

  const handleDateChange = (date: any | null) => {
    if (date && isValid(date.$d)) {
      const formatted = date.$d.toISOString();
      setApiPayload(prev => ({
        ...prev,
        due_datetime: formatted,
      }));
    } else {
      setApiPayload(prev => ({
        ...prev,
        due_datetime: '',
      }));
    }
  };
  return (
    <Wrapper>
      <SplitContainer>
        <FormRow label="Task Type" required>
          <StyledAntSelect
            options={taskTypeOptions}
            placeholder="Select Type"
            onChange={handleTaskTypeChange}
            value={apiPayload?.flag_type || null}
          />
        </FormRow>

        <FormRow label="Priority" required>
          <RadioButtonGroup
            heading=""
            options={priorityOptions || []}
            onChange={handlePriorityChange}
            direction="horizontal"
            selectedValue={apiPayload?.priority || 3}
            required={false}
          />
        </FormRow>

        <FormRow label="Due Date & Time" required>
          <StyleContainer>
            <DatePickerWrap>
              <DatePicker
                format="DD/MM/YYYY HH:mm A"
                value={
                  apiPayload?.due_datetime
                    ? dayjs(apiPayload?.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)}
              />
            </DatePickerWrap>
          </StyleContainer>
        </FormRow>
      </SplitContainer>

      <SplitContainer>
        <Label>
          Description
          <span style={{ color: 'red', fontSize: '20px' }}> * </span>
        </Label>
        <StyledTextArea
          placeholder="Add Description"
          required
          onChange={handleDescriptionChange}
          value={apiPayload?.description || ''}
        />
      </SplitContainer>
    </Wrapper>
  );
}

const getTaskTypeOptions = (staticData: any) => {
  return (
    staticData?.[0]?.order_flag_types?.map((item: any) => ({
      label: item?.type,
      value: item?.id,
    })) || []
  );
};

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 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 {};
};

const StyleContainer = styled.div`
  border-radius: 20px;
  background: #fff;
`;

const Label = styled.label`
  color: #6a7378;
  font-family: 'Lato', sans-serif;
  font-size: 14px;
  font-weight: 500;
`;

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: 25%;
`;

export default CreateTaskModal;
