/**
 * Signal Pack Detail Page
 * Full details of a signal pack with stats, performance history, and subscription
 */

import React, { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import {
  ArrowLeft,
  Star,
  Users,
  TrendingUp,
  CheckCircle,
  BarChart2,
  Clock,
  Calendar,
  Shield,
  Zap,
  AlertCircle,
  Loader2,
} from 'lucide-react';
import { useMarketplaceStore } from '../../../stores/marketplaceStore';
import { ReviewCard } from '../components';
import type { SignalPackPricing } from '../../../types/marketplace.types';

export default function SignalPackDetail() {
  const { slug } = useParams<{ slug: string }>();
  const {
    currentSignalPack: pack,
    reviews,
    totalReviews,
    relatedProducts,
    loadingDetail,
    loadingReviews,
    error,
    fetchSignalPackBySlug,
    fetchReviews,
    fetchRelatedProducts,
    subscribeToSignalPack,
    markReviewHelpful,
    resetCurrentProduct,
  } = useMarketplaceStore();

  const [selectedPricing, setSelectedPricing] = useState<SignalPackPricing | null>(null);
  const [subscribing, setSubscribing] = useState(false);

  useEffect(() => {
    if (slug) {
      fetchSignalPackBySlug(slug);
    }
    return () => {
      resetCurrentProduct();
    };
  }, [slug, fetchSignalPackBySlug, resetCurrentProduct]);

  useEffect(() => {
    if (pack) {
      fetchReviews(pack.id, 'signals', { page: 1, pageSize: 5, sortBy: 'helpful' });
      fetchRelatedProducts(pack.id);
      // Set default pricing (monthly or first available)
      const defaultPricing = pack.pricing.find((p) => p.period === 'monthly') || pack.pricing[0];
      setSelectedPricing(defaultPricing);
    }
  }, [pack, fetchReviews, fetchRelatedProducts]);

  const handleSubscribe = async () => {
    if (!pack || !selectedPricing) return;
    setSubscribing(true);
    try {
      await subscribeToSignalPack(pack.id, selectedPricing.id);
      // Show success or redirect
    } catch (err) {
      console.error('Failed to subscribe:', err);
    } finally {
      setSubscribing(false);
    }
  };

  if (loadingDetail) {
    return (
      <div className="flex items-center justify-center min-h-96">
        <Loader2 className="w-10 h-10 text-blue-500 animate-spin" />
      </div>
    );
  }

  if (error || !pack) {
    return (
      <div className="flex flex-col items-center justify-center min-h-96">
        <AlertCircle className="w-12 h-12 text-red-400 mb-4" />
        <h2 className="text-xl font-semibold text-white mb-2">Signal Pack Not Found</h2>
        <p className="text-gray-400 mb-4">{error || 'The requested signal pack does not exist.'}</p>
        <Link
          to="/marketplace"
          className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg"
        >
          Back to Marketplace
        </Link>
      </div>
    );
  }

  const periodLabels: Record<string, string> = {
    monthly: '/month',
    quarterly: '/3 months',
    yearly: '/year',
    lifetime: 'one-time',
  };

  return (
    <div className="space-y-8">
      {/* Back link */}
      <Link
        to="/marketplace"
        className="inline-flex items-center gap-2 text-gray-400 hover:text-white transition-colors"
      >
        <ArrowLeft className="w-4 h-4" />
        Back to Marketplace
      </Link>

      {/* Main Content */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Left Column - Main Info */}
        <div className="lg:col-span-2 space-y-6">
          {/* Header */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
            <div className="flex items-start gap-6">
              {/* Thumbnail */}
              <div className="w-24 h-24 rounded-xl bg-gradient-to-br from-blue-600/20 to-purple-600/20 flex items-center justify-center flex-shrink-0">
                {pack.thumbnailUrl ? (
                  <img
                    src={pack.thumbnailUrl}
                    alt={pack.name}
                    className="w-full h-full object-cover rounded-xl"
                  />
                ) : (
                  <BarChart2 className="w-12 h-12 text-blue-500" />
                )}
              </div>

              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-3 mb-2">
                  <h1 className="text-2xl font-bold text-white">{pack.name}</h1>
                  {pack.hasFreeTrial && (
                    <span className="px-2 py-1 bg-green-500 text-white text-xs font-medium rounded-full flex items-center gap-1">
                      <Zap className="w-3 h-3" />
                      {pack.freeTrialDays} Days Free
                    </span>
                  )}
                </div>

                {/* Provider */}
                <div className="flex items-center gap-3 mb-4">
                  {pack.provider.avatarUrl ? (
                    <img
                      src={pack.provider.avatarUrl}
                      alt={pack.provider.name}
                      className="w-8 h-8 rounded-full"
                    />
                  ) : (
                    <div className="w-8 h-8 rounded-full bg-gray-700 flex items-center justify-center text-gray-400 text-sm">
                      {pack.provider.name.charAt(0)}
                    </div>
                  )}
                  <span className="text-gray-400 flex items-center gap-1">
                    {pack.provider.name}
                    {pack.provider.verified && (
                      <CheckCircle className="w-4 h-4 text-blue-400" />
                    )}
                  </span>
                  <span className="text-gray-600">|</span>
                  <div className="flex items-center gap-1">
                    <Star className="w-4 h-4 text-yellow-400 fill-yellow-400" />
                    <span className="text-white font-medium">{pack.rating.toFixed(1)}</span>
                    <span className="text-gray-500">({pack.totalReviews} reviews)</span>
                  </div>
                </div>

                {/* Description */}
                <p className="text-gray-300">{pack.description}</p>
              </div>
            </div>
          </div>

          {/* Performance Stats */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
            <h2 className="text-lg font-semibold text-white mb-4">Performance Statistics</h2>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="bg-gray-900/50 rounded-lg p-4 text-center">
                <TrendingUp className="w-6 h-6 text-green-400 mx-auto mb-2" />
                <p className="text-2xl font-bold text-green-400">{pack.winRate}%</p>
                <p className="text-sm text-gray-400">Win Rate</p>
              </div>
              <div className="bg-gray-900/50 rounded-lg p-4 text-center">
                <BarChart2 className="w-6 h-6 text-blue-400 mx-auto mb-2" />
                <p className="text-2xl font-bold text-white">+{pack.avgProfitPercent}%</p>
                <p className="text-sm text-gray-400">Avg Profit</p>
              </div>
              <div className="bg-gray-900/50 rounded-lg p-4 text-center">
                <Calendar className="w-6 h-6 text-purple-400 mx-auto mb-2" />
                <p className="text-2xl font-bold text-white">{pack.avgSignalsPerWeek}</p>
                <p className="text-sm text-gray-400">Signals/Week</p>
              </div>
              <div className="bg-gray-900/50 rounded-lg p-4 text-center">
                <Users className="w-6 h-6 text-yellow-400 mx-auto mb-2" />
                <p className="text-2xl font-bold text-white">{pack.totalSubscribers.toLocaleString()}</p>
                <p className="text-sm text-gray-400">Subscribers</p>
              </div>
            </div>
          </div>

          {/* Symbols Covered */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
            <h2 className="text-lg font-semibold text-white mb-4">Symbols Covered</h2>
            <div className="flex flex-wrap gap-2">
              {pack.symbolsCovered.map((symbol) => (
                <span
                  key={symbol}
                  className="px-3 py-1.5 bg-gray-900 text-gray-300 rounded-lg text-sm font-medium"
                >
                  {symbol}
                </span>
              ))}
            </div>
          </div>

          {/* Recent Signals Preview */}
          {pack.recentSignals.length > 0 && (
            <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
              <h2 className="text-lg font-semibold text-white mb-4">Recent Signals (Preview)</h2>
              <div className="space-y-3">
                {pack.recentSignals.slice(0, 5).map((signal) => (
                  <div
                    key={signal.id}
                    className="flex items-center justify-between p-3 bg-gray-900/50 rounded-lg"
                  >
                    <div className="flex items-center gap-3">
                      <span
                        className={`px-2 py-1 text-xs font-medium rounded ${
                          signal.direction === 'long'
                            ? 'bg-green-500/20 text-green-400'
                            : 'bg-red-500/20 text-red-400'
                        }`}
                      >
                        {signal.direction.toUpperCase()}
                      </span>
                      <span className="font-medium text-white">{signal.symbol}</span>
                    </div>
                    <div className="flex items-center gap-4">
                      <span className="text-gray-400 text-sm">
                        Entry: ${signal.entryPrice.toFixed(2)}
                      </span>
                      {signal.status === 'closed' && signal.profitLossPercent !== undefined && (
                        <span
                          className={`font-medium ${
                            signal.profitLossPercent >= 0 ? 'text-green-400' : 'text-red-400'
                          }`}
                        >
                          {signal.profitLossPercent >= 0 ? '+' : ''}
                          {signal.profitLossPercent.toFixed(2)}%
                        </span>
                      )}
                      <span
                        className={`px-2 py-1 text-xs rounded ${
                          signal.status === 'active'
                            ? 'bg-blue-500/20 text-blue-400'
                            : signal.status === 'closed'
                            ? 'bg-gray-500/20 text-gray-400'
                            : 'bg-yellow-500/20 text-yellow-400'
                        }`}
                      >
                        {signal.status}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Reviews Section */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-white">
                Reviews ({totalReviews})
              </h2>
            </div>

            {loadingReviews ? (
              <div className="flex justify-center py-8">
                <Loader2 className="w-6 h-6 text-blue-500 animate-spin" />
              </div>
            ) : reviews.length > 0 ? (
              <div className="space-y-4">
                {reviews.map((review) => (
                  <ReviewCard
                    key={review.id}
                    review={review}
                    onMarkHelpful={markReviewHelpful}
                  />
                ))}
              </div>
            ) : (
              <p className="text-gray-400 text-center py-8">No reviews yet.</p>
            )}
          </div>
        </div>

        {/* Right Column - Subscription */}
        <div className="space-y-6">
          {/* Pricing Card */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6 sticky top-6">
            <h2 className="text-lg font-semibold text-white mb-4">Subscribe</h2>

            {/* Pricing Options */}
            <div className="space-y-3 mb-6">
              {pack.pricing.map((pricing) => (
                <button
                  key={pricing.id}
                  onClick={() => setSelectedPricing(pricing)}
                  className={`w-full p-4 rounded-lg border-2 transition-colors text-left ${
                    selectedPricing?.id === pricing.id
                      ? 'border-blue-500 bg-blue-500/10'
                      : 'border-gray-700 hover:border-gray-600'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-medium text-white capitalize">{pricing.period}</p>
                      {pricing.discountPercent && (
                        <p className="text-sm text-green-400">
                          Save {pricing.discountPercent}%
                        </p>
                      )}
                    </div>
                    <div className="text-right">
                      <p className="text-xl font-bold text-white">
                        ${pricing.priceUsd}
                        <span className="text-sm font-normal text-gray-400">
                          {periodLabels[pricing.period]}
                        </span>
                      </p>
                      {pricing.originalPriceUsd && (
                        <p className="text-sm text-gray-500 line-through">
                          ${pricing.originalPriceUsd}
                        </p>
                      )}
                    </div>
                  </div>
                  {pricing.isPopular && (
                    <span className="inline-block mt-2 px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded-full">
                      Most Popular
                    </span>
                  )}
                </button>
              ))}
            </div>

            {/* Subscribe Button */}
            <button
              onClick={handleSubscribe}
              disabled={subscribing || !selectedPricing}
              className="w-full py-3 bg-blue-600 hover:bg-blue-500 text-white font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {subscribing ? (
                <Loader2 className="w-5 h-5 animate-spin" />
              ) : (
                <>
                  Subscribe Now
                  {pack.hasFreeTrial && (
                    <span className="text-sm opacity-80">
                      ({pack.freeTrialDays} days free)
                    </span>
                  )}
                </>
              )}
            </button>

            {/* Trust Signals */}
            <div className="mt-6 pt-6 border-t border-gray-700 space-y-3">
              <div className="flex items-center gap-3 text-sm text-gray-400">
                <Shield className="w-5 h-5 text-green-400" />
                <span>7-day money-back guarantee</span>
              </div>
              <div className="flex items-center gap-3 text-sm text-gray-400">
                <Clock className="w-5 h-5 text-blue-400" />
                <span>Cancel anytime</span>
              </div>
              <div className="flex items-center gap-3 text-sm text-gray-400">
                <CheckCircle className="w-5 h-5 text-purple-400" />
                <span>Instant access to all signals</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
