"use client";
import React, { useContext, useEffect, useState } from "react";
import { useOfflineContext } from "@/context/dashboard/OfflineContext";
import axios from "@/lib/axios";
import { usePathname } from "next/navigation";
import RadioGroup from "@mui/material/RadioGroup";
import FormControlLabel from "@mui/material/FormControlLabel";
import Radio from "@mui/material/Radio";
import ImageCustom from "@/components/constantElements/ImageCustom";
import Title from "@/components/main/Title";
import CheckboxCustom from "@/components/constantElements/CheckboxCustom";
import TextareaCustom from "@/components/constantElements/TextareaCustom";
import ButtonCustom from "@/components/constantElements/ButtonCustom";
import TextFieldCustom from "@/components/constantElements/TextFieldCustom";
import CartSidebar from "@/components/cart/CartSidebar";
import styles from "@/assets/css/dashboard/Dashboard.module.css";
import { Swiper, SwiperSlide } from "swiper/react";
import StickyBox from "react-sticky-box";
import { useRouter } from "next/navigation";
import CartContext from "@/context/CartContext";
import Skeleton from "@mui/material/Skeleton";

// Import Swiper styles
import "swiper/css";
import "swiper/css/pagination";
import "@/styles/styles.css";
import Link from "next/link";
import { Tab, Tabs } from "@mui/material";
import CartHeader from "@/components/cart/CartHeader";
import CartFooter from "@/components/cart/CartFooter";

