import LayoutWithNav from "@/components/layout/LayoutWithNav";
import StandardContainer from "@/components/layout/StandardContainer";
import { NextSeo } from "next-seo";
import Image from "next/image";
import Link from "next/link";
import {
  Button,
  Col,
  Row,
  Modal,
  Form,
  Input,
  Upload,
  notification,
  Avatar,
  Typography,
  Card,
} from "antd";
import {
  DeleteOutlined,
  LoadingOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import type { UploadChangeParam } from "antd/es/upload";
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";
import RequireAuth from "auth/RequireAuth";
import { useUser } from "context/UserContext";
import type { NextPage } from "next";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { SyncLoader } from "react-spinners";
import { baseUrl, getRouterTitle, getToken } from "utilFuncs/utilFunctions";
import { UserOutlined } from "@ant-design/icons";
import styles from "../../styles/Home.module.css";
import ProfileLinks from "@/components/layout/ProfileLinks";
import { useMutation, useQuery, useQueryClient } from "react-query";
import {
  createShop,
  deleteItem,
  fetchMyShops,
  fetchShopAds,
} from "apiCalls/apiEndpoints";
import { withAuth } from "auth/withAuth";
import { PushSpinner } from "react-spinners-kit";
import Follow from "@/components/follow";

const { TextArea } = Input;

const MyShops: NextPage = () => {
  const router = useRouter();

  const { user, setUser } = useUser();

  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const [form] = Form.useForm();

  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [modalText, setModalText] = useState("Content of the modal");

  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [previewTitle, setPreviewTitle] = useState("");

  const showModal = () => {
    setVisible(true);
  };

  const handleOk = () => {
    setModalText("The modal will be closed after two seconds");
    setConfirmLoading(true);
    setTimeout(() => {
      setVisible(false);
      setConfirmLoading(false);
    }, 2000);
  };

  const handleCancel = () => {
    console.log("Clicked cancel button");
    setVisible(false);
  };

  const uploadButton = (
    <div>
      {<PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });

  const handleChangeNew: UploadProps["onChange"] = ({
    fileList: newFileList,
  }) => setFileList(newFileList);

  const handlePreviewModalCancel = () => setPreviewVisible(false);

  const handlePreview = async (file: any) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewVisible(true);
    setPreviewTitle(
      file.name || file.url!.substring(file.url!.lastIndexOf("/") + 1)
    );
  };

  const handleFormFinish = (values: any) => {
    console.log("values", values);
    // e.preventDefault()
    createShopMn(values);
  };

  const onFormFinishFailed = (errorinfo: any) => {
    console.log("failed", errorinfo);
  };

  const queryClient = useQueryClient();

  const [shop, setShop] = useState(null);

  //fetch my shops
  const { isLoading: isLoadingMyShops, data: myShopsMn } = useQuery(
    ["my-shops"],
    fetchMyShops,
    {
      onSuccess: (data) => {
        setShop(data.data[0]);
      },
    }
  );

  const shopSlug = myShopsMn?.data?.map((item: any) => item.slug)[0];
  const shopId = myShopsMn?.data?.map((item: any) => item.id)[0];

  console.log("shop id", shopId);

  //fetch my shop ads
  const { isLoading: isLoadingMyShopsAds, data: myShopsAdsMn } = useQuery(
    ["my-shop-ads", shopId!],
    fetchShopAds
  );

  const shopads = myShopsAdsMn?.data;

  //create shop with the mutation
  const {
    mutate: createShopMn,
    isLoading: isCreatingShop,
    isError: errorCreatingShops,
  } = useMutation(createShop, {
    onSuccess: (data) => {
      handleCancel();
      queryClient.invalidateQueries(["my-shops"]);
      notification.open({
        message: "Shop successfully created!",
        description:
          "Your shop has been created successfully, please allow for up to 24 hrs for us to verify your shop.",
      });
    },
    onError: (err: any) => {
      console.log(err);

      let errorObj = err.response.data.errors;

      let keys = Object.keys(errorObj);

      let message = "";

      keys.forEach((item) => {
        message += errorObj[item][0] + "\n";
      });

      notification.error({
        message: "Error Creating shop",
        description: message,
      });
    },
  });

  const [currentItem, setcurrentItem] = useState(null);

  //delete an advert
  const { mutate: deleteItemMn, isLoading: isDeletingItem } = useMutation(
    deleteItem,
    {
      onSuccess: (data) => {
        // router.reload();
        queryClient.invalidateQueries("my-shop-ads");
        notification.success({
          message: "Ad Deleted Successfully",
        });
      },
      onError: (err) => {
        console.log(err);
        notification.error({
          message: "Error",
          description: "Your Ad cannot be deleted at this time",
        });
      },
    }
  );

  if (isLoadingMyShops) {
    return (
      <div className="center mt-10">
        <SyncLoader color="green" size={5} />
      </div>
    );
  }

  return (
    <LayoutWithNav page_title="my-MyShops" description="my-MyShops">
     <NextSeo
        title="My Shop | Ashantiweb"
        description="View all your shops on ashantiweb"
      /> 
      <StandardContainer>
        {/* {isLoadingMyShops ? } */}

        <div className="flex justify-center items-center">
          <PushSpinner size={30} color="#686769" loading={isLoadingMyShops} />
        </div>

        {!isLoadingMyShops && (
          <Row>
            <Col
              xs={{ span: 24 }}
              sm={{ span: 24 }}
              md={{ span: 24 }}
              lg={{ span: 6 }}
            >
              <ProfileLinks shopSlug={shopSlug} />
            </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 pb-50">
                  {myShopsMn?.data.length <= 0 && (
                    <>
                      <p className="text-gray-700">
                        You do not have any active shop, please create one
                      </p>
                      <Button type="primary" onClick={showModal}>
                        create a new shop
                      </Button>
                    </>
                  )}

                  <Modal
                    title="Create A New Shop"
                    visible={visible}
                    // onOk={handleOk}
                    confirmLoading={confirmLoading}
                    onCancel={handleCancel}
                    footer={null}
                  >
                    <Form
                      // {...formItemLayout}
                      layout={"vertical"}
                      form={form}
                      onFinish={handleFormFinish}
                      onFinishFailed={onFormFinishFailed}
                      // initialValues={{ layout: formLayout }}
                      // onValuesChange={onFormLayoutChange}
                    >
                      <Form.Item
                        name="shop_name"
                        label="Shop Name"
                        rules={[
                          {
                            required: true,
                            message: "Please input your shop name",
                          },
                        ]}
                      >
                        <Input placeholder="Preferred Name for your shop" />
                      </Form.Item>
                      <Form.Item
                        name={"description"}
                        label="Tell us about your shop"
                        rules={[
                          {
                            required: true,
                            message:
                              "Please input a description about your shop",
                          },
                        ]}
                      >
                        <TextArea rows={4} placeholder="description" />
                      </Form.Item>
                      <Form.Item
                        name={"phone_number"}
                        label="Phone Number"
                        rules={[
                          {
                            required: true,
                            message:
                              "Please input a phone number for your shop",
                          },
                        ]}
                      >
                        <Input placeholder="Phone Number for your shop" />
                      </Form.Item>
                      <Form.Item
                        name={"email"}
                        label="Email"
                        rules={[
                          {
                            required: true,
                            message: "Please input an email for your shop",
                          },
                        ]}
                      >
                        <Input
                          type={"email"}
                          placeholder="Enter an email for your shop"
                        />
                      </Form.Item>
                      <Form.Item
                        name={"picture"}
                        label="Logo/Picture"
                        rules={[
                          {
                            required: false,
                            message: "Upload a picture or logo of your shop",
                          },
                        ]}
                      >
                        <Upload
                          name="file"
                          listType="picture-card"
                          className="avatar-uploader"
                          headers={{ Authorization: `Bearer ${getToken()}` }}
                          // action="/api/v1/magic-temp"
                          action={baseUrl() + "v1/magic-temp"}
                          // beforeUpload={beforeUpload}
                          onPreview={handlePreview}
                          onChange={handleChangeNew}
                          fileList={fileList}
                        >
                          {/* {imageUrl ? <div className='w-10 h-10 relative'><Image src={imageUrl} alt="avatar" layout='fill' /></div>  : uploadButton} */}
                          {fileList.length >= 1 ? null : uploadButton}
                          {/* <div className='w-10 h-10 relative'> {previewImage ? <Image src={previewImage} alt="avatar" layout='fill' /> : null} </div> */}
                        </Upload>
                        <Modal
                          visible={previewVisible}
                          title={previewTitle}
                          footer={null}
                          onCancel={handlePreviewModalCancel}
                        >
                          {/* <img alt="example" style={{ width: '100%' }} src={previewImage} /> */}
                          <div className="w-full h-50 relative bg-gray-500">
                            {" "}
                            {previewImage ? (
                              <Image
                                src={previewImage}
                                alt="avatar"
                                layout="fill"
                              />
                            ) : null}{" "}
                          </div>
                        </Modal>
                      </Form.Item>

                      <Form.Item>
                        <Button
                          htmlType="submit"
                          type="primary"
                          loading={isCreatingShop && !errorCreatingShops}
                        >
                          Submit
                        </Button>
                      </Form.Item>
                    </Form>
                  </Modal>

                  {/* display shop info here */}
                  <Row gutter={16}>
                    {shop?.verified ? (
                      <Card
                        style={{ textAlign: "center", marginTop: 16 }}
                        //   actions={getShopActions(shop)}
                      >
                        <Link
                          href={"/shop/" + shop?.slug}
                          // className="d-block w-100"
                        >
                          <a>
                            <Avatar
                              size={90}
                              src={shop?.picture}
                              style={{ marginBottom: "30px" }}
                            />
                            <Typography.Title
                              style={{ fontSize: "14px" }}
                              level={2}
                              ellipsis={{ rows: 2, expandable: false }}
                            >
                              {shop?.name}
                            </Typography.Title>
                            <Typography.Paragraph
                              ellipsis={{
                                rows: 2,
                                expandable: false,
                                symbol: "more",
                              }}
                            >
                              {shop?.description}
                            </Typography.Paragraph>

                            {/* <Follow entity={shop} modelType="shops" /> */}
                          </a>
                        </Link>
                        {/* <Button
                              type="priamry"
                              onClick={() =>
                                router.push(`/shop/${shop?.slug}/manage`)
                              }
                            >
                              Go to dashboard
                            </Button> */}
                      </Card>
                    ) : (
                      "Your shop is pending approval"
                    )}
                  </Row>

                  <Row className="mt-10">
                    <Col>
                      {shop && shop?.verified ? (
                        <Button
                          type="default"
                          onClick={() =>
                            router.push("/ads/post?post_to_shop=true")
                          }
                        >
                          Add new Ad to shop
                        </Button>
                      ) : (
                        ""
                      )}
                    </Col>
                  </Row>

                  <Row className="mt-10">
                    <Col>
                      {isLoadingMyShopsAds &&
                        "fetching shops ads please wait..."}
                    </Col>
                  </Row>

                  <Row>
                    <Col span={24}>
                      <h5 className="my-4">My shop ads</h5>
                    </Col>
                    <Col span={24}>
                      {shopads?.length <= 0 ? (
                        <>
                          <p>You have no ads</p>
                        </>
                      ) : (
                        <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-4 gap-4 w-full">
                          {shopads?.map((item: any, index: any) => (
                            <>
                              <a className="single-ads-product">
                                <div className="cursor-pointer border shadow-md rounded-md">
                                  <div className="h-[180px] sm:h-[200px] md:h-[170px] lg:h-[160px] w-full relative">
                                    <Image
                                      layout="fill"
                                      src={item?.picture}
                                      alt={item?.name}
                                      placeholder="blur"
                                      blurDataURL="/assets/images/preloader/preloader-static6.png"
                                    />
                                  </div>
                                  <div className="p-2">
                                    <p className="font-bold text-sm text-gray-700 h-12 mb-2">
                                      {item?.name.slice(0, 30)}
                                    </p>
                                    <p className="font-normal text-green-500 mt-2">
                                      GHC {item?.price}
                                    </p>
                                    <Button
                                      danger
                                      onClick={() => {
                                        setcurrentItem(item.id);
                                        deleteItemMn(`v1/ads/${item.id}`);
                                      }}
                                      loading={
                                        item.id == currentItem && isDeletingItem
                                      }

                                      // onClick={() => setLoadingToTrue(!loadingToTrue)}
                                    >
                                      <DeleteOutlined />
                                    </Button>
                                  </div>
                                </div>
                              </a>
                            </>
                          ))}
                        </div>
                      )}
                    </Col>
                  </Row>
                </div>
              </div>
            </Col>
          </Row>
        )}
      </StandardContainer>
    </LayoutWithNav>
  );
};

export default withAuth(MyShops);
