import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Button } from './ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Textarea } from './ui/textarea';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from './ui/dialog';
import { useToast } from '../hooks/use-toast';
import { CreditCard, Gift, Star, Crown, Zap } from 'lucide-react';

const BACKEND_URL = process.env.REACT_APP_BACKEND_URL;
const API = `${BACKEND_URL}/api`;

// Main Payment Button Component
export const PaymentButton = ({ 
  packageId, 
  targetId, 
  buttonText = "Subscribe", 
  variant = "default",
  className = "",
  icon: Icon = CreditCard,
  disabled = false 
}) => {
  const [isProcessing, setIsProcessing] = useState(false);
  const { toast } = useToast();

  const handlePayment = async () => {
    if (disabled) return;
    
    setIsProcessing(true);
    try {
      const originUrl = window.location.origin;
      
      const response = await axios.post(`${API}/payments/checkout/session`, {
        package_id: packageId,
        target_id: targetId,
        origin_url: originUrl,
        metadata: {
          source: 'web_app',
          page: window.location.pathname
        }
      });

      if (response.data.url) {
        window.location.href = response.data.url;
      } else {
        throw new Error('No payment URL received');
      }
    } catch (error) {
      console.error('Payment error:', error);
      toast({
        title: "Payment Error",
        description: error.response?.data?.detail || "Failed to start payment process",
        variant: "destructive",
      });
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <Button
      variant={variant}
      className={className}
      onClick={handlePayment}
      disabled={disabled || isProcessing}
    >
      <Icon className="w-4 h-4 mr-2" />
      {isProcessing ? 'Processing...' : buttonText}
    </Button>
  );
};

// Writer Subscription Tiers Component
export const WriterSubscriptionTiers = ({ writerId, writerName }) => {
  const [tiers] = useState([
    {
      packageId: 'writer_basic',
      name: 'Basic Support',
      price: '$5.00',
      description: 'Support the writer and get basic perks',
      benefits: [
        'Early access to chapters',
        'Behind-the-scenes content',
        'Monthly writer updates'
      ],
      color: 'from-blue-500 to-blue-600',
      icon: Star
    },
    {
      packageId: 'writer_premium', 
      name: 'Premium Support',
      price: '$15.00',
      description: 'Premium support with exclusive content',
      benefits: [
        'Everything from Basic',
        'Exclusive premium chapters',
        'Direct messaging with writer',
        'Monthly video calls',
        'Input on story direction'
      ],
      color: 'from-purple-500 to-purple-600',
      icon: Crown,
      popular: true
    },
    {
      packageId: 'writer_vip',
      name: 'VIP Support',
      price: '$30.00', 
      description: 'Ultimate support with all perks',
      benefits: [
        'Everything from Premium',
        'Character naming rights',
        'Custom short stories',
        'One-on-one consultations',
        'Advance copies of published works'
      ],
      color: 'from-gold-500 to-yellow-600',
      icon: Zap
    }
  ]);

  return (
    <div className="grid md:grid-cols-3 gap-6">
      {tiers.map((tier) => {
        const IconComponent = tier.icon;
        return (
          <Card 
            key={tier.packageId} 
            className={`relative rounded-xl bg-black/60 border-white/20 ${
              tier.popular ? 'ring-2 ring-purple-500 scale-105' : ''
            }`}
          >
            {tier.popular && (
              <div className="absolute -top-3 left-1/2 transform -translate-x-1/2">
                <span className="bg-purple-500 text-white px-4 py-1 rounded-full text-xs font-medium">
                  Most Popular
                </span>
              </div>
            )}
            
            <CardHeader className="text-center">
              <div className={`w-12 h-12 mx-auto mb-4 rounded-full bg-gradient-to-r ${tier.color} flex items-center justify-center`}>
                <IconComponent className="w-6 h-6 text-white" />
              </div>
              <CardTitle className="text-white text-xl">{tier.name}</CardTitle>
              <CardDescription className="text-gray-300">{tier.description}</CardDescription>
              <div className="text-3xl font-bold text-white mt-2">
                {tier.price}<span className="text-sm text-gray-400">/month</span>
              </div>
            </CardHeader>
            
            <CardContent className="space-y-4">
              <ul className="space-y-2">
                {tier.benefits.map((benefit, index) => (
                  <li key={index} className="flex items-start text-sm text-gray-300">
                    <span className="text-green-400 mr-2">✓</span>
                    {benefit}
                  </li>
                ))}
              </ul>
              
              <PaymentButton
                packageId={tier.packageId}
                targetId={writerId}
                buttonText={`Subscribe for ${tier.price}/mo`}
                variant={tier.popular ? "default" : "outline"}
                className={`w-full ${tier.popular ? 'bg-purple-600 hover:bg-purple-700' : 'border-white/30 text-white hover:bg-white/10'}`}
                icon={tier.icon}
              />
            </CardContent>
          </Card>
        );
      })}
    </div>
  );
};

// Tip Component
export const TipWriter = ({ writerId, writerName }) => {
  const [showTipDialog, setShowTipDialog] = useState(false);
  const [customAmount, setCustomAmount] = useState('');
  const [tipMessage, setTipMessage] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const { toast } = useToast();

  const predefinedTips = [
    { packageId: 'tip_small', label: '$3', amount: 3.00 },
    { packageId: 'tip_medium', label: '$10', amount: 10.00 },  
    { packageId: 'tip_large', label: '$25', amount: 25.00 }
  ];

  const handleCustomTip = async () => {
    const amount = parseFloat(customAmount);
    if (!amount || amount < 1 || amount > 1000) {
      toast({
        title: "Invalid Amount",
        description: "Please enter a tip amount between $1.00 and $1000.00",
        variant: "destructive",
      });
      return;
    }

    setIsProcessing(true);
    try {
      const originUrl = window.location.origin;
      
      const response = await axios.post(`${API}/payments/tip/session`, {
        writer_id: writerId,
        amount: amount,
        message: tipMessage,
        origin_url: originUrl
      });

      if (response.data.url) {
        window.location.href = response.data.url;
      } else {
        throw new Error('No payment URL received');
      }
    } catch (error) {
      console.error('Tip error:', error);
      toast({
        title: "Tip Error", 
        description: error.response?.data?.detail || "Failed to process tip",
        variant: "destructive",
      });
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <>
      <Button
        variant="outline"
        onClick={() => setShowTipDialog(true)}
        className="border-white/30 text-white hover:bg-white/10"
      >
        <Gift className="w-4 h-4 mr-2" />
        Tip Writer
      </Button>

      <Dialog open={showTipDialog} onOpenChange={setShowTipDialog}>
        <DialogContent className="bg-black border-white/20 text-white">
          <DialogHeader>
            <DialogTitle>Tip {writerName}</DialogTitle>
            <DialogDescription className="text-gray-400">
              Show your appreciation with a tip
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4">
            {/* Predefined tip amounts */}
            <div>
              <Label className="text-white">Quick tip amounts:</Label>
              <div className="grid grid-cols-3 gap-2 mt-2">
                {predefinedTips.map((tip) => (
                  <PaymentButton
                    key={tip.packageId}
                    packageId={tip.packageId}
                    targetId={writerId}
                    buttonText={tip.label}
                    variant="outline"
                    className="border-white/30 text-white hover:bg-white/10"
                    icon={Gift}
                  />
                ))}
              </div>
            </div>

            {/* Custom tip amount */}
            <div>
              <Label htmlFor="customAmount" className="text-white">Custom amount ($1 - $1000):</Label>
              <Input
                id="customAmount"
                type="number"
                min="1"
                max="1000"
                step="0.01"
                placeholder="0.00"
                value={customAmount}
                onChange={(e) => setCustomAmount(e.target.value)}
                className="bg-white/10 border-white/20 text-white"
              />
            </div>

            {/* Optional message */}
            <div>
              <Label htmlFor="tipMessage" className="text-white">Message (optional):</Label>
              <Textarea
                id="tipMessage"
                placeholder="Thank you for your amazing work!"
                value={tipMessage}
                onChange={(e) => setTipMessage(e.target.value)}
                className="bg-white/10 border-white/20 text-white"
                maxLength={500}
              />
              <div className="text-xs text-gray-400 mt-1">
                {tipMessage.length}/500 characters
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowTipDialog(false)}
              className="border-white/30 text-white hover:bg-white/10"
            >
              Cancel
            </Button>
            <Button
              onClick={handleCustomTip}
              disabled={!customAmount || isProcessing}
              className="bg-green-600 hover:bg-green-700 text-white"
            >
              {isProcessing ? 'Processing...' : `Tip $${customAmount || '0.00'}`}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
};

// Premium Membership Component
export const PremiumMembership = () => {
  const premiumPackages = [
    {
      packageId: 'site_premium_monthly',
      name: 'Monthly Premium',
      price: '$9.99',
      period: '/month',
      description: 'Get premium access to all content',
      popular: false
    },
    {
      packageId: 'site_premium_yearly', 
      name: 'Yearly Premium',
      price: '$99.99',
      period: '/year',
      description: 'Best value - 2 months free!',
      popular: true,
      savings: 'Save $20'
    }
  ];

  return (
    <div className="grid md:grid-cols-2 gap-6">
      {premiumPackages.map((pkg) => (
        <Card 
          key={pkg.packageId}
          className={`rounded-xl bg-black/60 border-white/20 ${
            pkg.popular ? 'ring-2 ring-gold-500' : ''
          }`}
        >
          {pkg.popular && (
            <div className="bg-gold-500 text-black text-center py-2 rounded-t-xl">
              <span className="font-medium text-sm">{pkg.savings}</span>
            </div>
          )}
          
          <CardHeader className="text-center">
            <CardTitle className="text-white text-xl">{pkg.name}</CardTitle>
            <CardDescription className="text-gray-300">{pkg.description}</CardDescription>
            <div className="text-3xl font-bold text-white mt-2">
              {pkg.price}<span className="text-sm text-gray-400">{pkg.period}</span>
            </div>
          </CardHeader>
          
          <CardContent>
            <PaymentButton
              packageId={pkg.packageId}
              buttonText={`Get ${pkg.name}`}
              variant={pkg.popular ? "default" : "outline"}
              className={`w-full ${pkg.popular ? 'bg-gold-600 hover:bg-gold-700' : 'border-white/30 text-white hover:bg-white/10'}`}
              icon={Crown}
            />
          </CardContent>
        </Card>
      ))}
    </div>
  );
};

// Chapter Purchase Component
export const ChapterPurchase = ({ chapterId, chapterTitle, price = "2.99" }) => {
  return (
    <Card className="rounded-xl bg-black/60 border-white/20">
      <CardHeader>
        <CardTitle className="text-white text-lg">Unlock Chapter</CardTitle>
        <CardDescription className="text-gray-300">
          Purchase "{chapterTitle}" to continue reading
        </CardDescription>
      </CardHeader>
      <CardContent>
        <div className="flex items-center justify-between mb-4">
          <span className="text-white">Chapter access</span>
          <span className="text-xl font-bold text-white">${price}</span>
        </div>
        <PaymentButton
          packageId="chapter_single"
          targetId={chapterId}
          buttonText={`Buy for $${price}`}
          className="w-full bg-blue-600 hover:bg-blue-700 text-white"
          icon={CreditCard}
        />
      </CardContent>
    </Card>
  );
};

// Payment Success Component  
export const PaymentSuccess = () => {
  const [paymentStatus, setPaymentStatus] = useState('checking');
  const [paymentDetails, setPaymentDetails] = useState(null);
  const { toast } = useToast();

  useEffect(() => {
    // Get session ID from URL
    const urlParams = new URLSearchParams(window.location.search);
    const sessionId = urlParams.get('session_id');
    
    if (sessionId) {
      pollPaymentStatus(sessionId);
    } else {
      setPaymentStatus('error');
    }
  }, []);

  const pollPaymentStatus = async (sessionId, attempts = 0) => {
    const maxAttempts = 5;
    const pollInterval = 2000; // 2 seconds

    if (attempts >= maxAttempts) {
      setPaymentStatus('timeout');
      return;
    }

    try {
      const response = await axios.get(`${API}/payments/status/${sessionId}`);
      const data = response.data;
      
      if (data.payment_status === 'paid') {
        setPaymentStatus('success');
        setPaymentDetails(data);
        toast({
          title: "Payment Successful!",
          description: "Your payment has been processed successfully.",
        });
        return;
      } else if (data.status === 'expired') {
        setPaymentStatus('expired');
        return;
      }

      // Continue polling if still pending
      setTimeout(() => pollPaymentStatus(sessionId, attempts + 1), pollInterval);
    } catch (error) {
      console.error('Error checking payment status:', error);
      setPaymentStatus('error');
    }
  };

  const getStatusContent = () => {
    switch (paymentStatus) {
      case 'checking':
        return (
          <div className="text-center">
            <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-white mx-auto mb-4"></div>
            <h2 className="text-2xl font-bold text-white mb-2">Processing Payment</h2>
            <p className="text-gray-300">Please wait while we confirm your payment...</p>
          </div>
        );
      
      case 'success':
        return (
          <div className="text-center">
            <div className="w-16 h-16 bg-green-500 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <h2 className="text-2xl font-bold text-white mb-2">Payment Successful!</h2>
            <p className="text-gray-300 mb-4">
              Thank you for your payment. Your access has been granted.
            </p>
            {paymentDetails && (
              <div className="bg-black/40 rounded-lg p-4 mb-4">
                <p className="text-sm text-gray-300">
                  Amount: ${(paymentDetails.amount_total / 100).toFixed(2)} {paymentDetails.currency.toUpperCase()}
                </p>
                <p className="text-sm text-gray-300">
                  Type: {paymentDetails.package_type}
                </p>
              </div>
            )}
          </div>
        );
        
      case 'expired':
        return (
          <div className="text-center">
            <div className="w-16 h-16 bg-yellow-500 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
            </div>
            <h2 className="text-2xl font-bold text-white mb-2">Payment Expired</h2>
            <p className="text-gray-300">Your payment session has expired. Please try again.</p>
          </div>
        );
        
      default:
        return (
          <div className="text-center">
            <div className="w-16 h-16 bg-red-500 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </div>
            <h2 className="text-2xl font-bold text-white mb-2">Payment Error</h2>
            <p className="text-gray-300">There was an error processing your payment. Please try again.</p>
          </div>
        );
    }
  };

  return (
    <div className="min-h-screen bg-black flex items-center justify-center p-4">
      <Card className="w-full max-w-md bg-black/60 border-white/20">
        <CardContent className="p-8">
          {getStatusContent()}
          <div className="mt-6 text-center">
            <Button
              onClick={() => window.location.href = '/'}
              className="bg-white text-black hover:bg-gray-200"
            >
              Return Home
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
};