"use client";
import { useEffect, useState } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Check, PlusCircle } from "lucide-react";
import Popup from "./popup";
import {
  useGetAdminSettings,
  useGetAdminRelationshipSettings,
  useGetAdminReligionSettings,
} from "@/src/utils/hooks/useGetAdminSettings";
import {
  setRelationShipName,
  setRelationShipType,
} from "@/src/redux/appActions";
import LoadingSpinner from "../../reusables/ui/LoadingSpinner";
import { useUpdateSettings } from "@/src/utils/hooks/useGetAdminSettings";
import { toast } from "react-toastify";
import SectionSkeleton from "../../reusables/ui/Loading";

type settingsPopType = "relationship" | "" | "religion";

export default function Settings() {
  const [currency, setCurrency] = useState("naira");
  const [subscriptionAmount, setSubscriptionAmount] = useState("");
  const [expirationDays, setExpirationDays] = useState("7");
  const [verificationAmount, setVerificationAmount] = useState("");
  const [matchPercentage, setMatchPercentage] = useState("70");
  const [popup, setPopup] = useState<boolean>(false);
  const [settingsType, setSettingsType] = useState<settingsPopType>("");
  const [popData, setPopData] = useState<{
    id: number;
    key: string;
    value: any[];
    created_at: string;
    updated_at: string;
  }>({ id: 0, key: "", value: [], created_at: "", updated_at: "" });

  const [initiaInputValus, setInitialInputValues] = useState<{
    subscriptionAmount: string;
    expirationDays: string;
    verificationAmount: string;
  }>({ subscriptionAmount: "0", expirationDays: "0", verificationAmount: "0" });

  // Track if the initial data has been loaded
  const [initialLoadComplete, setInitialLoadComplete] = useState(false);

  const formatNumberWithCommas = (value: string): string => {
    if (!value) return "";
    const number = value.replace(/,/g, "");
    if (isNaN(Number(number))) return value;
    return Number(number).toLocaleString();
  };

  const removeCommas = (value: string): string => {
    return value.replace(/,/g, "");
  };

  // Validation function for number inputs
  const validateNumberInput = (
    value: string,
    maxValue?: number,
    minValue: number = 1
  ): string => {
    // Remove commas for validation
    const cleanValue = removeCommas(value);

    // Allow empty string
    if (cleanValue === "") return "";

    if (isNaN(Number(cleanValue))) return "";

    const numValue = Number(cleanValue);

    if (numValue < minValue) return minValue.toString();

    if (maxValue && numValue > maxValue) return maxValue.toString();

    return cleanValue;
  };

  const handleSubscriptionAmountChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const inputValue = e.target.value;
    const validatedValue = validateNumberInput(inputValue);
    setSubscriptionAmount(validatedValue);
  };

  const handleExpirationDaysChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const inputValue = e.target.value;
    const validatedValue = validateNumberInput(inputValue, 30, 2);
    setExpirationDays(validatedValue);
  };

  const handleVerificationAmountChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const inputValue = e.target.value;
    const validatedValue = validateNumberInput(inputValue);
    setVerificationAmount(validatedValue);
  };

  const handlePopOpen = (settings: settingsPopType) => {
    setSettingsType(settings);
    setPopup(true);
  };

  const handlePopClose = () => {
    setSettingsType("");
    setPopup(false);
  };

  const { data, isLoading } = useGetAdminSettings();

  const { data: relationship_values, isLoading: relationship_loading } =
    useGetAdminRelationshipSettings("relationship_type");

  const { data: religion_values, isLoading: religion_loading } =
    useGetAdminReligionSettings("religion");

  // set pop render values
  useEffect(() => {
    console.log(relationship_values, "relation settings at pop");
    console.log(religion_values, "religion settings at pop");

    if (
      settingsType === "relationship" &&
      relationship_values &&
      relationship_values.payload
    ) {
      setPopData(relationship_values.payload);
    } else {
      if (
        settingsType === "religion" &&
        religion_values &&
        religion_values.payload
      )
        setPopData(religion_values.payload);
    }
  }, [relationship_values, religion_values, settingsType]);

  useEffect(() => {
    console.log(data, "is settings data");
    if (data?.payload?.length) {
      // subscripbe amount settings
      const subscribeAmountSetting = data.payload.find(
        (item: any) => item.key === "subscribe_amount"
      );

      const amount = subscribeAmountSetting?.value?.[0];
      setSubscriptionAmount(amount);

      const interestExpiration = data.payload.find(
        (item: any) => item.key === "subscribe_day"
      );
      const expirationDays = interestExpiration?.value?.[0];
      setExpirationDays(expirationDays);

      const addressVerificationAmount = data.payload.find(
        (item: any) => item.key === "address_verification_amount"
      );
      const addressVerificatinPrice = addressVerificationAmount?.value?.[0];
      setVerificationAmount(addressVerificatinPrice);

      setInitialInputValues((prev) => ({
        ...prev,
        subscriptionAmount: amount,
        expirationDays: expirationDays,
        verificationAmount: addressVerificatinPrice,
      }));

      // Mark initial load as complete after data is set
      setInitialLoadComplete(true);

      console.log(expirationDays, "expiration");
    }
  }, [isLoading, data]);

  const {
    mutate: mutateSubscriptionAmount,
    isPending: subscriptionAmountLoading,
  } = useUpdateSettings("subscribe_amount");

  const {
    mutate: mutateSubscriptionExpirationDay,
    isPending: subscriptionExpirationDayLoading,
  } = useUpdateSettings("subscribe_day");

  const {
    mutate: mutateAddressverificationAmount,
    isPending: addressVerificationAmount,
  } = useUpdateSettings("address_verification_amount");

  const handlePostSubscriptionAmount = async (value: string) => {
    const cleanValue = removeCommas(value);
    mutateSubscriptionAmount(Array(cleanValue), {
      onSuccess: (data) =>
        toast.success(
          data?.message || "Subscription amount updated successfully"
        ),
    });
  };

  const handlePostSubscriptionExpirationDay = async (value: string) => {
    const cleanValue = removeCommas(value);
    mutateSubscriptionExpirationDay(Array(cleanValue), {
      onSuccess: (data) =>
        toast.success(data?.message || "Subscription days successfully"),
    });
  };

  const handlePostAddressverificationAmount = async (value: string) => {
    const cleanValue = removeCommas(value);
    mutateAddressverificationAmount(Array(cleanValue), {
      onSuccess: (data) =>
        toast.success(
          data?.message || "address verification updated successfully"
        ),
    });
  };

  const shouldShowCheckmark = (currentValue: string, initialValue: string) => {
    const cleanCurrent = removeCommas(currentValue);
    const cleanInitial = removeCommas(initialValue);
    return initialLoadComplete && cleanCurrent.trim() !== cleanInitial.trim();
  };

  return (
    <>
      {isLoading ? (
        <SectionSkeleton />
      ) : (
        <div className="w-full max-w-4xl py-4 md:py-6">
          <Card className="p-6 bg-white rounded-lg shadow-sm">
            <form className="space-y-8">
              {/* Subscription Amount */}
              <div className="flex md:flex-row flex-col justify-between md:items-center">
                <div className="space-y-2 text-black md:mb-0 mb-2 font-semibold">
                  <h3 className="text-base font-medium text-[13px]">
                    Subscription amount
                  </h3>
                  <p className="text-[10px]">
                    You can tweak the amount you want to charge for users
                    subscription payment here
                  </p>
                </div>
                <div className="flex md:w-auto w-full">
                  <div
                    className={`flex ${
                      shouldShowCheckmark(
                        subscriptionAmount,
                        initiaInputValus.subscriptionAmount
                      )
                        ? "w-[95%]"
                        : "w-full"
                    }`}
                  >
                    <Input
                      type="text"
                      value={formatNumberWithCommas(subscriptionAmount)}
                      onChange={handleSubscriptionAmountChange}
                      placeholder="--"
                      className="w-full md:w-56 h-10 rounded-r-none"
                    />
                    <div className="h-10 flex items-center justify-center bg-[#D9D9D9] rounded-md rounded-l-none w-[60px]">
                      <span className="font-medium text-[16px]">₦</span>
                    </div>
                  </div>

                  {shouldShowCheckmark(
                    subscriptionAmount,
                    initiaInputValus.subscriptionAmount
                  ) && (
                    <Button
                      type="button"
                      variant={"ghost"}
                      className="cursor-pointer hover:bg-[#16166C]/20 bg-[#16166C]/20 ml-4 text-[#16166C] hover:text-[#16166C] relative group/tooltip"
                      onClick={async () =>
                        handlePostSubscriptionAmount(subscriptionAmount)
                      }
                    >
                      {subscriptionAmountLoading ? (
                        <LoadingSpinner className="text-[#16166C] bg-white" />
                      ) : (
                        <div>
                          <Check size={40} />
                          <div className="absolute top-full right-0 mb-1 px-2 py-1 text-xs bg-gray-800 text-white rounded opacity-0 group-hover/tooltip:opacity-100 transition-opacity duration-200 whitespace-nowrap pointer-events-none z-50">
                            Update subscription amount
                          </div>
                        </div>
                      )}
                    </Button>
                  )}
                </div>
              </div>

              {/* Interest Expiration Duration */}
              <div className="flex md:flex-row flex-col justify-between md:items-center">
                <div className="space-y-2 text-black md:mb-0 mb-2">
                  <h3 className="text-base font-semibold text-[13px]">
                    Interest expiration duration
                  </h3>
                  <p className="text-[10px] font-semibold">
                    This adjusts how long an interest shown in a person can stay
                    for before it expires
                  </p>
                </div>
                <div className="flex md:w-auto w-full gap-x-2 justify-between">
                  <div
                    className={`${
                      shouldShowCheckmark(
                        expirationDays,
                        initiaInputValus.expirationDays
                      )
                        ? "w-[95%]"
                        : "w-full"
                    } flex`}
                  >
                    <Input
                      type="text"
                      value={formatNumberWithCommas(expirationDays)}
                      onChange={handleExpirationDaysChange}
                      className="w-full md:w-56 h-10 rounded-r-none"
                    />
                    <div className="h-10 px-3 flex items-center justify-center bg-[#D9D9D9] rounded-md rounded-l-none w-[60px]">
                      <span className="text-black text-[16px]">days</span>
                    </div>
                  </div>

                  {shouldShowCheckmark(
                    expirationDays,
                    initiaInputValus.expirationDays
                  ) && (
                    <Button
                      type="button"
                      variant={"ghost"}
                      onClick={async () =>
                        handlePostSubscriptionExpirationDay(expirationDays)
                      }
                      className="cursor-pointer hover:bg-[#16166C]/20 bg-[#16166C]/20 ml-4 text-[#16166C] hover:text-[#16166C] relative group/tooltip"
                    >
                      {subscriptionExpirationDayLoading ? (
                        <LoadingSpinner className="text-[#16166C] bg-white" />
                      ) : (
                        <div>
                          <Check size={40} />
                          <div className="absolute top-full right-0 mb-1 px-2 py-1 text-xs bg-gray-800 text-white rounded opacity-0 group-hover/tooltip:opacity-100 transition-opacity duration-200 whitespace-nowrap pointer-events-none z-50">
                            Update interest expiration duration
                          </div>
                        </div>
                      )}
                    </Button>
                  )}
                </div>
              </div>

              {/* Verification Amount */}
              <div className="flex md:flex-row flex-col justify-between md:items-center">
                <div className="space-y-2 text-black md:mb-0 mb-2">
                  <h3 className="text-base font-semibold text-[13px]">
                    Address Verification amount
                  </h3>
                  <p className="text-[10px] font-semibold">
                    This adjusts how much you want to charge for address
                    verification
                  </p>
                </div>
                <div className="flex md:w-auto w-full gap-x-2 justify-between">
                  <div
                    className={`${
                      shouldShowCheckmark(
                        verificationAmount,
                        initiaInputValus.verificationAmount
                      )
                        ? "w-[95%]"
                        : "w-full"
                    } flex`}
                  >
                    <Input
                      type="text"
                      value={formatNumberWithCommas(verificationAmount)}
                      onChange={handleVerificationAmountChange}
                      className="w-full md:w-56 h-10 rounded-r-none"
                    />
                    <div className="h-10 px-3 flex items-center justify-center bg-[#D9D9D9] rounded-md rounded-l-none w-[60px]">
                      <span className="text-black text-[16px]">₦</span>
                    </div>
                  </div>

                  {shouldShowCheckmark(
                    verificationAmount,
                    initiaInputValus.verificationAmount
                  ) && (
                    <Button
                      variant={"ghost"}
                      type="button"
                      onClick={() =>
                        handlePostAddressverificationAmount(verificationAmount)
                      }
                      className="cursor-pointer hover:bg-[#16166C]/20 bg-[#16166C]/20 ml-4 text-[#16166C] hover:text-[#16166C] relative group/tooltip"
                    >
                      {addressVerificationAmount ? (
                        <LoadingSpinner className="text-[#16166C] bg-white" />
                      ) : (
                        <div>
                          <Check size={40} />
                          <div className="absolute top-full right-0 mb-1 px-2 py-1 text-xs bg-gray-800 text-white rounded opacity-0 group-hover/tooltip:opacity-100 transition-opacity duration-200 whitespace-nowrap pointer-events-none z-50">
                            Update address verification amount
                          </div>
                        </div>
                      )}
                    </Button>
                  )}
                </div>
              </div>

              {/* Add Relationship Type */}
              <div className="flex md:flex-row flex-col justify-between items-center">
                <div className="space-y-2 text-black font-semibold">
                  <h3 className="text-base text-[13px]">
                    Add Relationship type
                  </h3>
                  <p className="text-[10px]">
                    Your choice of relationship type visible to the users can be
                    created and updated here
                  </p>
                </div>
                <div className="flex md:w-auto w-full justify-end">
                  <Button
                    onClick={() => handlePopOpen("relationship")}
                    type="button"
                    variant="default"
                    className="bg-[#16166C] hover:bg-[#16166C] text-white h-8 cursor-pointer"
                  >
                    Add <PlusCircle className="ml-2 h-4 w-4" />
                  </Button>
                </div>
              </div>

              {/* Add Religion */}
              <div className="flex md:flex-row flex-col justify-between items-center">
                <div className="space-y-2 text-black">
                  <h3 className="text-base font-semibold text-[13px]">
                    Add Religion
                  </h3>
                  <p className="text-[10px] font-semibold">
                    Your choice of religion visible to the users can be created
                    and updated here
                  </p>
                </div>
                <div className="flex md:w-auto w-full justify-end">
                  <Button
                    onClick={() => handlePopOpen("religion")}
                    type="button"
                    variant="default"
                    className="bg-[#16166C] hover:bg-[#16166C] text-white h-8 cursor-pointer"
                  >
                    Add <PlusCircle className="ml-2 h-4 w-4" />
                  </Button>
                </div>
              </div>
            </form>
          </Card>

          <Popup
            reference={settingsType}
            isOpen={popup}
            onClose={handlePopClose}
            data={popData}
          />
        </div>
      )}
    </>
  );
}
