import React, { useState } from 'react';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Card } from '../ui/card';
import { Product, ProductLicense } from '../../types';
import { UserCard } from '@/components/user/UserCard';
import {
  ArrowLeft,
  ShoppingCart,
  Heart,
  Share2,
  Play,
  Pause,
  Star,
  Layers,
} from 'lucide-react';
import { LicenceCard } from './LicenceCard';
import { LicenceDetailsModal } from './modals/LicenceDetailsModal';
import { ReviewProductModal } from './modals/ReviewProductModal';
import { useToast } from '../../context/ToastContext';

interface ProductDetailViewProps {
  product: Product;
  onBack: () => void;
  onAddToCart: (product: Product, license?: ProductLicense) => void;
  similarProducts: Product[];
}

export const ProductDetailView: React.FC<ProductDetailViewProps> = ({
  product,
  onBack,
  onAddToCart,
  similarProducts,
}) => {
  const { addToast } = useToast();
  const [activeImage, setActiveImage] = useState(product.coverUrl);
  const [isPlaying, setIsPlaying] = useState(false);
  const [selectedLicenseId, setSelectedLicenseId] = useState<string>(
    product.licenses?.[0]?.id || '',
  );
  const [showLicenseInfo, setShowLicenseInfo] = useState<ProductLicense | null>(
    null,
  );
  const [showReviewModal, setShowReviewModal] = useState(false);

  const selectedLicense = product.licenses?.find(
    (l: ProductLicense) => l.id === selectedLicenseId,
  );

  const handleReviewSubmit = (_rating: number, _comment: string) => {
    addToast('Review submitted for moderation', 'success');
  };

  return (
    <div className="animate-fadeIn pb-20">
      {/* Header / Breadcrumb */}
      <div className="mb-6 flex items-center gap-4">
        <Button
          variant="ghost"
          onClick={onBack}
          icon={<ArrowLeft className="w-4 h-4" />}
        >
          Back to Market
        </Button>
        <span className="text-gray-500 text-sm">
          / {product.type} / {product.title}
        </span>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 mb-12">
        {/* Left Column: Visuals */}
        <div className="lg:col-span-5 space-y-4">
          <div className="relative aspect-square rounded-2xl overflow-hidden bg-black border border-kodo-steel shadow-2xl group">
            <img src={activeImage} className="w-full h-full object-cover" />
            <div className="absolute inset-0 bg-black/20 group-hover:bg-transparent transition-colors"></div>

            {/* Audio Preview Overlay */}
            <div className="absolute bottom-6 left-6 right-6 bg-black/60 backdrop-blur-md rounded-xl p-3 flex items-center gap-4 border border-white/10">
              <button
                onClick={() => setIsPlaying(!isPlaying)}
                className="w-10 h-10 rounded-full bg-kodo-cyan text-black flex items-center justify-center hover:scale-110 transition-transform"
              >
                {isPlaying ? (
                  <Pause className="w-5 h-5 fill-current" />
                ) : (
                  <Play className="w-5 h-5 fill-current ml-1" />
                )}
              </button>
              <div className="flex-1">
                <div className="text-xs font-bold text-white mb-1">
                  Audio Preview
                </div>
                <div className="h-1 bg-gray-600 rounded-full overflow-hidden">
                  <div className="h-full bg-kodo-cyan w-1/3 animate-pulse"></div>
                </div>
              </div>
            </div>
          </div>

          {/* Thumbnails */}
          {product.images && product.images.length > 1 && (
            <div className="flex gap-4 overflow-x-auto pb-2">
              {product.images.map((img: string, i: number) => (
                <div
                  key={i}
                  onClick={() => setActiveImage(img)}
                  className={`w-20 h-20 rounded-lg overflow-hidden cursor-pointer border-2 transition-all ${activeImage === img ? 'border-kodo-cyan' : 'border-transparent opacity-60 hover:opacity-100'}`}
                >
                  <img src={img} className="w-full h-full object-cover" />
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Right Column: Info & Purchase */}
        <div className="lg:col-span-7 flex flex-col">
          <div className="mb-6">
            <div className="flex justify-between items-start mb-2">
              <Badge label={product.type} variant="terminal" className="mb-2" />
              <div className="flex gap-2">
                <Button
                  variant="ghost"
                  size="icon"
                  className="border border-kodo-steel text-gray-400 hover:text-kodo-magenta"
                >
                  <Heart className="w-5 h-5" />
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  className="border border-kodo-steel text-gray-400 hover:text-white"
                >
                  <Share2 className="w-5 h-5" />
                </Button>
              </div>
            </div>
            <h1 className="text-4xl md:text-5xl font-display font-bold text-white mb-2 leading-tight">
              {product.title}
            </h1>
            <div className="flex items-center gap-4 text-sm text-gray-400">
              <span className="flex items-center gap-1 text-kodo-gold font-bold">
                <Star className="w-4 h-4 fill-current" /> {product.rating}
              </span>
              <span>•</span>
              <span>{product.reviewCount || 0} reviews</span>
              <span>•</span>
              <span className="text-kodo-cyan">{product.author}</span>
            </div>
          </div>

          {/* Metadata Grid */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
            <div className="bg-kodo-ink p-3 rounded border border-kodo-steel/50">
              <div className="text-[10px] text-gray-500 uppercase font-bold">
                BPM
              </div>
              <div className="text-white font-mono">{product.bpm || '-'}</div>
            </div>
            <div className="bg-kodo-ink p-3 rounded border border-kodo-steel/50">
              <div className="text-[10px] text-gray-500 uppercase font-bold">
                Key
              </div>
              <div className="text-white font-mono">{product.key || '-'}</div>
            </div>
            <div className="bg-kodo-ink p-3 rounded border border-kodo-steel/50">
              <div className="text-[10px] text-gray-500 uppercase font-bold">
                Genre
              </div>
              <div className="text-white truncate">{product.genre || '-'}</div>
            </div>
            <div className="bg-kodo-ink p-3 rounded border border-kodo-steel/50">
              <div className="text-[10px] text-gray-500 uppercase font-bold">
                Size
              </div>
              <div className="text-white">{product.size || '-'}</div>
            </div>
          </div>

          {/* Licenses */}
          <div className="mb-8">
            <h3 className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4 flex items-center gap-2">
              <Layers className="w-4 h-4" /> Select License
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {product.licenses?.map((license: ProductLicense) => (
                <LicenceCard
                  key={license.id}
                  license={license}
                  selected={selectedLicenseId === license.id}
                  onSelect={(l) => setSelectedLicenseId(l.id)}
                  onInfo={(l) => setShowLicenseInfo(l)}
                />
              ))}
            </div>
          </div>

          {/* Sticky Action Bar (Mobile optimized) */}
          <div className="mt-auto bg-kodo-graphite border border-kodo-steel p-4 rounded-xl shadow-2xl flex flex-col md:flex-row gap-4 items-center">
            <div className="flex-1">
              <div className="text-xs text-gray-400 uppercase font-bold">
                Total Price
              </div>
              <div className="text-3xl font-mono font-bold text-white">
                ${selectedLicense?.price || product.price}
              </div>
            </div>
            <Button
              variant="primary"
              size="lg"
              className="w-full md:w-auto px-8"
              icon={<ShoppingCart className="w-5 h-5" />}
              onClick={() => onAddToCart(product, selectedLicense)}
            >
              ADD TO CART
            </Button>
          </div>
        </div>
      </div>

      {/* Bottom Content: Desc & Reviews */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 space-y-8">
          <Card variant="default">
            <h3 className="font-bold text-white text-xl mb-4 border-b border-kodo-steel pb-2">
              Description
            </h3>
            <div className="prose prose-invert max-w-none text-gray-300">
              <p>{product.description}</p>
              <ul>
                {product.features?.map((f: string, i: number) => (
                  <li key={i}>{f}</li>
                ))}
              </ul>
            </div>
          </Card>

          <Card variant="default">
            <div className="flex justify-between items-center mb-6 border-b border-kodo-steel pb-2">
              <h3 className="font-bold text-white text-xl">Reviews</h3>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setShowReviewModal(true)}
              >
                Write a Review
              </Button>
            </div>

            <div className="space-y-6">
              {product.reviews?.map((review: any) => (
                <div key={review.id} className="flex gap-4">
                  <img
                    src={review.avatar}
                    className="w-10 h-10 rounded-full bg-gray-700"
                  />
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <span className="font-bold text-white">
                        {review.username}
                      </span>
                      <div className="flex text-kodo-gold text-xs">
                        {[...Array(5)].map((_, i) => (
                          <Star
                            key={i}
                            className={`w-3 h-3 ${i < review.rating ? 'fill-current' : 'text-gray-600'}`}
                          />
                        ))}
                      </div>
                      <span className="text-xs text-gray-500">
                        {review.date}
                      </span>
                    </div>
                    <p className="text-sm text-gray-300">{review.comment}</p>
                  </div>
                </div>
              ))}
              {(!product.reviews || product.reviews.length === 0) && (
                <p className="text-gray-500 italic text-center py-4">
                  No reviews yet. Be the first!
                </p>
              )}
            </div>
          </Card>
        </div>

        <div className="space-y-8">
          {/* Seller Info */}
          <UserCard
            user={{
              username: product.author,

              // fullName: product.author, // Removed because it doesn't exist on User type
              avatar: 'https://picsum.photos/id/100/200/200',
              stats: { followers: 1200, tracks: 45, following: 0, plays: 0 },
            }}
            onView={() => addToast('Viewing Seller Profile')}
          />

          {/* More from Seller */}
          <div>
            <h3 className="font-bold text-white text-sm uppercase tracking-wider mb-4">
              More from {product.author}
            </h3>
            <div className="space-y-4">
              {similarProducts.slice(0, 3).map((p) => (
                <div
                  key={p.id}
                  className="flex gap-3 cursor-pointer group"
                  onClick={() => addToast('Navigating to product...')}
                >
                  <img
                    src={p.coverUrl}
                    className="w-16 h-16 rounded bg-gray-800 object-cover"
                  />
                  <div>
                    <h4 className="font-bold text-white text-sm group-hover:text-kodo-cyan">
                      {p.title}
                    </h4>
                    <p className="text-xs text-gray-500">{p.type}</p>
                    <p className="text-xs font-mono text-white mt-1">
                      ${p.price}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Modals */}
      {showLicenseInfo && (
        <LicenceDetailsModal
          license={showLicenseInfo}
          onClose={() => setShowLicenseInfo(null)}
          onAddToCart={() => {
            setSelectedLicenseId(showLicenseInfo.id);
            onAddToCart(product, showLicenseInfo);
          }}
        />
      )}
      {showReviewModal && (
        <ReviewProductModal
          productTitle={product.title}
          onClose={() => setShowReviewModal(false)}
          onSubmit={handleReviewSubmit}
        />
      )}
    </div>
  );
};
