import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { __ } from '@/lib/i18n';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';
import { showSuccessToast, showErrorToast } from '@/lib/errorHandling';
import { DollarSign, Plus, CreditCard, Building, ArrowRight } from 'lucide-react';
import { formatMoney } from '@/lib/currency';

interface Payout {
    id: number;
    affiliate_id: number;
    affiliate_name?: string;
    affiliate_email?: string;
    amount: string;
    currency: string;
    method: string;
    status: string;
    notes: string;
    created_at: string;
    completed_at: string;
}

interface Affiliate {
    id: number;
    user_id: number;
    user_name?: string;
    user_email?: string;
    referral_code: string;
    total_earnings: string;
    paid_earnings: string;
    payable_balance: number;
    total_referrals: number;
    status: string;
}

export default function AffiliatesPayouts() {
    const qc = useQueryClient();
    const [showCreateForm, setShowCreateForm] = useState(false);
    const [selectedAffiliateId, setSelectedAffiliateId] = useState<number | null>(null);
    const [amount, setAmount] = useState('');
    const [method, setMethod] = useState('bank_transfer');

    // Fetch affiliates for dropdown
    const { data: affiliates = [], isLoading: isLoadingAffiliates } = useQuery<Affiliate[]>({
        queryKey: ['admin-affiliates'],
        queryFn: () => api.get('/admin/affiliates'),
    });

    // Fetch payouts
    const { data: payouts = [], isLoading: isLoadingPayouts } = useQuery<Payout[]>({
        queryKey: ['admin-payouts'],
        queryFn: () => api.get('/admin/affiliates/payouts'),
    });

    // Get selected affiliate balance
    const selectedAffiliate = affiliates.find(a => a.id === selectedAffiliateId);
    const payableBalance = selectedAffiliate?.payable_balance || 0;

    // Create payout mutation
    const createPayoutMutation = useMutation({
        mutationFn: async (data: { affiliate_id: number; amount: number; method: string }) => {
            return api.post('/admin/affiliates/payouts', data);
        },
        onSuccess: (result: any) => {
            qc.invalidateQueries({ queryKey: ['admin-payouts'] });
            qc.invalidateQueries({ queryKey: ['admin-affiliates'] });
            showSuccessToast(__('Payout created successfully!') + (result.coupon_code ? ` Coupon: ${result.coupon_code}` : ''));
            setShowCreateForm(false);
            setSelectedAffiliateId(null);
            setAmount('');
            setMethod('bank_transfer');
        },
        onError: (err: any) => {
            showErrorToast(err, __('Failed to create payout'));
        },
    });

    const handleCreatePayout = () => {
        if (!selectedAffiliateId || !amount) return;

        const amountNum = parseFloat(amount);
        if (amountNum <= 0) {
            showErrorToast({ message: 'Amount must be greater than 0' }, __('Invalid amount'));
            return;
        }

        if (amountNum > payableBalance) {
            showErrorToast({ message: `Amount exceeds payable balance of ${payableBalance}` }, __('Amount too high'));
            return;
        }

        createPayoutMutation.mutate({
            affiliate_id: selectedAffiliateId,
            amount: amountNum,
            method
        });
    };

    const formatCurrency = (value: string | number, currency?: string) => {
        try {
            return formatMoney(value, { currency });
        } catch {
            const num = typeof value === 'string' ? parseFloat(value) : value;
            if (isNaN(num)) return '—';
            return `${currency || 'IDR'} ${num.toLocaleString()}`;
        }
    };

    const formatDate = (dateStr: string) => {
        return new Date(dateStr).toLocaleDateString('id-ID', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between">
                <div>
                    <h2 className="text-xl font-semibold">{__('Affiliate Payouts')}</h2>
                    <p className="text-sm text-muted-foreground mt-1">
                        {__('Manage affiliate commission payouts')}
                    </p>
                </div>
                <Button onClick={() => setShowCreateForm(true)}>
                    <Plus className="w-4 h-4 mr-2" />
                    {__('Create Payout')}
                </Button>
            </div>

            {/* Create Payout Modal */}
            {showCreateForm && (
                <div className="bg-white dark:bg-gray-800 rounded-lg border p-6 space-y-4">
                    <h3 className="text-lg font-semibold">{__('Create New Payout')}</h3>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {/* Affiliate Selection */}
                        <div>
                            <label className="text-sm font-medium mb-2 block">{__('Affiliate')}</label>
                            <Select
                                value={selectedAffiliateId?.toString() || ''}
                                onValueChange={(v) => {
                                    setSelectedAffiliateId(parseInt(v));
                                    setAmount(''); // Reset amount when affiliate changes
                                }}
                            >
                                <SelectTrigger>
                                    <SelectValue placeholder={__('Select affiliate')} />
                                </SelectTrigger>
                                <SelectContent>
                                    {affiliates
                                        .filter(a => a.status === 'active')
                                        .filter(a => (a.payable_balance || 0) > 0)
                                        .map(affiliate => (
                                            <SelectItem key={affiliate.id} value={affiliate.id.toString()}>
                                                {affiliate.user_name || affiliate.user_email} (Payable: {formatCurrency(affiliate.payable_balance)})
                                            </SelectItem>
                                        ))}
                                </SelectContent>
                            </Select>
                        </div>

                        {/* Method Selection */}
                        <div>
                            <label className="text-sm font-medium mb-2 block">{__('Payment Method')}</label>
                            <Select value={method} onValueChange={setMethod}>
                                <SelectTrigger>
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="bank_transfer">
                                        <div className="flex items-center gap-2">
                                            <Building className="w-4 h-4" />
                                            {__('Bank Transfer')}
                                        </div>
                                    </SelectItem>
                                    <SelectItem value="store_credit">
                                        <div className="flex items-center gap-2">
                                            <CreditCard className="w-4 h-4" />
                                            {__('Store Credit')}
                                        </div>
                                    </SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>

                    {/* Amount Input */}
                    {selectedAffiliateId && (
                        <div className="space-y-2">
                            <div className="flex items-center justify-between">
                                <label className="text-sm font-medium">{__('Amount')}</label>
                                <span className="text-xs text-muted-foreground">
                                    {__('Available:')} {formatCurrency(payableBalance)}
                                </span>
                            </div>
                            <div className="flex gap-2">
                                <Input
                                    type="number"
                                    value={amount}
                                    onChange={(e) => setAmount(e.target.value)}
                                    placeholder="0"
                                    min="0"
                                    max={payableBalance}
                                    step="0.01"
                                />
                                <Button
                                    variant="outline"
                                    onClick={() => setAmount(payableBalance.toString())}
                                    disabled={payableBalance <= 0}
                                >
                                    {__('Pay All')}
                                </Button>
                            </div>
                            {method === 'store_credit' && parseFloat(amount) > 0 && (
                                <p className="text-xs text-muted-foreground">
                                    {__('A store credit coupon will be generated and emailed to the affiliate.')}
                                </p>
                            )}
                        </div>
                    )}

                    {/* Actions */}
                    <div className="flex justify-end gap-2 pt-4 border-t">
                        <Button variant="outline" onClick={() => setShowCreateForm(false)}>
                            {__('Cancel')}
                        </Button>
                        <Button
                            onClick={handleCreatePayout}
                            disabled={!selectedAffiliateId || !amount || createPayoutMutation.isPending}
                        >
                            {createPayoutMutation.isPending ? __('Creating...') : __('Create Payout')}
                        </Button>
                    </div>
                </div>
            )}

            {/* Payouts Table */}
            <div className="rounded-lg border overflow-hidden">
                <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                        <thead className="bg-gray-50 dark:bg-gray-900">
                            <tr>
                                <th className="px-4 py-3 text-left font-medium">{__('Affiliate')}</th>
                                <th className="px-4 py-3 text-left font-medium">{__('Amount')}</th>
                                <th className="px-4 py-3 text-left font-medium">{__('Method')}</th>
                                <th className="px-4 py-3 text-left font-medium">{__('Status')}</th>
                                <th className="px-4 py-3 text-left font-medium">{__('Date')}</th>
                                <th className="px-4 py-3 text-left font-medium">{__('Notes')}</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y">
                            {isLoadingPayouts ? (
                                <tr>
                                    <td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">
                                        {__('Loading...')}
                                    </td>
                                </tr>
                            ) : payouts.length === 0 ? (
                                <tr>
                                    <td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">
                                        {__('No payouts yet')}
                                    </td>
                                </tr>
                            ) : (
                                payouts.map((payout) => (
                                    <tr key={payout.id} className="hover:bg-gray-50/50 dark:hover:bg-gray-800/50">
                                        <td className="px-4 py-3">
                                            <div>
                                                <div className="font-medium">{payout.affiliate_name || '—'}</div>
                                                <div className="text-xs text-muted-foreground">{payout.affiliate_email}</div>
                                            </div>
                                        </td>
                                        <td className="px-4 py-3 font-medium">
                                            {formatCurrency(payout.amount, payout.currency)}
                                        </td>
                                        <td className="px-4 py-3">
                                            <span className="inline-flex items-center gap-1 text-xs">
                                                {payout.method === 'store_credit' ? (
                                                    <>
                                                        <CreditCard className="w-3 h-3" />
                                                        {__('Store Credit')}
                                                    </>
                                                ) : (
                                                    <>
                                                    <Building className="w-3 h-3" />
                                                    {__('Bank Transfer')}
                                                    </>
                                                )}
                                            </span>
                                        </td>
                                        <td className="px-4 py-3">
                                            <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                                                payout.status === 'completed'
                                                    ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                                                    : payout.status === 'pending'
                                                    ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200'
                                                    : 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200'
                                            }`}>
                                                {payout.status}
                                            </span>
                                        </td>
                                        <td className="px-4 py-3 text-muted-foreground">
                                            {payout.completed_at ? formatDate(payout.completed_at) : '—'}
                                        </td>
                                        <td className="px-4 py-3 text-muted-foreground text-xs max-w-[200px] truncate">
                                            {payout.notes || '—'}
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Summary Stats */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="bg-white dark:bg-gray-800 p-4 rounded-lg border">
                    <div className="text-sm text-muted-foreground">{__('Total Payouts')}</div>
                    <div className="text-2xl font-bold mt-1">{payouts.length}</div>
                </div>
                <div className="bg-white dark:bg-gray-800 p-4 rounded-lg border">
                    <div className="text-sm text-muted-foreground">{__('Total Paid')}</div>
                    <div className="text-2xl font-bold mt-1">
                        {formatCurrency(payouts.reduce((sum, p) => sum + parseFloat(p.amount || '0'), 0))}
                    </div>
                </div>
                <div className="bg-white dark:bg-gray-800 p-4 rounded-lg border">
                    <div className="text-sm text-muted-foreground">{__('Affiliates with Balance')}</div>
                    <div className="text-2xl font-bold mt-1">
                        {affiliates.filter(a => (a.payable_balance || 0) > 0).length}
                    </div>
                </div>
            </div>
        </div>
    );
}