'use client';

import { useForm } from '@inertiajs/react';
import { CreditCardIcon } from 'lucide-react';
import { useEffect, useId, useRef, useState } from 'react';
import { usePaymentInputs } from 'react-payment-inputs';
import images, { type CardImages } from 'react-payment-inputs/images';

import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogClose,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Flash,
    showFlash,
    useFlashToasts,
} from '@/components/use-flash-toasts';

interface CheckoutProps {
    open: boolean;
    setOpen: (v: boolean) => void;
    itemName: string;
    itemPrice: number;
    action: string;
    method?: 'post' | 'put' | 'patch';
    extraData?: {
        id: number;
        transaction_type: string;
    };
}

// Interfaz para el formulario de checkout
interface CheckoutForm {
    id: number;
    amount: number;
    transaction_type: string;
}

export default function Checkout({
    open,
    setOpen,
    itemName,
    itemPrice,
    action,
    method = 'post',
    extraData = {
        id: 0,
        transaction_type: '',
    },
}: CheckoutProps) {
    const id = useId();
    const { id: extraId, transaction_type } = extraData || {};
    // Usa la interfaz CheckoutForm en useForm
    const { data, post, put, patch, processing, errors, reset } =
        useForm<CheckoutForm>({
            id: extraId,
            amount: itemPrice,
            transaction_type,
        });
    const {
        meta,
        getCardNumberProps,
        getExpiryDateProps,
        getCVCProps,
        getCardImageProps,
    } = usePaymentInputs();
    const couponInputRef = useRef<HTMLInputElement>(null);
    const [showCouponInput, setShowCouponInput] = useState(false);
    const [couponCode, setCouponCode] = useState('');
    useFlashToasts({ errors });

    useEffect(() => {
        if (showCouponInput && couponInputRef.current) {
            couponInputRef.current.focus();
        }
    }, [showCouponInput]);

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        const send = method === 'put' ? put : method === 'patch' ? patch : post;
        send(action, {
            onSuccess: (page) => {
                const flash = page.props.flash as Flash;
                showFlash(flash);
                reset();
                setOpen(false);
            },
            onError: () => {
                // Los errores se muestran automáticamente por useFlashToasts
            },
        });
    };

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent>
                <div className="mb-2 flex flex-col gap-2">
                    <div
                        className="flex size-11 shrink-0 items-center justify-center rounded-full border"
                        aria-hidden="true"
                    >
                        <CreditCardIcon className="opacity-80" size={16} />
                    </div>
                    <DialogHeader>
                        <DialogTitle className="text-left">
                            Confirmar compra: {itemName}
                        </DialogTitle>
                        <DialogDescription className="text-left">
                            Paga de forma segura y cancela en cualquier momento.
                            <br />
                            <span className="block mt-2 text-2xl font-bold text-foreground">
                                Precio: ${data.amount} USD
                            </span>
                        </DialogDescription>
                    </DialogHeader>
                </div>

                <form className="space-y-5" onSubmit={submit}>
                    <div className="space-y-4">
                        <div className="*:not-first:mt-2">
                            <Label htmlFor={`name-${id}`}>
                                Nombre en la tarjeta
                            </Label>
                            <Input id={`name-${id}`} type="text" required />
                        </div>
                        <div className="*:not-first:mt-2">
                            <legend className="text-sm font-medium text-foreground">
                                Detalles de la tarjeta
                            </legend>
                            <div className="rounded-md shadow-xs">
                                <div className="relative focus-within:z-10">
                                    <Input
                                        className="peer rounded-b-none pe-9 shadow-none [direction:inherit]"
                                        {...getCardNumberProps()}
                                    />
                                    <div className="pointer-events-none absolute inset-y-0 end-0 flex items-center justify-center pe-3 text-muted-foreground/80 peer-disabled:opacity-50">
                                        {meta.cardType ? (
                                            <svg
                                                className="overflow-hidden rounded-sm"
                                                {...getCardImageProps({
                                                    images: images as unknown as CardImages,
                                                })}
                                                width={20}
                                            />
                                        ) : (
                                            <CreditCardIcon
                                                size={16}
                                                aria-hidden="true"
                                            />
                                        )}
                                    </div>
                                </div>
                                <div className="-mt-px flex">
                                    <div className="min-w-0 flex-1 focus-within:z-10">
                                        <Input
                                            className="rounded-e-none rounded-t-none shadow-none [direction:inherit]"
                                            {...getExpiryDateProps()}
                                        />
                                    </div>
                                    <div className="-ms-px min-w-0 flex-1 focus-within:z-10">
                                        <Input
                                            className="rounded-s-none rounded-t-none shadow-none [direction:inherit]"
                                            {...getCVCProps()}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                        {!showCouponInput ? (
                            <button
                                type="button"
                                onClick={() => setShowCouponInput(true)}
                                className="text-sm underline hover:no-underline"
                            >
                                + Agregar cupón
                            </button>
                        ) : (
                            <div className="*:not-first:mt-2">
                                <Label htmlFor={`coupon-${id}`}>
                                    Código de cupón
                                </Label>
                                <Input
                                    id={`coupon-${id}`}
                                    ref={couponInputRef}
                                    placeholder="Ingresa tu código"
                                    value={couponCode}
                                    onChange={(e) =>
                                        setCouponCode(e.target.value)
                                    }
                                />
                            </div>
                        )}
                    </div>
                </form>

                <p className="text-center text-xs text-muted-foreground">
                    Los pagos no son reembolsables. Puedes cancelar en cualquier
                    momento.
                </p>

                {/* Botones alineados a la derecha */}
                <div className="mt-4 flex gap-2 justify-end">
                    <DialogClose asChild>
                        <Button
                            variant="outline"
                            type="button"
                        >
                            Cancelar
                        </Button>
                    </DialogClose>
                    <Button
                        type="submit"
                        form=""
                        disabled={processing}
                        data-amount={data.amount}
                        onClick={submit}
                    >
                        {processing ? 'Procesando...' : 'Comprar'}
                    </Button>
                </div>
            </DialogContent>
        </Dialog>
    );
}
