import Card from "@/UI/Card";
import List from "@/UI/List";
import Menu from "@/UI/Menu";
import Table from "@/UI/Table";
import { stringShorter } from "@/utils/functions";
import { EditOutlined } from "@ant-design/icons";
import { Image, Popover, Tooltip, Badge, Divider } from "antd";
import moment from "moment";
import { useEffect } from "react";
import { BsQuestionCircle, BsThreeDotsVertical } from "react-icons/bs";
import { CiBarcode } from "react-icons/ci";
import { useDispatch, useSelector } from "react-redux";
import { Link, useParams } from "react-router-dom";
import {
  clearProduct,
  deleteProduct,
  loadSingleProduct,
} from "../../redux/rtk/features/product/productSlice";
import useCurrency from "../../utils/useCurrency";
import ViewBtn from "../Buttons/ViewBtn";
import CommonDelete from "../CommonUi/CommonDelete";
import BigDrawer from "../Drawer/BigDrawer";
import Loader from "../Loader/Loader";
import UserPrivateComponent from "../PrivacyComponent/UserPrivateComponent";
import AddGalleryImage from "./AddGalleryImage";
import AddVariantToExistingGroup from "./AddVariantToExisitngGroup";
import GenerateBarcode from "./BarcodeGenerator";
import GalleryImageSlider from "./GalleryImageSlider";

