import LayoutWithNav from "@/components/layout/LayoutWithNav";
import StandardContainer from "@/components/layout/StandardContainer";
import { useUser } from "context/UserContext";
import type { NextPage } from "next";
import { useRouter } from "next/router";
import { getRouterTitle } from "utilFuncs/utilFunctions";
import {
  Row,
  Col,
  Button,
  Tabs,
  Form,
  Input,
  notification,
  message,
  Modal,
} from "antd";
import ProfileLinks from "@/components/layout/ProfileLinks";
import {
  changePassword,
  fetchDistricts,
  genericDeleteRequest,
  genericPostRequest,
} from "apiCalls/apiEndpoints";
import { useDistricts } from "context/DistrictContext";
import { useMutation, useQueryClient } from "react-query";
import UpdateInformationForm from "@/components/forms/UpdateInformationForm";
import { NextSeo } from "next-seo";
import { withAuth } from "auth/withAuth";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import useToken from "utilFuncs/useToken";
import useAuth from "@/components/hooks/useAuth";

const { confirm } = Modal;
// import {queryclient} from "app"

const { TabPane } = Tabs;

const MyAccount: NextPage = ({ districts }: any) => {
  const [form] = Form.useForm();

  const router = useRouter();

  const { user, setUser } = useUser();

  const { setDistricts } = useDistricts();

  const queryClient = useQueryClient();

  const { setToken } = useToken();
  const { setisAuthenticated } = useAuth();

  setDistricts(districts);

  const { mutate: changePasswordMn, isLoading: isLoadingNewPassword } =
    useMutation(changePassword, {
      onSuccess: (data) => {
        notification.open({
          message: "Password Change Success",
          description: "Password was successfully changed",
        });

        // window.NavigationPreloadManager(())

        queryClient.invalidateQueries("user");
      },
      onError: (err: any) => {
        console.log(err);
        message.error(err?.response?.data?.errorMessage);
        notification.open({
          message: "An Error Occured",
          description: err?.response?.data?.errorMessage,
        });
      },
    });

  const { mutate: suspendUserMn, isLoading: isSuspendingAccount } = useMutation(
    genericDeleteRequest,
    {
      onSuccess: (data: any) => {
        notification.open({
          message: "Account Frozen Successfully",
          description: "Your account has successfully been Frozen",
        });
      },
      onError: (err: any) => {
        notification.open({
          message: "An Error Occured",
          description: err?.message,
        });
      },
    }
  );
  const { mutate: terminateAccMn, isLoading: isTerminatingAccount } =
    useMutation(genericDeleteRequest, {
      onSuccess: (data: any) => {
        notification.open({
          message: "Account Terminated Successfully",
          description: "Your account has successfully been Terminated",
        });

        setToken(null);

        setisAuthenticated(false);

        router.push("/");
      },
      onError: (err: any) => {
        notification.open({
          message: "An Error Occured while terminating your account",
          description: err?.message,
        });
      },
    });

  const { mutate: subToNotiMn, isLoading: isSubingToNoti } = useMutation(
    genericPostRequest,
    {
      onSuccess: (data: any) => {
        notification.open({
          message: "Notification Subscription Successful",
          description: "You have successfully subscribed to notifications, we'll notify you about updates on ashantiweb",
        });

       
      },
      onError: (err: any) => {
        notification.open({
          message: "An error occured while subscribing to notifications",
          description: err?.message,
        });
      },
    }
  );

  const { mutate: unsubToNotiMn, isLoading: isUnSubingToNoti } = useMutation(
    genericPostRequest,
    {
      onSuccess: (data: any) => {
        notification.open({
          message: "You have successfully unsubscribed from notifications",
          description: "You'll not be notified about updates on ashantiweb",
        });
      },
      onError: (err: any) => {
        notification.open({
          message: "An error occured while unsubscribing you from notifications, please try again later",
          description: err?.message,
        });
      },
    }
  );


  const onChange = (key: string) => {
    console.log(key);
  };

  const handleFormFinish = (values: any) => {
   
    changePasswordMn({
      password: values.new_password,
      old_password: values.old_password,
      password_confirmation: values.confirm_password,
    });
  };

  const onFormFinishFailed = (errorinfo: any) => {
    console.log("failed", errorinfo);
  };

  

  return (
    <LayoutWithNav page_title="My Account" description="My Acount">
      <NextSeo
        title={`My Account | Ashantiweb.com`}
        description={`My Account`}
      />
      <StandardContainer>
        <Row>
          <Col
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 24 }}
            lg={{ span: 6 }}
          >
            <ProfileLinks />
          </Col>
          <Col
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 24 }}
            lg={{ span: 18 }}
          >
            <div className="profile-dashboard">
              <div className="profile-sidebar-title">
                <h4 className="title">{getRouterTitle(router)}</h4>
              </div>
              <div className="profile-dashboard-wrapper pt-50">
                <Tabs defaultActiveKey="1" onChange={onChange}>
                  {/* change the condition for each one of these */}
                  <TabPane tab="Update your information" key="1">
                    <div className="profile-edit p-8">
                      <UpdateInformationForm />
                    </div>
                  </TabPane>
                  <TabPane tab="Password and Security" key="2">
                    <div className="profile-edit p-10">
                      <Form
                        // {...formItemLayout}
                        layout={"vertical"}
                        form={form}
                        onFinish={handleFormFinish}
                        onFinishFailed={onFormFinishFailed}
                      >
                        <Form.Item
                          name="old_password"
                          label="Old Password"
                          rules={[
                            {
                              required: true,
                              message: "Please input your old password",
                            },
                          ]}
                        >
                          <Input.Password placeholder="Enter your old password" />
                        </Form.Item>

                        <Form.Item
                          name={"new_password"}
                          label="New Password"
                          rules={[
                            {
                              required: true,
                              message: "Please input a new password",
                            },
                          ]}
                        >
                          <Input.Password placeholder="Enter Your new Password" />
                        </Form.Item>
                        <Form.Item
                          name={"confirm_password"}
                          label="Confirm Password"
                          rules={[
                            {
                              required: true,
                              message: "Please confirm your password",
                            },
                          ]}
                        >
                          <Input.Password placeholder="Re-enter your new password" />
                        </Form.Item>
                        <Form.Item>
                          <Button
                            htmlType="submit"
                            type="primary"
                            loading={isLoadingNewPassword}
                          >
                            Submit
                          </Button>
                        </Form.Item>
                      </Form>
                    </div>
                  </TabPane>
                  <TabPane tab="Actions" key="3">
                    <div className="profile-edit px-4">
                      <div className="container my-5 px-0 z-depth-1">
                        {user?.email_subscriptions?.length > 0 ? (
                          <section className="text-center white-text d-md-flex justify-content-between p-5 bg-success">
                            <div>
                              <h3 className="font-bold text-2xl mb-md-0 mb-4 mt-2 pt-1 text-white">
                                Unsubscribe to notifications
                              </h3>
                              <p className="text-white">
                                You will not recieve any notifications about
                                updates
                              </p>
                            </div>
                            <div>
                              <button
                                type="button"
                                className="btn btn-white btn-rounded"
                                disabled={isUnSubingToNoti}
                                onClick={() => {
                                  unsubToNotiMn("v1/auth/unsubscribe_from_email");
                                }}
                              >
                                {!isUnSubingToNoti
                                  ? "Click to unsubscribe"
                                  : "please wait..."}
                              </button>
                            </div>
                          </section>
                        ) : (
                          <section className="text-center white-text d-md-flex justify-content-between p-5 bg-success">
                            <div>
                              <h3 className="font-bold text-2xl mb-md-0 mb-4 mt-2 pt-1 text-white">
                                Subscribe to notifications
                              </h3>
                              <p className="text-white">
                                Get instant notifications on your device
                                whenever there is an update
                              </p>
                            </div>
                            <div>
                              <button
                                type="button"
                                className="btn btn-white btn-rounded"
                                disabled={isSubingToNoti}
                                onClick={() => {
                                  subToNotiMn("v1/auth/subscribe_to_email");
                                }}
                              >
                                {!isSubingToNoti
                                  ? "Click to subscribe"
                                  : "please wait..."}
                              </button>
                            </div>
                          </section>
                        )}
                      </div>
                      
                      <div className="container my-5 px-0 z-depth-1">
                        <section className="text-center white-text d-md-flex justify-content-between p-5 bg-warning">
                          <div>
                            <h3 className="font-bold text-2xl mb-md-0 mb-4 mt-2 pt-1 text-white">
                              Freeze Acount
                            </h3>
                          </div>
                          <div>
                            <button
                              type="button"
                              className="btn btn-white btn-rounded"
                              disabled={Boolean(
                                isSuspendingAccount || user?.deleted_at
                              )}
                              onClick={() => {
                                confirm({
                                  title: "Do you Want to Freeze your account?",
                                  icon: <ExclamationCircleOutlined />,
                                  content: "",
                                  onOk() {
                                    suspendUserMn(`v1/auth/suspend/${user.id}`);
                                  },
                                  onCancel() {},
                                });
                              }}
                            >
                              {isSuspendingAccount
                                ? "please wait..."
                                : "Freeze Account"}
                            </button>
                          </div>
                        </section>
                      </div>
                      <div className="container my-5 px-0 z-depth-1">
                        <section className="text-center white-text d-md-flex justify-content-between p-5 bg-danger">
                          <div>
                            <h3 className="font-bold text-2xl mb-md-0 mb-4 mt-2 pt-1 text-white">
                              Terminate Acount
                            </h3>
                            {/* <p className="text-white">Get instant notifications on your device whenever there is an update</p> */}
                          </div>
                          <div>
                            <button
                              type="button"
                              className="btn btn-white btn-rounded"
                              disabled={isTerminatingAccount}
                              onClick={() => {
                                confirm({
                                  title:
                                    "Do you want to terminate your account?",
                                  icon: <ExclamationCircleOutlined />,
                                  content: "This action cannot be reversed",
                                  onOk() {
                                    //terminate account
                                    // suspendUserMn(`v1/auth/suspend/${user.id}`);
                                    terminateAccMn(
                                      `v1/auth/delete/${user?.id}`
                                    );
                                  },
                                  onCancel() {},
                                });
                              }}
                            >
                              {isTerminatingAccount
                                ? "please wait..."
                                : "Terminate account"}
                            </button>
                          </div>
                        </section>
                      </div>
                    </div>
                  </TabPane>
                </Tabs>
              </div>
            </div>
          </Col>
        </Row>
      </StandardContainer>
    </LayoutWithNav>
  );
};

export default withAuth(MyAccount);

export async function getServerSideProps({ res, req }: any) {
  const districts = await fetchDistricts();

  return {
    props: {
      districts: districts.data,
    }, // will be passed to the page component as props
  };
}
