"use client";
import getData, { postData } from "@/utils/fetch";
import { useParseError } from "@/utils/lib/helpers";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Checkbox, Tabs, TabsRef, Tooltip } from "flowbite-react";
import { BaseSyntheticEvent, FC, useEffect, useRef, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { BsSend } from "react-icons/bs";
import { TiMessage, TiMessages } from "react-icons/ti";
import { toast } from "react-toastify";
import Button from "../Button";
import PageHeader from "../PageHeder";
import ActionButton from "../action-button";
import DropdownList from "../common/Dropdown";
import FilterForm from "../common/filter-form";
import { Textarea } from "../forms/Inputs";
import { clientFilter } from "../forms/schema/client-filter";
import { TSsmsSentSchema, smsSentSchema } from "../forms/schema/sms-sent";
import MyWallet from "../wallets/my-wallet";
import SmsClientList from "./sms-client-list";
import SmsSingle from "./sms-single";
import { useSearchParams } from "next/navigation";

type Props = {
  smsSent?: TSsmsSentSchema;
};

const SmsSentForm: FC<Props> = ({ smsSent }) => {
  const [filterValue, setFilter] = useState<string | null>(null);
  const [client_count, setClientCount] = useState(0);
  const [is_all_client, setAllClient] = useState(false);
  const searchParams = useSearchParams();
  const clientPhone = searchParams.get("phone");
  const tabsRef = useRef<TabsRef>(null);
  const allClientRef = useRef<HTMLInputElement>(null);
  const activeClientRef = useRef<HTMLInputElement>(null);
  const inactiveClientRef = useRef<HTMLInputElement>(null);
  const [sms_template_key, setSmsTemplateKey] = useState(1);
  const smsSentForm = useForm<TSsmsSentSchema>({
    resolver: zodResolver(smsSentSchema),
    mode: "onChange",
    defaultValues: smsSent as TSsmsSentSchema,
  });
  const queryClient = useQueryClient();
  const [template_type, setTemplateType] = useState<string | undefined>(
    undefined
  );
  const [query, setQuery] = useState<string | undefined>(undefined);
  const [message, setMessage] = useState<string | undefined>(undefined);
  const [clientIds, setClientIds] = useState<any[]>([]);

  const inputRef = useRef<HTMLInputElement>(null);

  const {
    handleSubmit,
    reset,
    control,
    setValue,
    formState: { errors },
  } = smsSentForm;

  const {
    mutate: smsSend,
    isPending,
    error,
    isError,
    isSuccess,
  } = useMutation({
    mutationFn: async (smsSentData: TSsmsSentSchema) => {
      const data = await postData(`/api/v1/sms-store`, smsSentData);
      if (data?.success) {
        return data?.data;
      }
      if (!data?.success) {
        throw data;
      }
    },
    onSuccess: (data) => {
      if (data?.message) {
        toast.success(`${data?.message}`);
      } else {
        toast.success(`Sms Send To Queue successfully!`);
      }
    },
    onError: (error: any) => {
      if (useParseError(error)) {
        toast.error(useParseError(error));
      }
    },
  });
  const onSubmit = async (data: TSsmsSentSchema) => {
    console.log(data);
    smsSend(data);
  };

  const onError = async (data: any) => {
    console.log(data);
  };
  useEffect(() => {
    setValue("clientIds", clientIds);
  }, [query, clientIds]);

  const handelAllClient = (event: BaseSyntheticEvent) => {
    let isChecked = event.target.checked;
    if (isChecked) {
      if (activeClientRef.current) {
        activeClientRef.current.checked = false;
      }
      if (inactiveClientRef.current) {
        inactiveClientRef.current.checked = false;
      }
      setAllClient(true);
      setValue("all_client", 1);
      let remove_inactive_filter = filterValue?.replace("status=0", "");
      setFilter(remove_inactive_filter);
      let remove_active_filter = filterValue?.replace("status=1", "");
      setFilter(remove_active_filter);
      setValue("status", null);
      if (
        template_type === "invoice_due" ||
        template_type === "invoice_due_reminder"
      ) {
        setFilter("invoice=due");
      }
    } else {
      setValue("all_client", 0);
      setAllClient(false);
      setFilter("");
      if (
        template_type === "invoice_due" ||
        template_type === "invoice_due_reminder"
      ) {
        setFilter("invoice=due");
      }
    }
    setClientIds([]);
    queryClient.invalidateQueries({ queryKey: ["clients"] });
  };

  const handelActiveClient = (event: BaseSyntheticEvent) => {
    let isChecked = event.target.checked;
    setValue("all_client", 0);
    setAllClient(false);
    if (isChecked) {
      allClientRef.current.checked = false;
      inactiveClientRef.current.checked = false;
      setFilter("status=1");
      setValue("status", 1);
    } else {
      let filter = filterValue?.replace("status=1", "");
      setFilter(filter);
      setValue("status", null);
    }
  };
  const handelInactiveClient = (event: BaseSyntheticEvent) => {
    let isChecked = event.target.checked;
    setValue("all_client", 0);
    setAllClient(false);
    if (isChecked) {
      allClientRef.current.checked = false;
      activeClientRef.current.checked = false;
      setFilter("status=0");
      setValue("status", 0);
    } else {
      let filter = filterValue?.replace("status=0", "");
      setFilter(filter);
      setValue("status", null);
    }
  };

  useEffect(() => {
    if (
      template_type === "invoice_due" ||
      template_type === "invoice_due_reminder"
    ) {
      setFilter("invoice=due");
    } else {
      setFilter("");
    }
  }, [template_type]);
  useEffect(() => {
    if (
      allClientRef?.current?.checked ||
      activeClientRef?.current?.checked ||
      inactiveClientRef?.current?.checked
    ) {
      setClientCount(client_count);
    } else {
      setClientCount(0);
    }
    if (clientIds?.length) {
      setClientCount(clientIds?.length);
    }
  }, [
    client_count,
    allClientRef,
    activeClientRef,
    inactiveClientRef,
    clientIds,
  ]);

  useEffect(() => {
    if (clientPhone && clientPhone?.length > 0) {
      tabsRef.current?.setActiveTab(1);
      setTemplateType("custom");
      setMessage("");
      setValue('sms_template_id', 7);
    }
  }, [clientPhone]);
  return (
    <>
      <PageHeader>
        <div className="flex justify-between px-2">
          <h1 className="font-semibold text-xl text-gray-900 mt-1">SMS</h1>
          <MyWallet balanceType={["sms"]} />
          <div className="flex">
            <ActionButton href="/communication-logs" type="back" title="Communication Logs" />
            <ActionButton
              href="/sms-templates"
              type="back"
              className="bg-green-500 ml-2"
            >
              Template
            </ActionButton>
          </div>
        </div>
      </PageHeader>
      <div className="pl-5 pt-2 bg-white">
        <Tabs
          aria-label="Tabs with icons"
          style="default"
          ref={tabsRef}
          onActiveTabChange={() => {
            reset();
            setClientCount(0);
            setSmsTemplateKey(sms_template_key + 1);
          }}
        >
          <Tabs.Item active title="Single SMS" icon={TiMessage}>
            <FormProvider {...smsSentForm}>
              <form onSubmit={handleSubmit(onSubmit, onError)}>
                <div className="overflow-auto mr-2">
                  <SmsSingle />
                </div>
                <input className="opacity-0" type="submit" ref={inputRef} />
              </form>
              <div className="pb-5">
                <ActionButton
                  isLoading={isPending}
                  type="submit"
                  title="Send"
                  onClick={() => inputRef.current?.click()}
                >
                  <BsSend className="mt-1 mr-1" />
                  <span>Send</span>
                </ActionButton>
              </div>
            </FormProvider>
          </Tabs.Item>
          <Tabs.Item active title="Bulk SMS" icon={TiMessages}>
            <FormProvider {...smsSentForm}>
              <form onSubmit={handleSubmit(onSubmit, onError)}>
                <div className="flex-none md:flex lg:flex gap-4 ">
                  <div className="mt-2 min-w-[300px]">
                    <DropdownList
                      name="sms_template"
                      idName="sms_template_id"
                      key={sms_template_key}
                      isMulti={false}
                      getLabel={(template) => template?.name}
                      defaultItems={clientPhone ? 'Custom' : ''}
                      placeholder="Select a template"
                      setOriginalValue={(template: any) => {
                        setMessage(template?.message);
                        setTemplateType(template?.template_type);
                      }}
                    />
                  </div>
                  <div className="mt-4 ml-2">
                    <p>
                      <span className="font-bold">{client_count}</span> SMS will
                      be send
                    </p>
                  </div>
                  <div className="mt-3 cursor-pointer">
                    <Checkbox
                      className="mr-2"
                      name="all_client"
                      id="all-client"
                      ref={allClientRef}
                      onChange={handelAllClient}
                    />
                    <label
                      htmlFor="all-client"
                      className="inline-block cursor-pointer"
                    >
                      All Clients
                    </label>
                  </div>
                  {template_type === "custom" && (
                    <>
                      <div className="mt-3 cursor-pointer">
                        <Checkbox
                          className="mr-2"
                          name="all_client"
                          ref={activeClientRef}
                          id="active-client"
                          value={1}
                          onChange={handelActiveClient}
                        />
                        <label
                          htmlFor="active-client"
                          className="inline-block cursor-pointer"
                        >
                          Active Clients
                        </label>
                      </div>
                      <div className="mt-3 cursor-pointer">
                        <Checkbox
                          ref={inactiveClientRef}
                          className="mr-2"
                          name="all_client"
                          id="inactive-client"
                          value={2}
                          onChange={handelInactiveClient}
                        />
                        <label
                          htmlFor="inactive-client"
                          className="inline-block cursor-pointer"
                        >
                          Inactive Clients
                        </label>
                      </div>
                    </>
                  )}
                </div>
                {message !== undefined && template_type !== "custom" && (
                  <div className="border mt-3 mr-2 p-5 rounded-md">
                    <div>{message}</div>
                  </div>
                )}
                {template_type === "custom" && (
                  <div className="mt-3 mr-2">
                    <Textarea
                      labelText="Message"
                      name="custom_message"
                      placeholder="Write Custom Message"
                      errors={errors}
                      rows={2}
                    />
                  </div>
                )}
                <input className="opacity-0" type="submit" ref={inputRef} />
              </form>
            </FormProvider>
            {message !== undefined && (
              <div className="pb-5">
                {client_count > 0 || clientIds?.length > 0 ? (
                  <ActionButton
                    isLoading={isPending}
                    type="submit"
                    title="Send"
                    onClick={() => inputRef.current?.click()}
                  >
                    <BsSend className="mt-1 mr-1" />
                    <span>Send</span>
                  </ActionButton>
                ) : (
                  <Tooltip content="SMS count is 0">
                    <Button
                      buttonType={`button`}
                      className="disabled"
                      disabled={true}
                    >
                      <BsSend className="mt-1 mr-1" />
                      <span>Send</span>
                    </Button>
                  </Tooltip>
                )}
              </div>
            )}
            {!is_all_client && (
              <div className="block mb-2 -ml-2">
                <FilterForm schema={clientFilter} setFilter={setFilter} />
              </div>
            )}
            <div className="mr-2 overflow-auto">
              <SmsClientList
                filterValue={filterValue}
                setFilter={setFilter}
                setClientCount={setClientCount}
                setClientIds={setClientIds}
                clientIds={clientIds}
                setQuery={setQuery}
                is_all_client={is_all_client}
              />
            </div>
          </Tabs.Item>
        </Tabs>
      </div>
    </>
  );
};

export default SmsSentForm;
