"use client";
import { Switch } from "@/src/components/user/settingspage/switch";
import { Input } from "@/src/components/user/settingspage/input";
import { Button } from "@/components/ui/button";
import Popup from "@/src/components/reusables/ui/popup";
import { useEffect, useState } from "react";
import { Check } from "lucide-react";
import { Value } from "@radix-ui/react-select";
import LoadingSpinner from "../../reusables/ui/LoadingSpinner";
import { useGetUserSettings } from "@/src/utils/hooks/useGetUserSettings";
import { toast } from "react-toastify";
import SkeletonLine from "../../reusables/SkeletonLine";
import { useGetUserProfile } from "@/src/utils/hooks/useGetUserProfile";
import { setAboutMe, setUserProfile } from "@/src/redux/profileSlice";
import { useAppDispatch } from "@/src/redux/hook";
import axiosInstance from "@/lib/axios";
import axios from "axios";

export default function SettingsPage() {
  const [deleteAccount, setDeleteAccount] = useState(false);
  const [matchupValue, setMatchupValue] = useState("");
  const [ageSwitch, setAgeSwitch] = useState<boolean | number | string>("");
  const [locationSwitch, setLocationSwitch] = useState<
    boolean | number | string
  >("");
  const [initialMatchupValue, setInitialMatchupValue] = useState("");
  const [deactivate, setDeactivate] = useState<any>("");
  const [loading, setLoading] = useState(false);
  const [loading2, setLoading2] = useState(false);

  const dispatch = useAppDispatch();

  const { data, isLoading, refetch } = useGetUserSettings();
  const { data: userProfileData, refetch: refetchProfile } =
    useGetUserProfile();

  useEffect(() => {
    if (data?.payload) {
      setAgeSwitch(data.payload.hide_age);
      setLocationSwitch(data.payload.hide_location);
      setMatchupValue(data.payload.matchup_settings);
      setInitialMatchupValue(data.payload.matchup_settings);
    }
  }, [data]);

  useEffect(() => {
    if (userProfileData?.payload) {
      setDeactivate(userProfileData?.payload?.is_account_deleted);
      dispatch(setUserProfile(userProfileData.payload));
      dispatch(setAboutMe(userProfileData.payload.about_me));
    }
  }, [userProfileData]);

  const updateSetting = async (
    field: "hide_age" | "hide_location",
    value: 1 | 0
  ) => {
    try {
      const userId = localStorage.getItem("userId");
      if (!userId) throw new Error("UserID not given");

      await axiosInstance.patch(`/users/${userId}/settings/${field}`, {
        value,
      });

      refetch();
    } catch (error) {
      console.error(error);
    }
  };

  // calls endpoint
  const handleDeleteClick = () => {
    setDeleteAccount(true);
  };

  const handleSettings = async ({ field }: any) => {
    try {
      if (typeof window === "undefined") return;

      const userId = localStorage.getItem("userId");

      if (!userId) {
        throw new Error("UserID not provided");
      }

      const userToken = localStorage.getItem("userToken");
      const apiUrl = process.env["NEXT_PUBLIC_DEV_URL"];

      setLoading2(true);

      const response = await axios.patch(
        `${apiUrl}/users/${userId}/settings/${field}`,
        {
          value: matchupValue,
        },
        {
          headers: {
            Authorization: `Bearer ${userToken}`,
            "Content-Type": "application/json",
          },
        }
      );

      setLoading2(false);
      toast.success(response?.data?.message);
      refetch();
    } catch (error) {
      setLoading(false);
    }
  };

  const handleDeactivateAccount = async () => {
    try {
      if (typeof window === "undefined") return;

      const userId = localStorage.getItem("userId");

      if (!userId) {
        throw new Error("USerID not provided");
      }

      setLoading(true);

      const response = await axiosInstance.post(
        `/account/request-deletion`,
        {}
      );

      setLoading(false);
      toast.success("Account Deactivated Successfully");
      refetchProfile();
    } catch (error) {
      setLoading(false);
    }
  };

  const handleActivateAccount = async () => {
    try {
      if (typeof window === "undefined") return;

      const userId = localStorage.getItem("userId");

      if (!userId) {
        return;
      }

      setLoading(true);

      const response = await axiosInstance.post(`/account/cancel-deletion`, {});

      setLoading(false);
      toast.success("Account Activated Successfully");
      refetchProfile();
    } catch (error) {
      setLoading(false);
    }
  };

  const hasChanged = matchupValue !== initialMatchupValue;

  return (
    <div className="min-h-screen py-8 px-4 md:px-8 max-w-[90%] mx-auto lg:-mt-[50px] mt-4">
      <div className="w-full font-semibold">
        <h1 className="text-[16px] font-bold mb-6">Settings</h1>

        <div className="bg-white border rounded-md p-6 md:p-8 md:w-[90%]">
          {/* Privacy Settings */}

          {isLoading ? (
            <div className="flex items-center sm:gap-10 gap-6 flex-col">
              <SkeletonLine />
              <SkeletonLine />
              <SkeletonLine />
            </div>
          ) : (
            <>
              <div className="mb-4 flex md:flex-row flex-col justify-between">
                <div>
                  <h2 className="text-[12px] font-bold mb-2">
                    Privacy Settings
                  </h2>
                  <p className="text-gray-700 mb-4 text-[10px]">
                    You can control if everyone should see your age/location
                  </p>
                </div>

                <div className="space-y-4">
                  {/* <div className="flex items-center justify-between text-[10px]">
                    <span className="text-gray-700 mr-1">Hide age</span>
                    <Switch
                      checked={ageSwitch === "1"}
                      onCheckedChange={(checked) => {
                        setAgeSwitch(checked ? 1 : 0);
                        updateSetting("hide_age", checked ? 1 : 0);
                      }}
                    />
                  </div> */}

                  <div className="flex items-center justify-between text-[10px]">
                    <span className="text-gray-700 mr-1">Hide Location</span>
                    <Switch
                      checked={locationSwitch === "1"}
                      onCheckedChange={(checked) => {
                        setLocationSwitch(checked ? 1 : 0);
                        updateSetting("hide_location", checked ? 1 : 0);
                      }}
                    />
                  </div>
                </div>
              </div>

              {/* Default Match Settings */}
              <div className="mb-4 lg:flex lg:items-center lg:justify-between">
                <div>
                  <h2 className="text-lg font-bold mb-2 text-[12px]">
                    Default match settings
                  </h2>
                  <p className="text-gray-700 mb-4 text-[10px]">
                    As a user, you can adjust your match percentage settings to
                    any percentage of choice
                  </p>
                </div>

                <div className="flex items-center justify-end md:w-auto w-full">
                  <div className="flex items-center md:w-auto w-full">
                    <Input
                      type="number"
                      defaultValue="70"
                      className="md:w-24 w-full h-10 rounded-r-none"
                      value={matchupValue}
                      onChange={(e) => setMatchupValue(e.target.value)}
                    />
                    <div className="h-10 px-3 flex items-center justify-center bg-gray-200 rounded-r-md border border-l-0 border-input">
                      %
                    </div>
                  </div>
                  {hasChanged && (
                    <Button
                      type="button"
                      variant={"ghost"}
                      className="cursor-pointer text-white ml-2 bg-red-500"
                      onClick={() =>
                        handleSettings({ field: "matchup_settings" })
                      }
                    >
                      {loading2 ? <LoadingSpinner /> : <Check size={40} />}
                    </Button>
                  )}
                </div>
              </div>

              {/* Notifications */}

              {/* Deactivate Account */}
              <div className="flex items-center gap-4 justify-between flex-wrap">
                <div>
                  <h2 className="text-lg font-bold mb-2 text-[12px]">
                    Deactivate account
                  </h2>
                  <p className="text-gray-700 mb-4 text-[10px]">
                    User can mark own account for deletion. When turned on, warn
                    user that his/her account on the portal will be deleted
                    after 7 days
                  </p>
                </div>

                <div className="flex justify-end">
                  {deactivate !== false ? (
                    <Button
                      className="bg-[#000] text-white rounded-full px-6"
                      onClick={() => handleActivateAccount()}
                    >
                      {loading ? <LoadingSpinner /> : "Activate"}
                    </Button>
                  ) : (
                    <Button
                      variant="destructive"
                      className={`rounded-full px-6 ${
                        deactivate === "1"
                          ? "bg-red-300 cursor-not-allowed"
                          : "bg-red-500 hover:bg-red-600"
                      }`}
                      onClick={handleDeleteClick}
                    >
                      {loading ? <LoadingSpinner /> : "Deactivate"}
                    </Button>
                  )}
                </div>
              </div>
            </>
          )}
        </div>
      </div>

      <Popup
        isOpen={deleteAccount}
        title="Deactivate Account"
        message="Do you really want to delete your account? Proceeding with this means your account will be deleted after 2 days"
        message2="You will not be able to login your account after the 2nd day of marking your account for deletion"
        onClose={() => setDeleteAccount(false)}
        handleDeactivateAccount={handleDeactivateAccount}
        setDeactivate={setDeactivate}
        loading={loading}
      />
    </div>
  );
}
