import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { zodResolver } from '@hookform/resolvers/zod';
import { usePage } from '@inertiajs/react';
import axios from 'axios';
import { ArrowRight, SquareDashedMousePointer } from 'lucide-react';
import { useTransition } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import * as z from 'zod';

const stage1Schema = z.object({
    amount: z.number().min(1, { message: 'Withdrawal amount must be at least 1.' }),
});

const stage2Schema = z.object({
    walletAddress: z.string().min(1, { message: 'Wallet address is required.' }),
});

// Stage 1: Enter the amount
export function WithdrawalStage1({
    onNext,
    onSetAmount,
    availableBalance,
}: {
    onNext: () => void;
    onSetAmount: (amount: number) => void;
    availableBalance: number;
}) {
    const form = useForm<z.infer<typeof stage1Schema>>({
        resolver: zodResolver(
            stage1Schema.refine((data) => data.amount <= availableBalance, {
                message: `Amount exceeds available balance ($${availableBalance.toLocaleString()}).`,
                path: ['amount'],
            }),
        ),
        defaultValues: {
            amount: 0,
        },
    });

    function onSubmit(values: z.infer<typeof stage1Schema>) {
        onSetAmount(values.amount);
        onNext();
    }

    return (
        <Card className="flex-1 p-6 shadow-none">
            <h3 className="text-lg font-semibold text-gray-800">Enter the amount</h3>
            <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                    <FormField
                        control={form.control}
                        name="amount"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Amount</FormLabel>
                                <FormControl>
                                    <div className="relative">
                                        <Input
                                            className="peer ps-6 pe-12"
                                            placeholder="0.00"
                                            type="text"
                                            {...field}
                                            onChange={(e) => {
                                                const value = e.target.value;
                                                field.onChange(value === '' ? 0 : Number.parseFloat(value));
                                            }}
                                            disabled={availableBalance <= 0}
                                        />
                                        <span className="pointer-events-none absolute inset-y-0 start-0 flex items-center justify-center ps-3 text-sm text-muted-foreground peer-disabled:opacity-50">
                                            $
                                        </span>
                                        <span className="pointer-events-none absolute inset-y-0 end-0 flex items-center justify-center pe-3 text-sm text-muted-foreground peer-disabled:opacity-50">
                                            USD
                                        </span>
                                    </div>
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <div className="flex justify-end">
                        <Button type="submit" className="flex items-center gap-2" disabled={availableBalance <= 0}>
                            CONTINUE <ArrowRight className="h-4 w-4" />
                        </Button>
                    </div>
                </form>
            </Form>
        </Card>
    );
}

// Stage 2: Select your Wallet address
export function WithdrawalStage2({
    onNext,
    onBack,
    onSetWalletAddress,
}: {
    onNext: () => void;
    onBack: () => void;
    onSetWalletAddress: (address: string, method: string) => void;
}) {
    const { user } = usePage().props.auth;

    const wallets = [
        { name: 'BITCOIN', address: user.btc_account },
        { name: 'ETHEREUM', address: user.eth_account },
        { name: 'USDT TRC 20', address: user.usdt_account },
    ];

    const form = useForm<z.infer<typeof stage2Schema>>({
        resolver: zodResolver(stage2Schema),
        defaultValues: {
            walletAddress: '',
        },
    });

    function onSubmit(values: z.infer<typeof stage2Schema>) {
        const wallet = wallets.find((wallet) => wallet.name === values.walletAddress);
        onSetWalletAddress(wallet?.address || '', values.walletAddress);
        onNext();
    }

    return (
        <Card className="flex-1 rounded-xl p-6 shadow-none">
            <h3 className="text-lg font-semibold text-gray-800">Select your Wallet address</h3>
            <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                    <FormField
                        control={form.control}
                        name="walletAddress"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel className="text-gray-500"> Wallet Address :</FormLabel>
                                <FormControl>
                                    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                                        {wallets.map((wallet) => (
                                            <div
                                                key={wallet.name}
                                                className={`cursor-pointer rounded-lg border p-4 ${
                                                    field.value === wallet.name ? 'border-green-500 ring-[1.5px] ring-green-500' : 'border-gray-200'
                                                }`}
                                                onClick={() => {
                                                    if (!wallet.address?.trim()) {
                                                        toast.warning('Kindly visit the settings page to set your wallet address.');
                                                    } else {
                                                        field.onChange(wallet.name);
                                                    }
                                                }}
                                            >
                                                <div className="mb-2 flex items-center justify-between">
                                                    <p className="text-sm font-medium text-gray-600">Direct deposit from your Wallet</p>
                                                    <SquareDashedMousePointer className="h-5 w-5 text-gray-400" />
                                                </div>
                                                <h4 className="text-base font-semibold">{wallet.name}</h4>
                                            </div>
                                        ))}
                                    </div>
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <div className="flex justify-between">
                        <Button variant="outline" onClick={onBack} className="flex items-center gap-2 bg-transparent">
                            <ArrowRight className="h-4 w-4 rotate-180" /> BACK
                        </Button>
                        <Button type="submit" className="flex items-center gap-2">
                            CONTINUE <ArrowRight className="h-4 w-4" />
                        </Button>
                    </div>
                </form>
            </Form>
        </Card>
    );
}

// Stage 3: Confirm your withdrawal
export function WithdrawalStage3({
    onBack,
    withdrawalDetails,
    reset,
}: {
    onBack: () => void;
    withdrawalDetails: {
        amount: number;
        wallet_address: string;
    };
    reset: () => void;
}) {
    const [loading, startTransition] = useTransition();

    const handleConfirm = () => {
        startTransition(async () => {
            await axios
                .post(route('withdraw.store'), withdrawalDetails)
                .then(() => {
                    toast.success('Withdrawal Request!', {
                        description: 'Your withdrawal request has been submitted.',
                        duration: 10000,
                    });
                    reset();
                })
                .catch((error) => {
                    if (error?.response?.data) {
                        const { message } = error.response.data;

                        toast.error(message || 'An error occurred during registration. Please try again later.');
                    }
                });
        });
    };

    return (
        <Card className="flex-1 rounded-xl p-6 shadow-none">
            <h3 className="text-lg font-semibold text-gray-800">Confirm your withdrawal</h3>
            <div className="mb-6">
                <p className="text-sm text-gray-600">Please review your withdrawal details:</p>
                <div className="mt-4 grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
                    <p className="text-gray-500">Amount:</p>
                    <p className="font-medium">${withdrawalDetails.amount.toLocaleString()} USD</p>
                    <p className="text-gray-500">Wallet Address:</p>
                    <p className="font-medium break-all">{withdrawalDetails.wallet_address}</p>
                    <p className="text-gray-500">Withdrawal Fee:</p>
                    <p className="font-medium">0.00%</p>
                    <p className="text-gray-500">Net Amount:</p>
                    <p className="font-medium">${withdrawalDetails.amount.toLocaleString()} USD</p>
                </div>
            </div>

            <div className="flex justify-between">
                <Button variant="outline" onClick={onBack} disabled={loading} className="flex items-center gap-2 bg-transparent">
                    <ArrowRight className="h-4 w-4 rotate-180" /> BACK
                </Button>
                <Button onClick={handleConfirm} disabled={loading} className="flex items-center gap-2">
                    {loading ? 'Processing...' : 'CONFIRM WITHDRAWAL'}
                </Button>
            </div>
        </Card>
    );
}