const Page = () => {
  const { offlineId } = useOfflineContext();
  const pathName = usePathname();
  const [data, setData] = useState(null);
  const [gatewaySelect, setGatewaySelect] = useState(0);
  const [radioId, setRadioId] = useState(0);
  const [selectType, setSelectType] = useState(0);
  const [checked, setChecked] = useState(true);
  const [value, setValue] = useState(0);
  const [client, setClient] = useState(false);
  const router = useRouter();

  useEffect(() => {
    axios
      .get(`api${pathName}`)
      .then((response) => {
        setData(response.data.data);
        setRadioId(response.data.data.gateways[0].id);
      })
      .catch((error) => {});
    setClient(true);
  }, []);

  function a11yProps(index) {
    return {
      id: `simple-tab-${index}`,
      "aria-controls": `simple-tabpanel-${index}`,
    };
  }

  const radioHandler = (event) => {
    setGatewaySelect(event.target.value);
    setSelectType(Number(event.target.name));

    setRadioId(event.target.parentElement.getAttribute("id-data"));
  };

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  const payHandler = () => {
    axios
      .post("api/dashboard/offline-payment-submit", {
        gateway: radioId,
        approvment: checked,
        order_id: data.order.id,
      })
      .then((response) => {
        router.push(response.data.redirect);
      })
      .catch(() => {});
  };

  const breakpoints = {
    340: {
      slidesPerView: 2.5,
    },
    540: {
      slidesPerView: 2.5,
    },
    768: {
      slidesPerView: 3.5,
    },

    990: {
      slidesPerView: 4.5,
    },
    1024: {
      slidesPerView: 5,
    },
  };

  return (
    <>
      <CartContext>
        <CartHeader />
        <main className={styles.offline}>
          <div className="col-span-8 grid grid-cols-8 gap-4">
            <div className="sm:col-span-4 col-span-8 border rounded-lg p-4 flex flex-col gap-2">
              {client ? (
                data &&
                data.order && (
                  <>
                    <div className="pb-2 border-b mb-2">اطلاعات سفارش</div>
                    {data.order.order_code && (
                      <div className="sm:text-base text-sm">
                        شماره سفارش : {data.order.order_code}
                      </div>
                    )}
                    {data.order.order_date && (
                      <div className="sm:text-base text-sm">
                        تاریخ ثبت سفارش : {data.order.order_date}
                      </div>
                    )}
                    {data.order.address_result && (
                      <div className="sm:text-base text-sm">
                        آدرس : {data.order.address_result.full_address}
                      </div>
                    )}
                  </>
                )
              ) : (
                <>
                <div className="h-6">
                  <Skeleton
                    variant="text"
                    sx={{ width: "100%" }}
                    animation="wave"
                  />
                </div>

                <div className="h-6">
                <Skeleton
                  variant="text"
                  sx={{ width: "100%" }}
                  animation="wave"
                />

                </div>
                <div className="h-6">

                <Skeleton
                  variant="text"
                  sx={{ width: "100%" }}
                  animation="wave"
                />
                </div>
                
                </>
              )}

              {data && data.user && (
                <>
                  {data.user.full_name && (
                    <div className="sm:text-base text-sm">
                      نام کاربر : {data.user.full_name}
                    </div>
                  )}
                  {data.user.mobile && (
                    <div className="sm:text-base text-sm">
                      شماره موبایل : {data.user.mobile}
                    </div>
                  )}
                </>
              )}
            </div>
            {data &&
              data.order &&
              data.order.order_items &&
              data.order.order_items.length > 0 && (
                <div className="sm:col-span-4 col-span-8 border rounded-lg p-4 flex flex-col gap-2">
                  <div className="pb-2 border-b mb-2">محصولات</div>
                  <Swiper
                    spaceBetween={5}
                    breakpoints={breakpoints}
                    className="mySwiper_offline_order"
                  >
                    {data.order.order_items.map((items) => (
                      <SwiperSlide key={items.id}>
                        <Link
                          href={`/${items.slug}`}
                          title={items.name}
                          className="p-2 border rounded-lg grid grid-cols-1 gap-1"
                        >
                          <ImageCustom
                            data={items.image}
                            alt={items.image_alt}
                            title={items.image_alt}
                            // props
                            loading={"lazy"}
                            width={103}
                            height={103}
                            // fullWidth={false}
                          />
                          <div className="text-xs text-center">
                            {items.alt_name}
                          </div>
                          <div className="text-xs text-center">
                            {Number(items.price).toLocaleString()} تومان
                          </div>
                        </Link>
                      </SwiperSlide>
                    ))}
                  </Swiper>
                </div>
              )}
          </div>

          <div
            className={`border sm:col-span-6 col-span-8 rounded-lg gap-4 flex flex-col`}
          >
            <div>
              <Tabs
                value={value}
                onChange={handleChange}
                aria-label="basic tabs example"
                sx={{
                  borderBottom: 1,
                  borderColor: "divider",
                  "& .MuiTab-root.Mui-selected": {
                    color: "var(--theme-color)",
                  },
                  "& .MuiTabs-indicator": {
                    backgroundColor: "var(--theme-color)",
                  },
                }}
              >
                <Tab label="انتخاب روش پرداخت" {...a11yProps(0)} />
              </Tabs>
            </div>
            <div className="px-4 w-full pb-4">
              <RadioGroup
                aria-labelledby="demo-radio-buttons-group-label"
                value={gatewaySelect}
                name="radio-buttons-group"
                onChange={radioHandler}
                sx={{
                  width: "100%",
                  display: "grid",
                  gridTemplateColumns: "1fr",
                  gap: "1rem",
                }}
              >
                {data &&
                  data.gateways.length > 0 &&
                  data.gateways.map((gatewayItems, index) => (
                    <FormControlLabel
                      key={gatewayItems.id}
                      value={index}
                      data-id={gatewayItems.id}
                      name={0}
                      sx={{
                        margin: 0,
                        width: "100%",
                        "& .MuiFormControlLabel-label": { width: "100%" },
                      }}
                      control={
                        <Radio
                          id-data={gatewayItems.id}
                          size="small"
                          sx={{
                            marginRight: 1,
                            color: "var(--theme-color)",
                            "&.Mui-checked": {
                              color: "var(--theme-color)",
                            },
                          }}
                        />
                      }
                      label={
                        <div className="border rounded-lg flex w-full p-4 items-center h-24 gap-2">
                          <ImageCustom
                            data={gatewayItems.icon}
                            alt={gatewayItems.icon_alt}
                            title={gatewayItems.icon_alt}
                            loading={"lazy"}
                            fullWidth={false}
                            size="original"
                            width={59}
                            height={59}
                          />
                          <p className="text-sm">{gatewayItems.name}</p>
                        </div>
                      }
                    />
                  ))}
              </RadioGroup>
              {client ?
              
              <CheckboxCustom
                label="با شرایط و قوانین دی سی ای کالا موافقم"
                checked={checked}
                onChange={() => setChecked(!checked)}
              />

              :

            <div className="h-6">
                  <Skeleton
                    variant="text"
                    sx={{ width: "100%" }}
                    animation="wave"
                  />
                </div>
            
            }
            </div>
          </div>

          <div className="sm:col-span-2 col-span-8">
            <StickyBox offsetTop={0}>
              <div className="border rounded-lg p-4 grid grid-cols-1 gap-4">
                <div className="flex items-center justify-between">
                  <div className="text-sm">{`مبلغ کل (${
                    data &&
                    data.order &&
                    data.order.order_items &&
                    data.order.order_items.length > 0
                      ? data.order.order_items.length
                      : 0
                  } کالا)`}</div>
                  <div className="text-sm font-bold">
                    {data &&
                      data.order &&
                      Number(data.order.order_final_amount).toLocaleString()}
                    <span className="mr-1 font-normal">تومان</span>
                  </div>
                </div>
                <div className="flex items-center justify-between">
                  <div className="text-sm">هزینه ارسال</div>
                  <div className="text-sm font-bold">
                    {data &&
                      data.order &&
                      Number(data.order.delivery_amount).toLocaleString()}
                    <span className="mr-1 font-normal">تومان</span>
                  </div>
                </div>

                <div className="flex items-center justify-between border-t pt-2">
                  <div className="sm:text-sm text-xs">مبلغ قابل پرداخت</div>
                  <div className="sm:text-sm text-xs font-bold">
                    {data &&
                      data.order &&
                      Number(data.order.order_final_amount).toLocaleString()}
                    <span className="mr-1 font-normal">تومان</span>
                  </div>
                </div>
                <ButtonCustom
                  text="درگاه پرداخت"
                  title="درگاه پرداخت"
                  fullWidth={true}
                  onClick={payHandler}
                />
              </div>
            </StickyBox>
          </div>
        </main>
        <CartFooter />
      </CartContext>
    </>
  );
};

export default Page;
