import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { Search, CheckCircle, XCircle, Edit, Pencil, Users, TrendingUp, DollarSign } from 'lucide-react';
import { api } from '@/lib/api';
import { __ } from '@/lib/i18n';
import { showSuccessToast, showErrorToast } from '@/lib/errorHandling';
import { formatMoney } from '@/lib/currency';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';

export default function AffiliatesList() {
    const [searchQuery, setSearchQuery] = useState('');
    const [editingAffiliate, setEditingAffiliate] = useState<any>(null);
    const [editRate, setEditRate] = useState('');
    const queryClient = useQueryClient();

    const { data: affiliates, isLoading } = useQuery({
        queryKey: ['admin-affiliates'],
        queryFn: async () => {
            const response: any = await api.get('/admin/affiliates');
            return Array.isArray(response) ? response : (response?.data || []);
        },
    });

    const updateMutation = useMutation({
        mutationFn: async ({ id, rate }: { id: number; rate: number }) => {
            return api.post(`/admin/affiliates/${id}/update`, { custom_commission_rate: rate });
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['admin-affiliates'] });
            setEditingAffiliate(null);
            showSuccessToast(__('Commission rate updated successfully'));
        },
        onError: (err: any) => {
            showErrorToast(err, __('Failed to update commission rate'));
        }
    });

    const approveMutation = useMutation({
        mutationFn: async (id: number) => {
            await api.post(`/admin/affiliates/${id}/approve`);
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['admin-affiliates'] });
        }
    });

    const filteredAffiliates = (affiliates || []).filter((aff: any) => {
        const code = aff.referral_code || '';
        return code.toLowerCase().includes(searchQuery.toLowerCase());
    });

    // Stats
    const totalAffiliates = (affiliates || []).length;
    const activeAffiliates = (affiliates || []).filter((a: any) => a.status === 'active').length;
    const pendingAffiliates = (affiliates || []).filter((a: any) => a.status === 'pending').length;
    const totalEarnings = (affiliates || []).reduce((sum: number, a: any) => sum + parseFloat(a.total_earnings || 0), 0);
    const totalPayable = (affiliates || []).reduce((sum: number, a: any) => sum + parseFloat(a.payable_balance || 0), 0);

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

    return (
        <div className="space-y-6">
            {/* Stats Cards */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <div className="bg-white dark:bg-gray-800 p-4 rounded-lg border">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg">
                            <Users className="w-5 h-5 text-blue-600 dark:text-blue-400" />
                        </div>
                        <div>
                            <div className="text-sm text-muted-foreground">{__('Total Affiliates')}</div>
                            <div className="text-2xl font-bold">{totalAffiliates}</div>
                        </div>
                    </div>
                </div>
                <div className="bg-white dark:bg-gray-800 p-4 rounded-lg border">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
                            <CheckCircle className="w-5 h-5 text-green-600 dark:text-green-400" />
                        </div>
                        <div>
                            <div className="text-sm text-muted-foreground">{__('Active')}</div>
                            <div className="text-2xl font-bold">{activeAffiliates}</div>
                        </div>
                    </div>
                </div>
                <div className="bg-white dark:bg-gray-800 p-4 rounded-lg border">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-yellow-100 dark:bg-yellow-900 rounded-lg">
                            <TrendingUp className="w-5 h-5 text-yellow-600 dark:text-yellow-400" />
                        </div>
                        <div>
                            <div className="text-sm text-muted-foreground">{__('Total Earnings')}</div>
                            <div className="text-2xl font-bold">{formatCurrency(totalEarnings)}</div>
                        </div>
                    </div>
                </div>
                <div className="bg-white dark:bg-gray-800 p-4 rounded-lg border">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg">
                            <DollarSign className="w-5 h-5 text-purple-600 dark:text-purple-400" />
                        </div>
                        <div>
                            <div className="text-sm text-muted-foreground">{__('Payable Balance')}</div>
                            <div className="text-2xl font-bold">{formatCurrency(totalPayable)}</div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Search and Table */}
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div className="relative flex-1 max-w-sm">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
                    <Input
                        placeholder={__('Search by referral code...')}
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="!pl-9"
                    />
                </div>
            </div>

            {isLoading ? (
                <div className="text-center py-8 text-muted-foreground">
                    {__('Loading affiliates...')}
                </div>
            ) : filteredAffiliates.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                    {searchQuery ? __('No affiliates found matching your search') : __('No affiliates yet')}
                </div>
            ) : (
                <div className="border rounded-lg">
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>{__('User ID')}</TableHead>
                                <TableHead>{__('Code')}</TableHead>
                                <TableHead>{__('Rate')}</TableHead>
                                <TableHead>{__('Status')}</TableHead>
                                <TableHead className="text-right">{__('Earnings')}</TableHead>
                                <TableHead className="text-right">{__('Payable')}</TableHead>
                                <TableHead className="text-right">{__('Actions')}</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {filteredAffiliates.map((affiliate: any) => (
                                <TableRow key={affiliate.id}>
                                    <TableCell className="font-medium">{affiliate.user_id}</TableCell>
                                    <TableCell>{affiliate.referral_code}</TableCell>
                                    <TableCell>
                                        {editingAffiliate?.id === affiliate.id ? (
                                            <div className="flex items-center gap-2">
                                                <Input
                                                    type="number"
                                                    value={editRate}
                                                    onChange={(e) => setEditRate(e.target.value)}
                                                    className="w-20 h-8 text-sm"
                                                    min="0"
                                                    max="100"
                                                    step="0.01"
                                                />
                                                <Button
                                                    size="sm"
                                                    variant="outline"
                                                    onClick={() => updateMutation.mutate({ id: affiliate.id, rate: parseFloat(editRate) })}
                                                    disabled={updateMutation.isPending}
                                                >
                                                    {__('Save')}
                                                </Button>
                                                <Button
                                                    size="sm"
                                                    variant="ghost"
                                                    onClick={() => setEditingAffiliate(null)}
                                                >
                                                    {__('Cancel')}
                                                </Button>
                                            </div>
                                        ) : (
                                            <div className="flex items-center gap-2">
                                                <span>
                                                    {affiliate.custom_commission_rate !== null && affiliate.custom_commission_rate !== undefined && affiliate.custom_commission_rate !== ''
                                                        ? `${parseFloat(affiliate.custom_commission_rate).toFixed(1)}% (custom)`
                                                        : `${parseFloat(affiliate.commission_rate || 10).toFixed(1)}% (default)`}
                                                </span>
                                                <button
                                                    onClick={() => {
                                                        setEditingAffiliate(affiliate);
                                                        const rate = affiliate.custom_commission_rate ?? affiliate.commission_rate ?? 10;
                                                        setEditRate(rate.toString());
                                                    }}
                                                    className="p-1 hover:bg-muted rounded"
                                                    title={__('Edit commission rate')}
                                                >
                                                    <Pencil className="h-3 w-3" />
                                                </button>
                                            </div>
                                        )}
                                    </TableCell>
                                    <TableCell>
                                        <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                                            affiliate.status === 'active'
                                                ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300'
                                                : 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300'
                                        }`}>
                                            {affiliate.status}
                                        </span>
                                    </TableCell>
                                    <TableCell className="text-right">{formatCurrency(affiliate.total_earnings)}</TableCell>
                                    <TableCell className="text-right text-green-600 font-medium">
                                        {formatCurrency(affiliate.payable_balance || 0)}
                                    </TableCell>
                                    <TableCell className="text-right">
                                        {affiliate.status === 'pending' && (
                                            <Button
                                                variant="outline"
                                                size="sm"
                                                onClick={() => approveMutation.mutate(affiliate.id)}
                                                disabled={approveMutation.isPending}
                                            >
                                                <CheckCircle className="mr-2 h-4 w-4 text-green-500" />
                                                {__('Approve')}
                                            </Button>
                                        )}
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </div>
            )}
        </div>
    );
}