const DetailsProduct = () => {
  const { id } = useParams();
  const columns = [
    {
      id: 1,
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: "50px",
      render: (id) => <Link to={`/admin/product/${id}`}>{id}</Link>,
      renderCsv: (id) => id,
    },
    {
      id: 2,
      title: "Image",
      dataIndex: "productThumbnailImage",
      render: (productThumbnailImage) => (
        <div className='w-[2.5rem] h-[1.375rem] relative'>
          <img
            className='absolute object-cover w-full h-full'
            alt='product'
            onError={handleOnError}
            src={
              `${import.meta.env.VITE_APP_API}/media/view/${productThumbnailImage}` ||
              "/images/default.jpg"
            }
          />
        </div>
      ),
      key: "image",
      width: "70px",
      csvOff: true,
    },
    {
      id: 4,
      title: "Name",
      dataIndex: "name",
      key: "name",
      render: (name, { id }) => (
        <Link title={name} to={`/admin/product/${id}`}>
          {stringShorter(name, 45)}
        </Link>
      ),
      width: "150px",
      renderCsv: (name) => name,
      tdClass: "whitespace-normal",
    },
    {
      id: 3,
      title: "SKU",
      dataIndex: "sku",
      key: "sku",
    },

    {
      id: 7,
      title: "Purchase price",
      dataIndex: "stockInfo",
      render: (stockInfo) => stockInfo[0]?.productPurchasePrice,
      renderCsv: (stockInfo) => stockInfo[0]?.productPurchasePrice,
      key: "productPurchasePrice",
      responsive: ["md"],
    },
    {
      id: 8,
      title: "Sale price",
      dataIndex: "stockInfo",
      render: (stockInfo) => stockInfo[0]?.productSalePrice,
      renderCsv: (stockInfo) => stockInfo[0]?.productSalePrice,
      key: "productSalePrice",
      responsive: ["md"],
    },
    {
      id: 9,
      title: "Attributes",
      dataIndex: "productProductAttributeValue",
      key: "productProductAttributeValue",
      render: (productProductAttributeValue) =>
        productProductAttributeValue?.map((item, index) => (
          <span key={index}>
            {item.productAttributeValue.productAttribute.name}:{" "}
            {item.productAttributeValue.name}
            {index !== productProductAttributeValue.length - 1 ? ", " : ""}
          </span>
        )),
    },
    {
      id: 6,
      title: "Quantity",
      dataIndex: "stockInfo",
      render: (stockInfo) => stockInfo[0]?.productQuantity,
      renderCsv: (stockInfo) => stockInfo[0]?.productQuantity,
      key: "productQuantity",
    },
    {
      id: 12,
      title: "Reorder QTY",
      dataIndex: "stockInfo",
      render: (stockInfo) => stockInfo[0]?.reorderQuantity,
      renderCsv: (stockInfo) => stockInfo[0]?.reorderQuantity,
      key: "reorderQuantity",
    },
    {
      id: 13,
      title: "",
      key: "action",
      render: ({ id }) => [
        {
          label: <ViewBtn title={"View"} path={`/admin/product/${id}`} />,
          key: "view",
        },
      ],
      csvOff: true,
    },
  ];

  const columnsOtherStock = [
    {
      id: 1,
      title: "Store",
      dataIndex: "store",
      render: (store) => store?.name,
      renderCsv: (store) => store?.name,
      key: "store",
    },
    {
      id: 1,
      title: "Purchase price",
      dataIndex: "productPurchasePrice",
      key: "productPurchasePrice",
    },
    {
      id: 1,
      title: "Sale price",
      dataIndex: "productSalePrice",
      key: "productSalePrice",
    },
    {
      id: 1,
      title: "Quantity",
      dataIndex: "productQuantity",
      key: "productQuantity",
    },
    {
      id: 1,
      title: "Reorder quantity",
      dataIndex: "reorderQuantity",
      key: "reorderQuantity",
    },{
      id: 1,
      title: "Negative Sell Allowed",
      dataIndex: "isNegativeSale",
      key: "isNegativeSale",
      render: (isNegativeSale) => (isNegativeSale === "true" ? "Yes" : "No"),
    }
  ];
  const dispatch = useDispatch();
  const { product, error } = useSelector((state) => state.products);
  const currency = useCurrency();

  useEffect(() => {
    dispatch(loadSingleProduct(id));
    return () => {
      dispatch(clearProduct());
    };
  }, [dispatch, id]);
  const handleOnError = (e) => {
    e.target.src = "/images/default.jpg";
  };

  return (
    <>
      {product ? (
        <div className="space-y-6">
          {/* Header Card */}
          <Card
            className='bg-gray-100'
            title={
              <div className="flex items-center gap-4 ml-5">
                <div className="flex-1">
                  <h1 className='text-xl sm:text-2xl md:text-3xl   mb-2 break-words'>
                    {product?.name}
                  </h1>
                  <div className="flex items-center gap-3 flex-wrap">
                    <span className="text-sm text-gray-600 font-medium">SKU: {product?.sku}</span>
                  </div>
                </div>
              </div>
            }
            extra={
              <Popover
                className='mr-1'
                content={
                  <Menu
                    items={[
                      {
                        label: (
                          <UserPrivateComponent permission={"update-product"}>
                            <Link
                              to={`/admin/product/${product?.id}/update`}
                              className='flex items-center gap-2 cursor-pointer text-xs sm:text-sm hover:text-blue-600 transition-colors'
                            >
                              <EditOutlined className=' rounded-md' />
                              Edit
                            </Link>
                          </UserPrivateComponent>
                        ),
                        key: "edit",
                      },
                      {
                        label: (
                          <CommonDelete
                            values={{
                              id,
                              status: product?.status,
                            }}
                            title={product.status === "true" ? "Hide" : "Show"}
                            permission={"delete-product"}
                            deleteThunk={deleteProduct}
                            loadThunk={loadSingleProduct}
                            query={id}
                            className='bg-white text-black text-xs sm:text-sm'
                          />
                        ),
                        key: "delete",
                      },
                      {
                        label: (
                          <Link
                            to={`/admin/print-barcode/${id}`}
                            className='flex items-center gap-2 rounded text-xs sm:text-sm hover:text-blue-600 transition-colors'
                          >
                            <CiBarcode className='text-[1rem]' />
                            Barcode print
                          </Link>
                        ),
                        key: "barcode",
                      },
                    ]}
                  />
                }
                placement='bottomRight'
                arrow={false}
                trigger='click'
              >
                <BsThreeDotsVertical className='cursor-pointer text-xl hover:text-blue-600 transition-colors' />
              </Popover>
            }
          />

          {/* Main Content Grid */}
          <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
            {/* Left Column - Product Image & Barcode */}
            <div className="xl:col-span-1">
              <Card className="shadow-md hover:shadow-lg transition-shadow h-full bg-white">
                <div className='flex flex-col items-center p-4'>
                  <div className="mb-6 w-full">
                    <h3 className="text-lg font-semibold text-gray-800 mb-3 text-center">Product Image</h3>
                    <div className="relative group w-full max-w-md m-auto">
                      <Image
                        className='rounded-lg w-full aspect-square object-cover border-4 border-gray-100 shadow-md'
                        src={
                          import.meta.env.VITE_APP_API +
                            "/media/view/" +
                            product.productThumbnailImage || "/images/default.jpg"
                        }
                        onError={handleOnError}
                        preview={{
                          mask: <div className="text-white">🔍 Click to view</div>
                        }}
                      />
                    </div>
                  </div>
                  
                  <Divider className="my-4" />
                  
                  <div className='w-full max-w-md'>
                    <h3 className="text-lg font-semibold text-gray-800 mb-3 text-center">Product Barcode</h3>
                    <div className="bg-gray-50 p-4 rounded-lg border border-gray-200 overflow-x-auto">
                      <div className="min-w-[200px] flex justify-center">
                        <GenerateBarcode sku={product?.sku} />
                      </div>
                    </div>
                  </div>
                </div>
              </Card>
            </div>

            {/* Right Column - Product Details */}
            <div className="xl:col-span-2 space-y-6">
              {/* Specifications Card */}
              <Card className="shadow-md hover:shadow-lg transition-shadow bg-white">
                <h2 className='text-xl m-3 font-bold text-gray-800 mb-4 pb-3 border-b-2 flex items-center gap-2'>
                 
                  Product Specifications
                </h2>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-3">
                    <List
                      labelClassName='font-semibold text-gray-700 text-sm'
                      list={[
                        {
                          label: "Manufacturer",
                          value: (
                            <Link
                              to={`/admin/manufacturer/${product?.productGroup.manufacturer?.id}`}
                              className='text-sm text-blue-600 hover:text-blue-800 hover:underline font-medium'
                            >
                              {product?.productGroup.manufacturer?.name}
                            </Link>
                          ),
                        },
                        {
                          label: "Brand",
                          value: (
                            <Link
                              to={`/admin/product-brand/${product?.productGroup.productBrand?.id}`}
                              className='text-sm text-blue-600 hover:text-blue-800 hover:underline font-medium'
                            >
                              {product?.productGroup.productBrand?.name}
                            </Link>
                          ),
                        },
                        {
                          label: "Category",
                          value: (
                            <Link
                              to={`/admin/product-category/${product?.productGroup.subCategory?.productCategory?.id}`}
                              className='text-sm text-blue-600 hover:text-blue-800 hover:underline font-medium'
                            >
                              {
                                product.productGroup.subCategory?.productCategory
                                  ?.name
                              }
                            </Link>
                          ),
                        },
                        {
                          label: "Sub-category",
                          value: (
                            <Link
                              to={`/admin/product-subcategory/${product?.productGroup.subCategory?.id}`}
                              className='text-sm text-blue-600 hover:text-blue-800 hover:underline font-medium'
                            >
                              {product?.productGroup.subCategory?.name}
                            </Link>
                          ),
                        },
                      ]}
                    />
                  </div>
                  <div className="space-y-3">
                    <List
                      labelClassName='font-semibold text-gray-700 text-sm'
                      list={[
                        {
                          label: "UoM",
                          value: (
                            <span className='text-sm font-medium text-gray-800'>
                              {product?.productGroup.uom &&
                                `${product?.productGroup.uomValue}${
                                  product?.productGroup.uom?.name
                                    ? `/${product.productGroup.uom.name}`
                                    : ""
                                }`}
                            </span>
                          ),
                        },
                        product.length && {
                          label: "Length",
                          value: <span className='text-sm font-medium text-gray-800'>{product.length}</span>,
                        },
                        product.width && {
                          label: "Width",
                          value: <span className='text-sm font-medium text-gray-800'>{product.width}</span>,
                        },
                        product.height && {
                          label: "Height",
                          value: <span className='text-sm font-medium text-gray-800'>{product.height}</span>,
                        },
                        product.weight && {
                          label: "Weight",
                          value: <span className='text-sm font-medium text-gray-800'>{product.weight}</span>,
                        },
                      ]}
                    />
                  </div>
                </div>
                {product?.productProductAttributeValue?.length > 0 && (
                  <>
                    <Divider />
                    <div>
                      <h3 className="font-semibold text-gray-700 mb-2">Attributes</h3>
                      <div className="flex flex-wrap gap-2">
                        {product?.productProductAttributeValue?.map((item, index) => (
                          <span key={index} className="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm font-medium">
                            {item.productAttributeValue.productAttribute.name}: {item.productAttributeValue.name}
                          </span>
                        ))}
                      </div>
                    </div>
                  </>
                )}
              </Card>

              {/* Pricing and Stock Cards Grid */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Pricing Card */}
                <Card className="shadow-md hover:shadow-lg transition-shadow bg-gradient-to-br ">
                  <h2 className='text-xl p-3 font-bold text-gray-800 mb-4 pb-3 border-b-2  flex items-center gap-2'>
                   
                    Pricing
                  </h2>
                  <List
                    labelClassName={"font-semibold text-gray-700 text-sm"}
                    list={[
                      {
                        label: "Sale Price",
                        value: (
                          <span className='text-xs '>
                            <span
                              dangerouslySetInnerHTML={{
                                __html: currency?.currencySymbol,
                              }}
                            />
                            {product?.stockInfo[0]?.productSalePrice}
                          </span>
                        ),
                      },
                      {
                        label: "Purchase Price",
                        value: (
                          <span className='text-xs '>
                            <span
                              dangerouslySetInnerHTML={{
                                __html: currency?.currencySymbol,
                              }}
                            />
                            {product?.stockInfo[0]?.productPurchasePrice}
                          </span>
                        ),
                      },
                      {
                        label: "Purchase TAX",
                        value: <span className='text-xs'>{`${
                          product?.productGroup.productPurchaseTax?.percentage
                            ? product?.productGroup.productPurchaseTax?.percentage
                            : 0
                        }%`}</span>,
                      },
                      {
                        label: "Sale TAX",
                        value: <span className='text-xs'>{`${
                          product?.productGroup.productSalesTax?.percentage
                            ? product?.productGroup.productSalesTax?.percentage
                            : 0
                        }%`}</span>,
                      },
                      {
                        label: "Discount",
                        value: <span className='text-xs'>{product?.discount?.value
                          ? `${product?.discount.value}${
                              product?.discount.type == "percentage"
                                ? "%"
                                : " flat"
                            }`
                          : "0%"}</span>,
                      },
                    ]}
                  />
                </Card>

                {/* Stock Card */}
                <Card className="shadow-md hover:shadow-lg transition-shadow bg-gradient-to-br ">
                  <h2 className='text-xl font-bold text-gray-800 mb-4 pb-3 border-b-2 p-3 flex items-center gap-2'>
                    
                    Stock Details
                  </h2>
                  <List
                    labelClassName={"font-semibold text-gray-700 text-sm"}
                    list={[
                      {
                        label: "Quantity",
                        value: (
                          <span className={`text-xs  ${
                            product?.stockInfo[0]?.productQuantity > product?.stockInfo[0]?.reorderQuantity 
                              ? '' 
                              : ''
                          }`}>
                            {product?.stockInfo[0]?.productQuantity}
                          </span>
                        ),
                      },
                      {
                        label: "Reorder Quantity",
                        value: <span className='text-xs  '>{product?.stockInfo[0]?.reorderQuantity}</span>,
                      },
                      {
                        label: "Negative Sell",
                        value: (
                          <span className="text-xs ">
                            {product.stockInfo[0]?.isNegativeSale === "true" ? "Allowed" : "Not Allowed"}
                          </span>
                        ),
                      },
                    ]}
                  />
                </Card>
              </div>

              {/* Item Details Card */}
              <Card className="shadow-md hover:shadow-lg transition-shadow bg-white">
                <h2 className='text-xl p-3 font-bold text-gray-800 mb-4 pb-3 border-b-2  flex items-center gap-2'>
                 
                  Item Details
                </h2>
                <List
                  labelClassName={"font-semibold text-gray-700 text-sm"}
                  list={[
                    {
                      label: (
                        <span className='flex items-center gap-1 text-sm'>
                          SKU
                          <Tooltip
                            placement='topLeft'
                            title='The stock keeping unit of the item'
                          >
                            <BsQuestionCircle className='text-xs text-gray-500' />
                          </Tooltip>
                        </span>
                      ),
                      value: <span className='text-sm font-medium text-gray-800 break-all font-mono bg-gray-100 px-2 py-1 rounded'>{product?.sku}</span>,
                    },
                    product?.eanNo && {
                      label: (
                        <span className='flex items-center gap-1 text-sm'>
                          EAN
                          <Tooltip
                            placement='topLeft'
                            title='Thirteen digit unique number (International Article Number)'
                          >
                            <BsQuestionCircle className='text-xs text-gray-500' />
                          </Tooltip>
                        </span>
                      ),
                      value: <span className='text-sm font-medium text-gray-800 break-all font-mono bg-gray-100 px-2 py-1 rounded'>{product.eanNo}</span>,
                    },
                    product?.upcNo && {
                      label: (
                        <span className='flex items-center gap-1 text-sm'>
                          UPC
                          <Tooltip
                            placement='topLeft'
                            title='Twelve digit unique code (Universal Product Code)'
                          >
                            <BsQuestionCircle className='text-xs text-gray-500' />
                          </Tooltip>
                        </span>
                      ),
                      value: <span className='text-sm font-medium text-gray-800 break-all font-mono bg-gray-100 px-2 py-1 rounded'>{product.upcNo}</span>,
                    },
                    product?.isbnNo && {
                      label: (
                        <span className='flex items-center gap-1 text-sm'>
                          ISBN
                          <Tooltip
                            placement='topLeft'
                            title='Thirteen digit unique commercial book identifier (International Standard Book Number) '
                          >
                            <BsQuestionCircle className='text-xs text-gray-500' />
                          </Tooltip>
                        </span>
                      ),
                      value: <span className='text-sm font-medium text-gray-800 break-all font-mono bg-gray-100 px-2 py-1 rounded'>{product.isbnNo}</span>,
                    },
                    product?.partNo && {
                      label: <span className='text-sm'>Part No</span>,
                      value: <span className='text-sm font-medium text-gray-800 break-all font-mono bg-gray-100 px-2 py-1 rounded'>{product.partNo}</span>,
                    },
                    {
                      label: <span className='text-sm'>Create Date</span>,
                      value: <span className='text-sm font-medium text-gray-800'>{moment(product?.createdAt).format("ll")}</span>,
                    },
                  ]}
                />
              </Card>
            </div>
          </div>

          {/* Gallery Images Card */}
          <Card className="shadow-md hover:shadow-lg transition-shadow bg-white">
            <h2 className='text-xl font-bold text-gray-800 mb-4 flex items-center justify-between'>
              <span className="flex items-center gap-2">
                <span className="w-1 h-6 mt-3 rounded"></span>
                Gallery Images
              </span>
              <AddGalleryImage
                product={{
                  id: product.id,
                  data: product.productGroup?.galleryImage,
                }}
              />
            </h2>
            <div className="bg-gray-50 p-4 rounded-lg">
              <GalleryImageSlider data={product.productGroup.galleryImage} />
            </div>
          </Card>

          {/* Product Variants Card */}
          <Card className="shadow-md hover:shadow-lg transition-shadow bg-white">
            <h2 className='text-xl font-bold text-gray-800 mb-4 flex items-center justify-between'>
              <span className="flex p-3 items-center gap-2">
               
                Product Variants
              </span>
              <BigDrawer title='Add Variant' width={85}>
                <AddVariantToExistingGroup product={product} />
              </BigDrawer>
            </h2>
            <div className='bg-gray-50 p-4 rounded-lg'>
              <Table
                columns={columns}
                data={product.productGroup.products?.filter(
                  (item) => item.id !== product.id
                )}
              />
            </div>
          </Card>

          {/* Description Card */}
          <Card className="shadow-md hover:shadow-lg transition-shadow bg-white">
            <h2 className='text-xl font-bold text-gray-800 mb-4 pb-3   flex items-center gap-2'>
              <span className="w-1 h-6  rounded"></span>
              Product Description
            </h2>
            <div className="bg-gray-50 p-6 rounded-lg">
              <p
                className='text-sm leading-relaxed text-gray-700'
                dangerouslySetInnerHTML={{
                  __html: product?.productGroup.description,
                }}
              ></p>
            </div>
          </Card>

          {/* Other Stock Locations Card */}
          <Card className="shadow-md hover:shadow-lg transition-shadow bg-white">
            <h2 className='text-xl p-3 font-bold text-gray-800 mb-4 pb-3 border-b-2  flex items-center gap-2'>
              
              Stock in Other Stores
            </h2>
            <div className='bg-gray-50 p-4 rounded-lg'>
              <Table
                columns={columnsOtherStock}
                data={product?.stockStoreInfo?.filter(
                  (item) => item.storeId !== product?.stockInfo[0]?.storeId
                )}
              />
            </div>
          </Card>
        </div>
      ) : (
        <Loader />
      )}
    </>
  );
}

export default DetailsProduct;
