"use client"
import Image, { } from "next/image"
import { Phone, Minus, Plus, MapPin,  CircleCheckIcon, Instagram, Car } from "lucide-react"

import { getColors, getFeatures, getImages, getOneProduct, getPrices } from "@/lib/features/web/service"
import { useQuery } from "@tanstack/react-query"
import { ColorProps, FeatureProps, ImageProps, PriceProps, ProductProps } from "@/lib/features/web/type"
import { url } from "@/lib/constant"
import Loading from "../loading"
import { Button } from "@/components/ui/button"
import Categories from "./navbar"
import Header from "./header"
import Footer from "./footer"
import { useEffect, useState } from "react"

import MOMO from "@/img/mtn-logo.jpg"
import VISA from '@/img/master-card.png'

interface Props {
  productId: string;
}

export default function ProductDetail({ productId }: Props) {

    const [imageUrl, setImageUrl] = useState('')
    const [price, setPrice] = useState(0)

    const [size, setSize] = useState('')


    // get product
    const { data, isLoading, error } = useQuery({
      queryKey: ["product-details"],
      queryFn: () => getOneProduct(productId),
    });


    // images
    const { data: imageData, isLoading: isImageLoading, error: errorImage } = useQuery({
      queryKey: ["product-images"],
      queryFn: () => getImages(productId),
    });


    // colors
    const { data: colorData, isLoading: isColorLoading, error: errorColor } = useQuery({
      queryKey: ["product-colors"],
      queryFn: () => getColors(productId),
    });


    // colors
    const { data: featureData, isLoading: isFeatureLoading, error: errorFeature } = useQuery({
      queryKey: ["product-features"],
      queryFn: () => getFeatures(productId),
    });


    // prices
    const { data: priceData, isLoading: isPriceLoading, error: errorPrice } = useQuery({
      queryKey: ["product-prices"],
      queryFn: () => getPrices(productId),
    });

    // Update quotation type
    useEffect(() => {
      if (data?.data) {
        setImageUrl(data?.data?.tbl_productPhoto);
        setPrice(data?.data?.tbl_productPrice)
      }
    }, [data]);




    if (isLoading || isImageLoading || isColorLoading || isFeatureLoading || isPriceLoading) {
        return <Loading />;
    }

    if (error) return "Network error ";
    if (errorImage) return "Network error ";

    if (errorColor) return "Network error ";
    if (errorFeature) return "Network error ";

    if (errorPrice) return "Network error ";

    

    const details: ProductProps = data?.data || null;

    const images: ImageProps[] = imageData?.data || [];

    const colors: ColorProps[] = colorData?.data || [];

    const features: FeatureProps[] = featureData?.data || [];

    const prices: PriceProps[] = priceData?.data || [];


    


  return (
    <main className="min-h-screen">

      {/* Header */}
      <Header />
      



      {/* Navigation */}
      <Categories />



      <div className="container mx-auto px-4 py-8">
      <div className="grid grid-cols-1 md:grid-cols-12 gap-8">
        {/* Thumbnails */}
        <div className="hidden md:flex md:col-span-1 flex-col gap-4">
          {images?.map( (image) => (
            <div key={image?.tbl_prod_imageToken} 
              className="border border-gray-200 p-1 rounded-md"

              onClick={() => setImageUrl(image?.tbl_prod_image)}
            >
              <Image
                src={url+'img/'+image?.tbl_prod_image}
                alt={`iPhone thumbnail`}
                width={100}
                height={100}
                className="w-full h-auto"
              />
            </div>
          ))}
        </div>

        {/* Main Image */}
        <div className="md:col-span-5">
          <div className="border border-gray-200 p-4 rounded-md">
            <center>
              <Image
                src={url+'img/'+imageUrl}
                alt="iPhone 16 Pro Max"
                width={300}
                height={300}
              />
            </center>
          </div>

          {/**********************  Color Options ******************/}
          <div className="flex justify-center gap-4 mt-6">
            {colors?.map( (color) =>(
              <button key={color?.tbl_product_colorToken} 
                className={`w-10 h-10 rounded-full border-2 border-gray-300`}
                style={{backgroundColor: color?.tbl_colorCode?.toLowerCase()}}

                onClick={() => setImageUrl(color?.tbl_product_colorPhoto)}
              >

              </button>

            ))}
          </div>
        </div>

        {/* Product Details */}
        <div className="md:col-span-6">
          <p className="font-bold mb-2" style={{fontSize: 20}}>
            {details?.tbl_productBrand}
          </p>
          <p className="text-red-500 text-xl font-semibold mb-4">
            {'RWF '+new Intl.NumberFormat("en-US", {
                        minimumFractionDigits: 0,
                        maximumFractionDigits: 2,
                      }).format( Number(price) )}
          </p>

          <div className="space-y-4 mb-6">
            <div className="flex items-center">
              <span className="font-semibold w-32">Brand:</span>
              <span>{details?.tbl_specificationYear}</span>
            </div>

            <div className="flex items-center">
              <span className="font-semibold w-32">Category:</span>
              <span>{details?.tbl_product_categName}</span>
            </div>

            <div className="flex items-center">
              <span className="font-semibold w-32">Contact store:</span>
              <a href="tel:0788889611" className="flex items-center text-blue-500">
                <Phone className="h-4 w-4 mr-1" />
                0788 889 611
              </a>
            </div>
          </div>

          <div className="mb-6">
            <h3 className="font-semibold mb-3">Storage</h3>
            <div className="flex gap-4">

              {prices?.map( (price) => (
                <button key={price?.tbl_priceToken}  onClick={() => {
                  setPrice(price?.tbl_priceAmt)
                  setSize(price?.tbl_priceToken)
                  }} 
                  className={size === price?.tbl_priceToken ? 
                    `px-4 py-2 border-2 border-blue-500 rounded-md bg-white`: 
                    `px-4 py-2 border border-gray-300 rounded-md bg-white`
                  }
                >
                  {price?.tbl_sizeName}
                </button>
              ))}
              
            </div>
          </div>

          <div className="flex items-center gap-4 mb-6">
            <Button variant="outline" size="icon">
              <Minus className="h-4 w-4" />
            </Button>
            <span className="w-10 text-center">1</span>
            <Button variant="outline" size="icon">
              <Plus className="h-4 w-4" />
            </Button>
            <Button className="bg-blue-500 hover:bg-blue-600">
              <Plus className="h-4 w-4 mr-2" /> Cart
            </Button>
          </div>

          {/*<div className="mb-6">
            <h3 className="font-semibold mb-3">Generation</h3>
            <div className="inline-block px-4 py-2 bg-gray-100 rounded-md">5G</div>
          </div>  */}
        </div>
      </div>

      {/* Specifications */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-8 mt-12">
        <div className="space-y-6">
          <div className="flex items-start gap-4">
            <div className="bg-blue-100 p-2 rounded-md">
              <MapPin className="h-6 w-6 text-blue-500" />
            </div>
            <div>
              <h3 className="font-semibold">Makuza Peace plaza</h3>
            </div>
          </div>

          <div className="flex items-start gap-4">
            <div className="bg-blue-100 p-2 rounded-md">
              <svg className="h-6 w-6 text-blue-500" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect x="2" y="4" width="20" height="16" rx="2" stroke="currentColor" strokeWidth="2" />
                <path d="M8 12H16" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
              </svg>
            </div>
            <div>
              <h3 className="font-semibold">Payment method</h3>
              <div className="flex gap-2 mt-2">
                <div className="w-full">
                  <Image src={MOMO} height={40} width={40} alt=""  />
                </div>
                <div className="w-full">
                  <Image src={VISA} height={60} width={60} alt=""  />
                </div>

              </div>
            </div>
          </div>

          <div className="flex items-start gap-4">

            <div className="bg-blue-100 p-2 rounded-md">
              <svg className="h-6 w-6 text-blue-500" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" />
                <path
                  d="M12 8V12L15 15"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            </div>

            <div>
              <h3 className="font-semibold">Contact</h3>
                <a href="tel:0788889611" className="flex items-center text-blue-500">
                <Phone className="h-4 w-4 mr-1" />
                0788 889 611
              </a>
            </div>

          </div>


          <div className="flex items-start gap-4">
            
            <div className="bg-blue-100 p-2 rounded-md">
              <Instagram className="h-4 w-4 mr-1" />
            </div>


            <div>
              <h3 className="font-semibold">Social media</h3>
                <a href="https://www.instagram.com/kigaliphones_kt" target="blank" className="flex items-center text-blue-500">
                <Instagram className="h-4 w-4 mr-1" />
                kigaliphones_kt
              </a>
            </div>

          </div>

          <div className="flex items-start gap-4">
            <div className="bg-blue-100 p-2 rounded-md">
              <Car />
            </div>
            <div>
              <h3 className="font-semibold">Fre delivery</h3>
              <p></p>
            </div>
          </div>

          <div className="flex items-start gap-4">
            <div className="bg-blue-100 p-2 rounded-md">
              <Image src={MOMO} height={40} width={40} alt=""  />
            </div>
            <div>
              <h3 className="font-semibold">MOMO Code</h3>
              <p>001271</p>
            </div>
          </div>

        </div>

        <div className="space-y-6">


          {features?.map( (feature)  => (

          <div className="flex items-start gap-4" key={feature?.tbl_prod_featureToken}>
            <div className="bg-blue-100 p-2 rounded-md">
              <CircleCheckIcon className="text-blue-500" />
              {/*<svg className="h-6 w-6 text-blue-500" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M12 16C14.2091 16 16 14.2091 16 12C16 9.79086 14.2091 8 12 8C9.79086 8 8 9.79086 8 12C8 14.2091 9.79086 16 12 16Z"
                  stroke="currentColor"
                  strokeWidth="2"
                />
                <path d="M3 12H8M16 12H21" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
              </svg>*/}
            </div>
            <div>
              <h3 className="font-semibold">{feature?.tbl_featureName}</h3>
              <p>{feature?.tbl_prod_featureDesc}</p>
            </div>
          </div>
          ))}




        </div>
      </div>
    </div>

      <br />


      {/* WhatsApp Chat Button */}
      <Footer />
    </main>
  )
}
