"use client";

import { useState } from "react";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useCartStore } from "@/lib/store";
import { Star, ShoppingCart, Heart, Share2, Minus, Plus, Truck, Shield, RotateCcw } from "lucide-react";
import { toast } from "sonner";

interface Product {
  id: string;
  name: string;
  slug: string;
  description: string;
  price: number;
  salePrice?: number | null;
  images: string;
  stock: number;
  category?: { name: string; slug: string };
  rating?: number;
  reviewCount?: number;
  soldCount?: number;
  isVirtual?: boolean;
}

interface ProductDetailModalProps {
  product: Product | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function ProductDetailModal({ product, open, onOpenChange }: ProductDetailModalProps) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="sr-only">{product?.name || "Product Details"}</DialogTitle>
        </DialogHeader>
        {product && <ProductDetailContent product={product} onOpenChange={onOpenChange} />}
      </DialogContent>
    </Dialog>
  );
}

function ProductDetailContent({ product, onOpenChange }: { product: Product; onOpenChange: (open: boolean) => void }) {
  const [quantity, setQuantity] = useState(1);
  const [selectedImage, setSelectedImage] = useState(0);
  const { addItem, toggleCart } = useCartStore();

  const images = JSON.parse(product.images || "[]");
  const mainImage = images[selectedImage] || images[0] || "/placeholder-product.png";
  const discount = product.salePrice
    ? Math.round(((product.price - product.salePrice) / product.price) * 100)
    : 0;

  const handleAddToCart = () => {
    if (product.stock < 1) {
      toast.error("Product is out of stock");
      return;
    }

    addItem({
      productId: product.id,
      name: product.name,
      price: product.price,
      salePrice: product.salePrice || undefined,
      image: mainImage,
      quantity,
    });
    
    toast.success(`Added ${quantity} to cart`);
    toggleCart();
  };

  const handleBuyNow = () => {
    if (product.stock < 1) {
      toast.error("Product is out of stock");
      return;
    }

    addItem({
      productId: product.id,
      name: product.name,
      price: product.price,
      salePrice: product.salePrice || undefined,
      image: mainImage,
      quantity,
    });
    
    onOpenChange(false);
  };

  return (
    <div className="grid md:grid-cols-2 gap-6">
      {/* Images */}
      <div className="space-y-4">
        <div className="relative aspect-square rounded-lg overflow-hidden bg-muted">
          <Image
            src={mainImage}
            alt={product.name}
            fill
            className="object-cover"
          />
          {discount > 0 && (
            <Badge className="absolute top-2 left-2" variant="destructive">
              -{discount}%
            </Badge>
          )}
        </div>
        {images.length > 1 && (
          <div className="flex gap-2 overflow-x-auto">
            {images.map((img: string, idx: number) => (
              <button
                key={idx}
                onClick={() => setSelectedImage(idx)}
                className={`relative w-20 h-20 rounded-lg overflow-hidden flex-shrink-0 border-2 transition-colors ${
                  selectedImage === idx ? "border-primary" : "border-transparent"
                }`}
              >
                <Image src={img} alt="" fill className="object-cover" />
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Details */}
      <div className="space-y-4">
        {/* Category */}
        {product.category && (
          <span className="text-sm text-muted-foreground">
            {product.category.name}
          </span>
        )}

        {/* Name */}
        <h1 className="text-2xl font-bold">{product.name}</h1>

        {/* Rating & Sold */}
        <div className="flex items-center gap-4">
          {product.rating && product.rating > 0 && (
            <div className="flex items-center gap-1">
              <Star className="h-5 w-5 fill-yellow-400 text-yellow-400" />
              <span className="font-medium">{product.rating.toFixed(1)}</span>
              <span className="text-muted-foreground">({product.reviewCount} reviews)</span>
            </div>
          )}
          {product.soldCount && product.soldCount > 0 && (
            <span className="text-muted-foreground">{product.soldCount} sold</span>
          )}
        </div>

        {/* Price */}
        <div className="flex items-center gap-3">
          <span className="text-3xl font-bold text-primary">
            ৳{(product.salePrice || product.price).toLocaleString()}
          </span>
          {product.salePrice && (
            <span className="text-lg text-muted-foreground line-through">
              ৳{product.price.toLocaleString()}
            </span>
          )}
        </div>

        {/* Stock status */}
        <div className="flex items-center gap-2">
          {product.stock > 0 ? (
            <Badge variant="outline" className="text-green-600 border-green-600">
              In Stock ({product.stock})
            </Badge>
          ) : (
            <Badge variant="outline" className="text-red-600 border-red-600">
              Out of Stock
            </Badge>
          )}
          {product.isVirtual && (
            <Badge variant="secondary">Digital Product</Badge>
          )}
        </div>

        <Separator />

        {/* Quantity */}
        <div className="flex items-center gap-4">
          <span className="font-medium">Quantity:</span>
          <div className="flex items-center border rounded-lg">
            <Button
              variant="ghost"
              size="icon"
              className="h-10 w-10"
              onClick={() => setQuantity(Math.max(1, quantity - 1))}
            >
              <Minus className="h-4 w-4" />
            </Button>
            <span className="w-12 text-center font-medium">{quantity}</span>
            <Button
              variant="ghost"
              size="icon"
              className="h-10 w-10"
              onClick={() => setQuantity(Math.min(product.stock, quantity + 1))}
              disabled={quantity >= product.stock}
            >
              <Plus className="h-4 w-4" />
            </Button>
          </div>
        </div>

        {/* Actions */}
        <div className="flex gap-3">
          <Button
            size="lg"
            className="flex-1"
            onClick={handleAddToCart}
            disabled={product.stock < 1}
          >
            <ShoppingCart className="h-5 w-5 mr-2" />
            Add to Cart
          </Button>
          <Button
            size="lg"
            variant="outline"
            onClick={handleBuyNow}
            disabled={product.stock < 1}
          >
            Buy Now
          </Button>
          <Button size="lg" variant="ghost">
            <Heart className="h-5 w-5" />
          </Button>
          <Button size="lg" variant="ghost">
            <Share2 className="h-5 w-5" />
          </Button>
        </div>

        {/* Features */}
        <div className="grid grid-cols-3 gap-4 pt-4">
          <div className="flex flex-col items-center text-center">
            <Truck className="h-6 w-6 text-muted-foreground mb-1" />
            <span className="text-xs text-muted-foreground">Free Delivery</span>
          </div>
          <div className="flex flex-col items-center text-center">
            <Shield className="h-6 w-6 text-muted-foreground mb-1" />
            <span className="text-xs text-muted-foreground">Secure Payment</span>
          </div>
          <div className="flex flex-col items-center text-center">
            <RotateCcw className="h-6 w-6 text-muted-foreground mb-1" />
            <span className="text-xs text-muted-foreground">7 Day Returns</span>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="md:col-span-2 mt-6">
        <Tabs defaultValue="description">
          <TabsList>
            <TabsTrigger value="description">Description</TabsTrigger>
            <TabsTrigger value="reviews">Reviews ({product.reviewCount || 0})</TabsTrigger>
          </TabsList>
          <TabsContent value="description" className="mt-4">
            <div className="prose prose-sm max-w-none">
              <p className="whitespace-pre-line">{product.description}</p>
            </div>
          </TabsContent>
          <TabsContent value="reviews" className="mt-4">
            <p className="text-muted-foreground">No reviews yet. Be the first to review this product!</p>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}
