import { ActionIcon, Button, Divider, Flex, Grid, LoadingOverlay, Text, TextInput, Checkbox } from "@mantine/core";
import { type UseFormReturnType } from "@mantine/form";
import { notifications } from "@mantine/notifications";
import { IconPlus, IconTrash, IconExclamationCircleFilled } from "@tabler/icons-react";
import React, { useState } from "react";
import { createCampaign, sendCampaign } from "@/lib/features/notifications/action";
import StepContentWrapper from "../stepContentWrapper";
import StepperNavigation from "../stepperNavigation";
import { useDisclosure } from "@mantine/hooks";
import ConfirmAlert from "@/components/blocks/ConfirmAlert/confirmAlert";
import type {
  AdditionalOptionsFormType,
  NotificationFormType,
  ScheduleFormType,
  TargetFormType,
} from "./types";

const AdditionalOptionsForm: React.FC<{
  activeStep: number;
  setActiveStep: React.Dispatch<React.SetStateAction<number>>;
  form: UseFormReturnType<
    AdditionalOptionsFormType,
    (values: AdditionalOptionsFormType) => AdditionalOptionsFormType
  >;
  notificationForm: UseFormReturnType<
    NotificationFormType,
    (values: NotificationFormType) => NotificationFormType
  >;
  targetForm: UseFormReturnType<
    TargetFormType,
    (values: TargetFormType) => TargetFormType
  >;
  scheduleForm: UseFormReturnType<
    ScheduleFormType,
    (values: ScheduleFormType) => ScheduleFormType
  >;
  onSuccess?: () => void;
}> = ({
  activeStep,
  setActiveStep,
  form,
  notificationForm,
  scheduleForm,
  targetForm,
  onSuccess,
}) => {
    const [loading, setLoading] = useState(false);
    const [confirmOpened, { open: openConfirm, close: closeConfirm }] = useDisclosure(false);
    const [pendingPayload, setPendingPayload] = useState<any>(null);

    const processCampaign = async (payload: any) => {
      setLoading(true);
      try {
        const res: any = await createCampaign(payload);

        if (res.success && res.data) {
          const campaignId = res.data.id;

          if (payload.status === "IN_PROGRESS") {
            await sendCampaign(campaignId);
            notifications.show({
              title: "Success",
              message: "Campaign created and sending initiated!",
              color: "green",
            });
          } else {
            notifications.show({
              title: "Success",
              message: "Campaign scheduled successfully!",
              color: "green",
            });
          }

          // Reset all forms
          setActiveStep(0);
          notificationForm.reset();
          targetForm.reset();
          scheduleForm.reset();
          form.reset();

          onSuccess?.();

        } else {
          notifications.show({
            title: "Error",
            message: res.message || "Failed to create campaign",
            color: "red",
          });
        }
      } catch (e: any) {
        notifications.show({
          title: "Error",
          message: e.message || "An unexpected error occurred",
          color: "red",
          autoClose: 10000,
        });
      } finally {
        setLoading(false);
        closeConfirm();
      }
    };

    const handleSubmit = async (data: AdditionalOptionsFormType) => {
      const hasEmptyKey = (data.customData || []).some((item) => item.key.trim() === "");
      if (hasEmptyKey) return;

      const notif = notificationForm.getValues();
      const target = targetForm.getValues();
      const schedule = scheduleForm.getValues();
      const options = data;

      // Clean target criteria
      const cleanedTarget = {
        ...target,
        members: target.members.filter((m: string) => m.trim() !== ""),
      };

      // Calculate scheduled_at
      let scheduledAt: string | null = null;
      if (schedule.notificationType === "Scheduled" && schedule.scheduleDate && schedule.scheduleTime) {
        const date = new Date(schedule.scheduleDate);
        const [hours, minutes] = schedule.scheduleTime.split(":").map(Number);
        if (!isNaN(hours) && !isNaN(minutes)) {
          date.setHours(hours);
          date.setMinutes(minutes);
        }
        scheduledAt = date.toISOString();
      } else if (schedule.notificationType === "Daily") {
        if (schedule.startDate) {
          scheduledAt = new Date(schedule.startDate).toISOString();
        }
      }

      const payload = {
        name: notif.name || "test_adding",
        title: notif.title || " ",
        body: notif.text || " ",
        image_url: notif.image || undefined,
        target_criteria: cleanedTarget,
        additional_data: {
          customData: options.customData,
          schedule_details: schedule,
          persist: options.persist,
          apply_block_list: options.apply_block_list,
          apply_default_email: options.apply_default_email,
        },
        status: schedule.notificationType === "Now" ? "IN_PROGRESS" : "SCHEDULED",
        scheduled_at: scheduledAt
      };

      if (schedule.notificationType === "Now") {
        setPendingPayload(payload);
        openConfirm();
      } else {
        await processCampaign(payload);
      }
    };

    const handleAddCustomDataFields = () => {
      form.insertListItem("customData", { key: "", value: "" });
    };

    const last = form?.values?.customData?.[form.values.customData.length - 1];
    const disableAdd = last ? last.key.trim() === "" : false;

    const handleDeleteCustomDataField = (index: number) => {
      form.removeListItem("customData", index);
    };

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

    return (
      <StepContentWrapper
        title="Step 4 - Additional Options (Optional)"
        onClearClick={clearTargetForm}
      >
        <LoadingOverlay visible={loading} />
        <form
          onSubmit={form.onSubmit(handleSubmit)}
          style={{
            flex: 1,
            display: "flex",
            flexDirection: "column",
            justifyContent: "space-between",
            gap: "32px"
          }}
        >
          <Grid gutter={"lg"}>
            <Grid.Col span={12}>
              <Flex justify={"space-between"} align={"center"}>
                <Text fz={20} fw={500}>
                  Custom Data
                </Text>
                <Button
                  size="compact-sm"
                  leftSection={
                    <IconPlus size={13} style={{ marginRight: "-3px" }} />
                  }
                  onClick={handleAddCustomDataFields}
                  disabled={disableAdd}
                >
                  Custom Data
                </Button>
              </Flex>
              {form.values.customData?.map((obj, index) => (
                <React.Fragment key={index}>
                  {index > 0 && <Divider w={"100%"} mt={20} />}
                  <Flex mt={10} gap="sm" align="flex-end">
                    <div style={{ flex: 1 }}>
                      <TextInput
                        fz={14}
                        labelProps={{ fz: 13, mb: 5 }}
                        label="Key"
                        radius={4}
                        required
                        value={obj.key}
                        error={obj.key.trim() === "" ? "Key is required" : undefined}
                        onChange={(e) =>
                          form.setFieldValue(
                            `customData.${index}.key`,
                            e.target.value,
                          )
                        }
                      />
                    </div>
                    <div style={{ flex: 1, paddingBottom: obj.key.trim() === "" ? 20 : 0 }}>
                      <TextInput
                        fz={14}
                        labelProps={{ fz: 13, mb: 5 }}
                        label="Value"
                        radius={4}
                        value={obj.value}
                        onChange={(e) =>
                          form.setFieldValue(
                            `customData.${index}.value`,
                            e.target.value,
                          )
                        }
                      />
                    </div>
                    <div style={{ paddingBottom: obj.key.trim() === "" ? 20 : 0 }}>
                      <ActionIcon
                        color="red"
                        variant="light"
                        size="lg"
                        onClick={() => handleDeleteCustomDataField(index)}
                      >
                        <IconTrash size={16} />
                      </ActionIcon>
                    </div>
                  </Flex>
                </React.Fragment>
              ))}

              <Divider my={20} />
              <Checkbox
                key={form.key('persist')}
                label="Persist Notification"
                description="Save this notification in the user's history"
                {...form.getInputProps('persist', { type: 'checkbox' })}
              />

              <Checkbox
                mt="md"
                key={form.key('apply_block_list')}
                label="Apply Block List"
                description="Do not send to emails in the block list"
                {...form.getInputProps('apply_block_list', { type: 'checkbox' })}
              />

              <Checkbox
                mt="md"
                key={form.key('apply_default_email')}
                label="Apply Default Email"
                description="Include default monitoring emails in every batch"
                {...form.getInputProps('apply_default_email', { type: 'checkbox' })}
              />

            </Grid.Col>
          </Grid>
          <Flex justify={"end"}>
            <StepperNavigation
              activeStep={activeStep}
              setActiveStep={setActiveStep}
              notificationData={notificationForm.values}
            />
          </Flex>
        </form>
        <ConfirmAlert
          title="Send Notification"
          titleIcon={<IconExclamationCircleFilled color="orange" />}
          message="Are you sure you want to send this notification now?"
          handleConfirm={() => processCampaign(pendingPayload)}
          modalProps={{
            opened: confirmOpened,
            onClose: closeConfirm,
          }}
        />
      </StepContentWrapper>
    );
  };

export default AdditionalOptionsForm;
