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 { Switch } from './ui/switch';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';
import { Badge } from './ui/badge';
import { useToast } from '../hooks/use-toast';
import { 
  DollarSign, 
  CreditCard, 
  Settings, 
  Clock, 
  CheckCircle, 
  XCircle, 
  AlertCircle,
  ArrowUpRight,
  Wallet,
  TrendingUp,
  Calendar,
  FileText
} from 'lucide-react';

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

// Writer Earnings Dashboard Component
export const WriterEarningsDashboard = ({ writerId }) => {
  const [earnings, setEarnings] = useState(null);
  const [balance, setBalance] = useState(null);
  const [withdrawals, setWithdrawals] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);

  const itemsPerPage = 10;
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const { toast } = useToast();

  useEffect(() => {
    fetchEarningsData();
  }, []);

  const fetchEarningsData = async () => {
    try {
      setLoading(true);
      const [earningsRes, balanceRes, withdrawalsRes] = await Promise.all([
        axios.get(`${API}/payments/writer-earnings`, {
          withCredentials: true
        }),
        axios.get(`${API}/payments/writer/balance`, {
          withCredentials: true
        }),
        axios.get(`${API}/payments/writer/withdrawals`, {
          withCredentials: true
        })
      ]);

      setEarnings(earningsRes.data);
      setBalance(balanceRes.data);
      setWithdrawals(withdrawalsRes.data.withdrawals);
    } catch (error) {
      console.error('Error fetching earnings data:', error);
      toast({
        title: "Error",
        description: "Failed to load earnings data",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const formatCurrency = (amount) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
    }).format(amount || 0);
  };

  const getStatusBadge = (status) => {
    const statusConfig = {
      'completed': { color: 'bg-green-600', text: 'Completed', icon: CheckCircle },
      'pending': { color: 'bg-yellow-600', text: 'Pending', icon: Clock },
      'processing': { color: 'bg-blue-600', text: 'Processing', icon: ArrowUpRight },
      'failed': { color: 'bg-red-600', text: 'Failed', icon: XCircle },
      'cancelled': { color: 'bg-gray-600', text: 'Cancelled', icon: XCircle }
    };

    const config = statusConfig[status] || statusConfig['pending'];
    const IconComponent = config.icon;

    return (
      <Badge className={`${config.color} text-white`}>
        <IconComponent className="w-3 h-3 mr-1" />
        {config.text}
      </Badge>
    );
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="animate-pulse space-y-4">
          <div className="h-32 bg-white/10 rounded-xl"></div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="h-24 bg-white/10 rounded-xl"></div>
            <div className="h-24 bg-white/10 rounded-xl"></div>
            <div className="h-24 bg-white/10 rounded-xl"></div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Earnings Overview */}
      <Card className="bg-gradient-to-r from-green-600 to-emerald-700 text-white">
        <CardHeader>
          <CardTitle className="flex items-center">
            <TrendingUp className="w-5 h-5 mr-2" />
            Writer Earnings Overview
          </CardTitle>
          <CardDescription className="text-green-100">
            Your earnings and payout information
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div>
              <p className="text-green-100 text-sm">Available Balance</p>
              <p className="text-3xl font-bold">
                {formatCurrency(balance?.available_balance)}
              </p>
            </div>
            <div>
              <p className="text-green-100 text-sm">Total Earnings</p>
              <p className="text-2xl font-bold">
                {formatCurrency(balance?.net_earnings)}
              </p>
              <p className="text-xs text-green-200">
                After {balance?.platform_fee_percentage}% platform fee
              </p>
            </div>
            <div>
              <p className="text-green-100 text-sm">Total Withdrawn</p>
              <p className="text-2xl font-bold">
                {formatCurrency(balance?.total_withdrawn)}
              </p>
              {balance?.pending_withdrawals > 0 && (
                <p className="text-xs text-yellow-200">
                  {formatCurrency(balance?.pending_withdrawals)} pending
                </p>
              )}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Earnings Breakdown */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <Card className="bg-black/60 border-white/20">
          <CardHeader className="pb-2">
            <CardTitle className="text-white text-sm flex items-center">
              <DollarSign className="w-4 h-4 mr-2" />
              Tips Received
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-2xl font-bold text-white">
              {formatCurrency(earnings?.total_tips)}
            </p>
            <p className="text-xs text-gray-400">
              From {earnings?.recent_tips?.length || 0} supporters
            </p>
          </CardContent>
        </Card>

        <Card className="bg-black/60 border-white/20">
          <CardHeader className="pb-2">
            <CardTitle className="text-white text-sm flex items-center">
              <FileText className="w-4 h-4 mr-2" />
              Chapter Sales
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-2xl font-bold text-white">
              {formatCurrency(earnings?.total_chapter_sales)}
            </p>
            <p className="text-xs text-gray-400">Individual chapter purchases</p>
          </CardContent>
        </Card>

        <Card className="bg-black/60 border-white/20">
          <CardHeader className="pb-2">
            <CardTitle className="text-white text-sm flex items-center">
              <Calendar className="w-4 h-4 mr-2" />
              Subscribers
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-2xl font-bold text-white">
              {earnings?.active_subscribers || 0}
            </p>
            <p className="text-xs text-gray-400">Active monthly subscribers</p>
          </CardContent>
        </Card>
      </div>

      {/* Withdrawal History */}
      <Card className="bg-black/60 border-white/20">
        <CardHeader>
          <CardTitle className="text-white flex items-center justify-between">
            <span className="flex items-center">
              <Wallet className="w-5 h-5 mr-2" />
              Withdrawal History
            </span>
            <WithdrawalRequestButton onWithdrawalComplete={fetchEarningsData} />
          </CardTitle>
        </CardHeader>
        <CardContent>
          {withdrawals.length === 0 ? (
            <div className="text-center py-8">
              <Wallet className="w-12 h-12 text-gray-400 mx-auto mb-4" />
              <p className="text-gray-400">No withdrawals yet</p>
              <p className="text-sm text-gray-500">
                Request your first payout when you have earnings available
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {withdrawals.slice(startIndex, endIndex).map((withdrawal) => (
                <div key={withdrawal.id} className="flex items-center justify-between p-4 border border-white/10 rounded-lg">
                  <div className="flex items-center space-x-4">
                    <div className="w-10 h-10 bg-green-600 rounded-full flex items-center justify-center">
                      <ArrowUpRight className="w-5 h-5 text-white" />
                    </div>
                    <div>
                      <p className="text-white font-medium">
                        {formatCurrency(withdrawal.amount)}
                      </p>
                      <p className="text-sm text-gray-400">
                        {new Date(withdrawal.requested_at).toLocaleDateString()}
                        {withdrawal.notes && ` • ${withdrawal.notes}`}
                      </p>
                    </div>
                  </div>
                  <div className="text-right">
                    {getStatusBadge(withdrawal.status)}
                    {withdrawal.fee_amount > 0 && (
                      <p className="text-xs text-gray-400 mt-1">
                        Fee: {formatCurrency(withdrawal.fee_amount)}
                      </p>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
        {/* Pagination */}
        <div className="flex justify-between items-center mt-4">
          <Button
            onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
            disabled={currentPage === 1}
            variant="outline"
            size="sm"
          >
            Previous
          </Button>
          <span className="text-white text-sm">
            Page {currentPage} of {Math.ceil(withdrawals.length / itemsPerPage)}
          </span>
          <Button
            onClick={() => setCurrentPage(prev => prev + 1)}
            disabled={endIndex >= withdrawals.length}
            variant="outline"
            size="sm"
          >
            Next
          </Button>
        </div>
      </Card>
    </div>
  );
};

// Withdrawal Request Button Component
export const WithdrawalRequestButton = ({ onWithdrawalComplete }) => {
  const [showDialog, setShowDialog] = useState(false);
  const [amount, setAmount] = useState('');
  const [notes, setNotes] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const [balance, setBalance] = useState(null);
  const { toast } = useToast();

  useEffect(() => {
    if (showDialog) {
      fetchBalance();
    }
  }, [showDialog]);

  const fetchBalance = async () => {
    try {
      const response = await axios.get(`${API}/payments/writer/balance`, {
        withCredentials: true
      });
      setBalance(response.data);
    } catch (error) {
      console.error('Error fetching balance:', error);
    }
  };

  const handleWithdrawal = async () => {
    const withdrawalAmount = parseFloat(amount);
    
    if (!withdrawalAmount || withdrawalAmount <= 0) {
      toast({
        title: "Invalid Amount",
        description: "Please enter a valid withdrawal amount",
        variant: "destructive",
      });
      return;
    }

    if (withdrawalAmount > (balance?.available_balance || 0)) {
      toast({
        title: "Insufficient Balance",
        description: `Available balance: $${balance?.available_balance?.toFixed(2) || '0.00'}`,
        variant: "destructive",
      });
      return;
    }

    setIsProcessing(true);
    try {
      const response = await axios.post(`${API}/payments/writer/withdrawal`, {
        amount: withdrawalAmount,
        notes: notes.trim() || undefined
      }, {
        withCredentials: true
      });

      toast({
        title: "Withdrawal Request Submitted",
        description: response.data.message || "Your withdrawal request has been processed",
      });

      setShowDialog(false);
      setAmount('');
      setNotes('');
      
      if (onWithdrawalComplete) {
        onWithdrawalComplete();
      }
    } catch (error) {
      console.error('Withdrawal error:', error);
      toast({
        title: "Withdrawal Failed",
        description: error.response?.data?.detail || "Failed to process withdrawal request",
        variant: "destructive",
      });
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <>
      <Button
        onClick={() => setShowDialog(true)}
        className="bg-green-600 hover:bg-green-700 text-white"
        disabled={!balance || balance.available_balance <= 0}
      >
        <Wallet className="w-4 h-4 mr-2" />
        Request Withdrawal
      </Button>

      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="bg-black border-white/20 text-white">
          <DialogHeader>
            <DialogTitle>Request Withdrawal</DialogTitle>
            <DialogDescription className="text-gray-400">
              Withdraw your available earnings to your connected bank account
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {balance && (
              <div className="bg-green-600/20 border border-green-600/50 rounded-lg p-4">
                <div className="flex justify-between items-center">
                  <span className="text-white">Available Balance:</span>
                  <span className="text-white font-bold text-lg">
                    ${balance.available_balance?.toFixed(2) || '0.00'}
                  </span>
                </div>
                <div className="text-xs text-gray-300 mt-2">
                  <p>Min: ${balance.minimum_withdrawal?.toFixed(2)} • Max: ${balance.maximum_withdrawal?.toFixed(2)}</p>
                  {balance.pending_withdrawals > 0 && (
                    <p className="text-yellow-400">
                      ${balance.pending_withdrawals?.toFixed(2)} pending withdrawal
                    </p>
                  )}
                </div>
              </div>
            )}

            <div>
              <Label htmlFor="withdrawalAmount" className="text-white">Withdrawal Amount ($)</Label>
              <Input
                id="withdrawalAmount"
                type="number"
                min="1"
                max={balance?.available_balance || 0}
                step="0.01"
                placeholder="0.00"
                value={amount}
                onChange={(e) => setAmount(e.target.value)}
                className="bg-white/10 border-white/20 text-white"
              />
              <div className="flex justify-between mt-1">
                <span className="text-xs text-gray-400">
                  Transfer fee: ~0.25%
                </span>
                {amount && !isNaN(parseFloat(amount)) && (
                  <span className="text-xs text-gray-400">
                    You'll receive: ~${(parseFloat(amount) * 0.9975).toFixed(2)}
                  </span>
                )}
              </div>
            </div>

            <div>
              <Label htmlFor="notes" className="text-white">Notes (optional)</Label>
              <Textarea
                id="notes"
                placeholder="Add a note for this withdrawal..."
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                className="bg-white/10 border-white/20 text-white"
                maxLength={200}
              />
              <div className="text-xs text-gray-400 mt-1">
                {notes.length}/200 characters
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowDialog(false)}
              className="border-white/30 text-white hover:bg-white/10"
            >
              Cancel
            </Button>
            <Button
              onClick={handleWithdrawal}
              disabled={isProcessing || !amount || parseFloat(amount) <= 0}
              className="bg-green-600 hover:bg-green-700 text-white"
            >
              {isProcessing ? 'Processing...' : 'Request Withdrawal'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
};

// Stripe Connect Onboarding Component
export const StripeConnectOnboarding = () => {
  const [connectStatus, setConnectStatus] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const { toast } = useToast();

  useEffect(() => {
    fetchConnectStatus();
  }, []);

  const fetchConnectStatus = async () => {
    try {
      setIsLoading(true);
      const response = await axios.get(`${API}/payments/writer/connect-status`, {
        withCredentials: true
      });
      setConnectStatus(response.data);
    } catch (error) {
      console.error('Error fetching Connect status:', error);
      toast({
        title: "Error",
        description: "Failed to load Connect account status",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleCreateConnectAccount = async () => {
    try {
      setIsLoading(true);
      const response = await axios.post(`${API}/payments/writer/connect-account`, {}, {
        withCredentials: true
      });

      // Redirect to Stripe onboarding
      if (response.data.onboarding_url) {
        window.location.href = response.data.onboarding_url;
      }
    } catch (error) {
      console.error('Error creating Connect account:', error);
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to create Connect account",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  if (isLoading) {
    return (
      <Card className="bg-black/60 border-white/20">
        <CardContent className="p-6">
          <div className="animate-pulse flex space-x-4">
            <div className="rounded-full bg-white/20 h-12 w-12"></div>
            <div className="flex-1 space-y-2 py-1">
              <div className="h-4 bg-white/20 rounded w-3/4"></div>
              <div className="h-4 bg-white/20 rounded w-1/2"></div>
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  const getStatusIcon = () => {
    if (!connectStatus?.has_account) return AlertCircle;
    if (connectStatus.payouts_enabled) return CheckCircle;
    return Clock;
  };

  const getStatusColor = () => {
    if (!connectStatus?.has_account) return 'text-yellow-500';
    if (connectStatus.payouts_enabled) return 'text-green-500';
    return 'text-blue-500';
  };

  const StatusIcon = getStatusIcon();

  return (
    <Card className="bg-black/60 border-white/20">
      <CardHeader>
        <CardTitle className="text-white flex items-center">
          <StatusIcon className={`w-5 h-5 mr-2 ${getStatusColor()}`} />
          Bank Account Connection
        </CardTitle>
        <CardDescription className="text-gray-400">
          Connect your bank account to receive payments
        </CardDescription>
      </CardHeader>
      <CardContent>
        {!connectStatus?.has_account ? (
          <div className="space-y-4">
            <div className="bg-yellow-600/20 border border-yellow-600/50 rounded-lg p-4">
              <div className="flex items-start space-x-3">
                <AlertCircle className="w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="text-white font-medium">Bank Account Required</p>
                  <p className="text-sm text-gray-300 mt-1">
                    You need to connect a bank account to receive withdrawals. This process is secure and handled by Stripe.
                  </p>
                </div>
              </div>
            </div>
            <Button
              onClick={handleCreateConnectAccount}
              className="w-full bg-blue-600 hover:bg-blue-700 text-white"
              disabled={isLoading}
            >
              <CreditCard className="w-4 h-4 mr-2" />
              {isLoading ? 'Setting up...' : 'Connect Bank Account'}
            </Button>
          </div>
        ) : connectStatus.payouts_enabled ? (
          <div className="bg-green-600/20 border border-green-600/50 rounded-lg p-4">
            <div className="flex items-center space-x-3">
              <CheckCircle className="w-5 h-5 text-green-500" />
              <div>
                <p className="text-white font-medium">Bank Account Connected</p>
                <p className="text-sm text-gray-300">
                  Your bank account is verified and ready for payouts
                </p>
              </div>
            </div>
          </div>
        ) : (
          <div className="space-y-4">
            <div className="bg-blue-600/20 border border-blue-600/50 rounded-lg p-4">
              <div className="flex items-start space-x-3">
                <Clock className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="text-white font-medium">Verification In Progress</p>
                  <p className="text-sm text-gray-300 mt-1">
                    Your bank account connection is being verified. This usually takes 1-2 business days.
                  </p>
                  {connectStatus.requirements && Object.keys(connectStatus.requirements).length > 0 && (
                    <p className="text-sm text-yellow-300 mt-2">
                      Additional information may be required to complete verification.
                    </p>
                  )}
                </div>
              </div>
            </div>
            <Button
              onClick={fetchConnectStatus}
              variant="outline"
              className="w-full border-white/30 text-white hover:bg-white/10"
            >
              Refresh Status
            </Button>
          </div>
        )}
      </CardContent>
    </Card>
  );
};