"use client";
import React, { useContext, useState } from "react";
import { Plus, Minus, FileText } from "lucide-react"; // Added FileText icon
import ProductContext from "@/app/contexts/productContext";
import { backendUrl } from "@/utils/axios";
import { useCurrency } from "@/app/contexts/currencyContext";
import Link from "next/link";
import Image from "next/image";

function ProductDetails({ productId }) {
  const [quantity, setQuantity] = useState(1);
  const [selectedSize, setSelectedSize] = useState(null);
  const [selectedDesign, setSelectedDesign] = useState(null);
  const [termsAccepted, setTermsAccepted] = useState(false);
  const [showCertificate, setShowCertificate] = useState(false);
  const { products, cartFn } = useContext(ProductContext);
  const { formatPrice, isLoading } = useCurrency();

  const product = products?.find((pr) => pr.id == productId);
  React.useEffect(() => {
    if (product && product.variants?.length > 0) {
      setSelectedSize(product.variants[0]?.size?.size_name || "");
      setSelectedDesign(product.design_associations?.[0]?.design?.id || "");
    }
  }, [product]);

  if (!product) return null;

  const hasVariants = product.variants?.length > 0;
  const hasDesigns = product.design_associations?.length > 0;
  const hasCertificate = product.certificate && product.certificate !== "NA";

  const selectedVariant = hasVariants
    ? product.variants.find((v) => v.size.size_name === selectedSize)
    : null;

  const currentPrice = selectedVariant?.price || product.price || 0;
  const designPrice = hasDesigns
    ? product.design_associations.find((d) => d.design.id === selectedDesign)
        ?.design.design_price || 0
    : 0;

  const totalPrice = currentPrice + designPrice;
  
  const handleViewCertificate = () => {
    setShowCertificate(true);
    // If it's a PDF, open in a new tab
    if (product.certificate.toLowerCase().endsWith('.pdf')) {
      window.open(`${backendUrl}${product.certificate}`, '_blank');
      setShowCertificate(false);
    }
  };

  return (
    <div className="max-w-xl p-6 space-y-6">
      <div className="flex justify-between items-start">
        <h1 className="text-2xl font-semibold">{product.product_name}</h1>
      </div>

      {hasVariants ? (
        <div className="flex items-center">
          <span className="text-2xl text-[#C17A0F]">
            {isLoading ? (
              <span>Loading...</span>
            ) : (
              <span>{formatPrice(totalPrice)}</span>
            )}
          </span>
        </div>
      ) : (
        <div className="text-2xl text-[#C17A0F]">Price on request</div>
      )}

      <div className="space-y-4">
        {hasVariants && (
          <div>
            <h3 className="text-sm mb-2">Select Size</h3>
            <div className="flex space-x-4">
              {product.variants.map((variant) => (
                <button
                  key={variant.size.id}
                  className={`px-4 py-2 border rounded ${
                    selectedSize === variant.size.size_name
                      ? "border-[#C17A0F]"
                      : "border-gray-300"
                  }`}
                  onClick={() => setSelectedSize(variant.size.size_name)}
                >
                  {variant.size.size_name}
                </button>
              ))}
            </div>
          </div>
        )}

        {hasDesigns && (
          <div>
            <h3 className="text-sm mb-2">Select Your Design</h3>
            <div className="grid grid-cols-4 gap-4">
              {product.design_associations.map((design) => (
                <button
                  key={design.id}
                  className={`p-2 border rounded text-center ${
                    selectedDesign === design.design.id
                      ? "border-[#C17A0F]"
                      : "border-gray-300"
                  }`}
                  onClick={() => setSelectedDesign(design.design.id)}
                >
                  <div className="h-12 w-12 mx-auto mb-2 bg-gray-200">
                    <Image
                      src={`${backendUrl}${design.design.design_icon}`}
                      alt={design.design.design_name}
                      width={48}
                      height={48}
                      className="w-full h-full object-cover rounded-full"
                    />
                  </div>
                  <div className="text-sm">{design.design.design_name}</div>
                  <div className="text-sm text-gray-500">
                    {isLoading ? (
                      <span>Loading...</span>
                    ) : (
                      <span>{formatPrice(design.design.design_price)}</span>
                    )}
                  </div>
                </button>
              ))}
            </div>
          </div>
        )}

        <div>
          {product?.product_category?.category_name && (
            <h3 className="text-sm mb-2">
              Category: {product.product_category.category_name}
            </h3>
          )}
          {product?.product_subcategory?.subcategory_name && (
            <p className="text-sm">
              Subcategory: {product.product_subcategory.subcategory_name}
            </p>
          )}
        </div>

        {hasCertificate && (
          <div className="mt-4">
            <button
              onClick={handleViewCertificate}
              className="flex items-center text-blue-600 hover:text-blue-800"
            >
              <FileText className="w-4 h-4 mr-2" />
              View Certificate
            </button>
          </div>
        )}

        {hasVariants && (
          <>
            <div className="flex items-center justify-between border rounded-md p-2 w-32">
              <button
                onClick={() => setQuantity(Math.max(1, quantity - 1))}
                className="p-2"
              >
                <Minus className="w-4 h-4" />
              </button>
              <span>{quantity}</span>
              <button
                onClick={() => setQuantity(quantity + 1)}
                className="p-2"
                disabled={quantity >= selectedVariant?.stock}
              >
                <Plus className="w-4 h-4" />
              </button>
            </div>
            <div className="text-sm">
              Stock:{" "}
              {selectedVariant?.stock > 0 ? "available" : "Not Available"}
            </div>
          </>
        )}
        <div className="text-sm">
          <input
            type="checkbox"
            className="mr-2"
            checked={termsAccepted}
            onChange={(e) => setTermsAccepted(e.target.checked)}
          />
          <span>I agree with the </span>
          <Link href="/policies/terms-of-services" className="text-blue-600">
            terms of services
          </Link>
          <span> and </span>
          <Link href="/policies/refund-policy" className="text-blue-600">
            return And Cancellation policy
          </Link>
        </div>

        {hasVariants && selectedVariant?.stock > 0 ? (
          <button
            onClick={() => cartFn(selectedVariant.id, selectedDesign, quantity)}
            disabled={!termsAccepted}
            className={`w-full py-3 rounded-md ${
              termsAccepted
                ? "bg-[#C17A0F] text-white cursor-pointer"
                : "bg-gray-300 text-gray-500 cursor-not-allowed"
            }`}
          >
            ADD TO CART
          </button>
        ) : (
          <button className="w-full bg-[#C17A0F] text-white py-3 rounded-md">
            REQUEST PRICE
          </button>
        )}

        <div className="mt-8 border-t pt-6">
          <h2 className="text-xl font-semibold mb-4">Product Description</h2>
          <div
            dangerouslySetInnerHTML={{ __html: product.description }}
            className="text-sm prose prose-sm max-w-none"
          />
        </div>
        <div className="mt-8 border-t pt-6">
          <h2 className="text-xl font-semibold mb-4">Beej Mantra</h2>
          <div
            dangerouslySetInnerHTML={{ __html: product.beej_mantra }}
            className="text-sm prose prose-sm max-w-none"
          />
        </div>
      </div>

      {showCertificate && !product.certificate.toLowerCase().endsWith('.pdf') && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white p-4 rounded-lg max-w-4xl max-h-[90vh] overflow-auto">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-xl font-semibold">Product Certificate</h3>
              <button 
                onClick={() => setShowCertificate(false)}
                className="text-gray-500 hover:text-gray-700"
              >
                ✕
              </button>
            </div>
            <div className="flex justify-center">
              <img 
                src={`${backendUrl}${product.certificate}`} 
                alt="Product Certificate" 
                className="max-w-full max-h-[70vh] object-contain"
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default ProductDetails;
