import timezones from "@/utils/timezones.json";
import { Flex, Grid, NumberInput, Select, Text } from "@mantine/core";
import { DatePickerInput, TimePicker } from "@mantine/dates";
import "@mantine/dates/styles.css";
import { type UseFormReturnType } from "@mantine/form";
import { IconChevronDown } from "@tabler/icons-react";
import StepContentWrapper from "../stepContentWrapper";
import StepperNavigation from "../stepperNavigation";
import type { ScheduleFormType } from "./types";

const ScheduleForm: React.FC<{
  activeStep: number;
  setActiveStep: React.Dispatch<React.SetStateAction<number>>;
  form: UseFormReturnType<
    ScheduleFormType,
    (values: ScheduleFormType) => ScheduleFormType
  >;
  audienceCount: number | null;
}> = ({ activeStep, setActiveStep, form, audienceCount }) => {
  const handleSubmit = (data: ScheduleFormType) => {
    setActiveStep((current) => (current < 4 ? current + 1 : current));
  };

  const clearTargetForm = () => {
    form.reset();
  };

  const handleNotificationTypeChange = (value: string | null) => {
    form.reset();
    form.setValues({
      notificationType: value as "Now" | "Scheduled" | "Daily",
    });
  };

  const notificationTypeValue = () => form.values.notificationType;

  // Calculate batch info
  const batchSize = form.values.batchSize || 750;
  const totalRecipients = audienceCount || 0;
  const totalBatches = Math.ceil(totalRecipients / batchSize);
  const isEstimated = audienceCount === null;

  return (
    <StepContentWrapper
      title="Step 3 - Scheduling"
      onClearClick={clearTargetForm}
    >
      <form
        onSubmit={form.onSubmit(handleSubmit)}
        style={{
          flex: 1,
          display: "flex",
          flexDirection: "column",
          justifyContent: "space-between",
          gap: "32px"
        }}
      >
        <Grid gutter={"lg"}>
          <Grid.Col span={6}>
            <Select
              data={["Now", "Scheduled", "Daily"]}
              label="Notification Type"
              labelProps={{ fz: 13, mb: 5 }}
              rightSection={<IconChevronDown height={18} width={18} />}
              rightSectionProps={{
                style: {
                  borderLeft: "1px solid var(--mantine-color-grey-12)",
                  marginBlock: "6px",
                },
              }}
              w={"100%"}
              key={form.key("notificationType")}
              {...form.getInputProps("notificationType")}
              onChange={handleNotificationTypeChange}
            />
          </Grid.Col>
          <Grid.Col span={6}>
            <NumberInput
              label="Batch Size (Max 750)"
              labelProps={{ fz: 13, mb: 5 }}
              min={1}
              max={750}
              w={"100%"}
              key={form.key("batchSize")}
              {...form.getInputProps("batchSize")}
            />
            {totalRecipients > 0 && (
              <Text size="sm" c="dimmed" mt={5}>
                Total recipients: <b>{totalRecipients.toLocaleString()}</b>.
                This will be sent in <b>{totalBatches}</b> batch{totalBatches > 1 ? 'es' : ''} of <b>{batchSize}</b> message{batchSize > 1 ? 's' : ''} each.
              </Text>
            )}
            {isEstimated && (
              <Text size="xs" c="dimmed" mt={5}>
                * Batch calculation based on estimated audience from Step 2.
              </Text>
            )}
          </Grid.Col>
          {notificationTypeValue() !== "Now" && (
            <>
              {notificationTypeValue() === "Scheduled" && (
                <Grid.Col span={6}>
                  <DatePickerInput
                    label="Schedule Date"
                    fz={14}
                    labelProps={{ fz: 13, mb: 5 }}
                    rightSection={<IconChevronDown height={18} width={18} />}
                    rightSectionProps={{
                      style: {
                        borderLeft: "1px solid var(--mantine-color-grey-12)",
                        marginBlock: "6px",
                      },
                    }}
                    minDate={new Date()}
                    key={form.key("scheduleDate")}
                    {...form.getInputProps("scheduleDate")}
                  />
                </Grid.Col>
              )}
              <Grid.Col span={6}>
                <TimePicker
                  label="Schedule Time"
                  fz={14}
                  labelProps={{ fz: 13, mb: 5 }}
                  rightSection={<IconChevronDown height={18} width={18} />}
                  rightSectionProps={{
                    style: {
                      borderLeft: "1px solid var(--mantine-color-grey-12)",
                      marginBlock: "6px",
                    },
                  }}
                  withDropdown
                  format="12h"
                  pointer
                  key={form.key("scheduleTime")}
                  {...form.getInputProps("scheduleTime")}
                />
              </Grid.Col>
              <Grid.Col span={notificationTypeValue() === "Daily" ? 6 : 12}>
                <Select
                  data={timezones}
                  label="Time Zone"
                  labelProps={{ fz: 13, mb: 5 }}
                  rightSection={<IconChevronDown height={18} width={18} />}
                  rightSectionProps={{
                    style: {
                      borderLeft: "1px solid var(--mantine-color-grey-12)",
                      marginBlock: "6px",
                    },
                  }}
                  searchable
                  key={form.key("timeZone")}
                  {...form.getInputProps("timeZone")}
                />
              </Grid.Col>
              {notificationTypeValue() === "Daily" && (
                <>
                  <Grid.Col span={12}>
                    <Flex align={"center"} gap={10}>
                      <Text fz={13} fw={400}>
                        Send no more than one message every
                      </Text>
                      <NumberInput
                        radius={4}
                        w={42}
                        hideControls
                        min={1}
                        allowDecimal={false}
                        key={form.key("notificationInterval")}
                        {...form.getInputProps("notificationInterval")}
                      />
                      <Text fz={13} fw={400}>
                        days
                      </Text>
                    </Flex>
                  </Grid.Col>
                  <Grid.Col span={6}>
                    <DatePickerInput
                      label="Start Date"
                      fz={14}
                      labelProps={{ fz: 13, mb: 5 }}
                      rightSection={<IconChevronDown height={18} width={18} />}
                      rightSectionProps={{
                        style: {
                          borderLeft: "1px solid var(--mantine-color-grey-12)",
                          marginBlock: "6px",
                        },
                      }}
                      minDate={new Date()}
                      key={form.key("startDate")}
                      {...form.getInputProps("startDate")}
                    />
                  </Grid.Col>
                  <Grid.Col span={6}>
                    <DatePickerInput
                      label="End Date"
                      fz={14}
                      labelProps={{ fz: 13, mb: 5 }}
                      rightSection={<IconChevronDown height={18} width={18} />}
                      rightSectionProps={{
                        style: {
                          borderLeft: "1px solid var(--mantine-color-grey-12)",
                          marginBlock: "6px",
                        },
                      }}
                      minDate={new Date()}
                      key={form.key("endDate")}
                      {...form.getInputProps("endDate")}
                    />
                  </Grid.Col>
                </>
              )}
            </>
          )}
        </Grid>
        <Flex justify={"end"}>
          <StepperNavigation
            activeStep={activeStep}
            setActiveStep={setActiveStep}
          />
        </Flex>
      </form>
    </StepContentWrapper>
  );
};

export default ScheduleForm;
