import { ArrowLeft, DollarSign, Wallet } from 'lucide-react';
import { useForm } from '@inertiajs/react';
import type { FormEvent } from 'react';
import { useEffect, useState } from 'react';
import { ConfirmActionModal } from '@/components/confirm-action-modal';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import ProjectionSummary from '@/pages/investments/components/projection-summary';
import type { InvestmentProjection } from '@/pages/investments/types';

type FundingSource = 'blockchain' | 'balance';

type InvestmentConfirmationProps = {
    projection: InvestmentProjection;
    canSubmitInvestment: boolean;
    onCancel: () => void;
    fundingSource: FundingSource;
    onFundingSourceChange: (value: FundingSource) => void;
    withdrawableBalanceUsd: string;
    minInvestmentAmount: number;
    /** Flujo desde ?reinvertir=1: solo saldo retirable, sin mínimo de inversión nueva. */
    reinvestMode?: boolean;
};

export default function InvestmentConfirmation({
    projection,
    canSubmitInvestment,
    onCancel,
    fundingSource,
    onFundingSourceChange,
    withdrawableBalanceUsd,
    minInvestmentAmount,
    reinvestMode = false,
}: InvestmentConfirmationProps) {
    const withdrawableUsd = Number.parseFloat(withdrawableBalanceUsd.replace(',', '.')) || 0;
    const meetsMinForBalance = projection.amount >= minInvestmentAmount;
    const canUseBalance =
        withdrawableUsd + 1e-6 >= projection.amount && meetsMinForBalance && projection.amount >= 0.01;

    const form = useForm({
        funding_source: fundingSource,
        amount: projection.amount,
        duration_months: projection.durationMonths,
        txid: '',
    });

    const [confirmOpen, setConfirmOpen] = useState(false);

    useEffect(() => {
        form.setData('funding_source', fundingSource);
    }, [fundingSource]);

    useEffect(() => {
        form.setData('amount', projection.amount);
        form.setData('duration_months', projection.durationMonths);
    }, [projection.amount, projection.durationMonths]);

    function submit(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        if (!canSubmitInvestment) {
            return;
        }
        if (reinvestMode && form.data.funding_source !== 'balance') {
            return;
        }
        if (form.data.funding_source === 'balance' && !canUseBalance) {
            return;
        }
        setConfirmOpen(true);
    }

    function executeInvestment() {
        form.transform((data) =>
            data.funding_source === 'balance'
                ? {
                      ...data,
                      txid: '',
                  }
                : data,
        );
        form.post('/invertir', {
            preserveScroll: true,
            onFinish: () => setConfirmOpen(false),
        });
    }

    const originLabel =
        form.data.funding_source === 'balance' ? 'Saldo retirable' : 'Depósito externo (TXID / QR)';

    return (
        <Card className="w-full overflow-hidden border-primary/20 bg-card">
            <CardHeader className="space-y-1 p-5 pb-2">
                <CardTitle className="flex items-center gap-2 text-xl">
                    <DollarSign className="size-5" />
                    Resumen de inversión
                </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6 p-5">
                <ConfirmActionModal
                    cancelLabel="Volver"
                    confirmLabel="Sí, solicitar"
                    open={confirmOpen}
                    processing={form.processing}
                    title="¿Confirmar solicitud de inversión?"
                    onConfirm={executeInvestment}
                    onOpenChange={setConfirmOpen}
                    description="Recibirás un correo con un enlace para confirmar la operación antes de que se registre."
                >
                    <div className="space-y-2 text-muted-foreground">
                        <p>
                            <span className="text-foreground font-medium">Monto:</span>{' '}
                            <span className="tabular-nums text-foreground">
                                {projection.amount.toFixed(2)} US$
                            </span>
                        </p>
                        <p>
                            <span className="text-foreground font-medium">Plazo:</span>{' '}
                            <span className="text-foreground">{projection.durationMonths} meses</span>
                        </p>
                        <p>
                            <span className="text-foreground font-medium">Origen:</span> {originLabel}
                        </p>
                    </div>
                </ConfirmActionModal>

                <form className="space-y-6" onSubmit={submit}>
                    <div>
                        <h2 className="mb-3 text-base font-semibold">Origen del capital</h2>
                        {reinvestMode ? (
                            <p className="text-muted-foreground mb-3 text-sm">
                                Estás en <strong className="text-foreground">reinversión</strong>: el cargo se hará sólo
                                contra tu saldo retirable disponible (sin depósito externo ni TXID).
                            </p>
                        ) : null}
                        <div
                            className={`grid gap-3 ${reinvestMode ? '' : 'sm:grid-cols-2'}`}
                        >
                            {!reinvestMode ? (
                                <button
                                    type="button"
                                    className={`flex flex-col rounded-lg border p-4 text-left transition-colors hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none ${
                                        fundingSource === 'blockchain'
                                            ? 'border-primary bg-primary/5 ring-2 ring-primary/25'
                                            : ''
                                    } ${!canSubmitInvestment ? 'pointer-events-none opacity-60' : ''}`}
                                    onClick={() => canSubmitInvestment && onFundingSourceChange('blockchain')}
                                >
                                    <div className="font-medium leading-none">Depósito externo (QR)</div>
                                    <p className="text-muted-foreground mt-2 text-xs leading-snug">
                                        Envío on-chain. Indica TXID después de transferir desde la vista
                                        lateral.
                                    </p>
                                </button>
                            ) : null}
                            <button
                                type="button"
                                className={`flex flex-col rounded-lg border p-4 text-left transition-colors hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none ${
                                    fundingSource === 'balance' ? 'border-primary bg-primary/5 ring-2 ring-primary/25' : ''
                                } ${!canSubmitInvestment ? 'pointer-events-none opacity-60' : ''} ${
                                    !canUseBalance ? 'opacity-60' : ''
                                } ${reinvestMode ? 'border-violet-500/40 ring-2 ring-violet-400/35' : ''}`}
                                disabled={!canUseBalance || !canSubmitInvestment}
                                onClick={() =>
                                    canSubmitInvestment &&
                                    canUseBalance &&
                                    onFundingSourceChange('balance')
                                }
                            >
                                <div className="flex items-start gap-2">
                                    <Wallet className="text-primary mt-0.5 size-4 shrink-0" aria-hidden />
                                    <div className="min-w-0">
                                        <div className="font-medium leading-none">Saldo retirable disponible</div>
                                        <p className="text-muted-foreground mt-2 text-xs leading-snug">
                                            Usa sólo ganancias y bonos que ya puedas retirar o reinvertir (no el
                                            principal pactado dentro del plazo). Disponible:{' '}
                                            <span className="tabular-nums text-foreground">
                                                {withdrawableBalanceUsd}&nbsp;US$
                                            </span>
                                        </p>
                                        {!canUseBalance ? (
                                            <p className="mt-2 text-xs text-destructive leading-snug">
                                                {withdrawableUsd < projection.amount
                                                    ? `Necesitas al menos ${projection.amount.toFixed(2)} US$ retirables para este monto (o cambia la cantidad a invertir).`
                                                    : null}
                                                {withdrawableUsd >= projection.amount && !meetsMinForBalance ? (
                                                    <span>El producto tiene un valor mínimo distinto.</span>
                                                ) : null}
                                            </p>
                                        ) : null}
                                    </div>
                                </div>
                            </button>
                        </div>
                        <InputError message={form.errors.funding_source} />
                    </div>

                    <div>
                        <h2 className="mb-3 text-base font-semibold">Resumen de inversión</h2>
                        <ProjectionSummary
                            projection={projection}
                            showInitialLabel="Monto"
                            totalLabel="Total esperado"
                            plusPrefix={false}
                        />
                    </div>

                    {fundingSource === 'blockchain' && !reinvestMode ? (
                        <div className="space-y-2">
                            <Label htmlFor="txid">TXID / hash de la transacción</Label>
                            <Input
                                autoCapitalize="none"
                                autoComplete="off"
                                className="text-sm"
                                id="txid"
                                name="txid"
                                onChange={(event) => form.setData('txid', event.target.value)}
                                placeholder="Pega aquí el identificador del envío"
                                required
                                spellCheck={false}
                                type="text"
                                value={form.data.txid}
                            />
                            <p className="text-muted-foreground text-xs">
                                Tras enviar los fondos a la dirección indicada (QR/sidebar), registra el txid aquí para
                                dejar una inversión pendiente hasta que operaciones confirme.
                            </p>
                            <InputError message={form.errors.txid} />
                        </div>
                    ) : null}

                    <InputError message={form.errors.amount} />

                    <div className="flex flex-col gap-3">
                        <Button
                            className="h-11 w-full font-semibold"
                            disabled={
                                form.processing ||
                                !canSubmitInvestment ||
                                (fundingSource === 'balance' && !canUseBalance)
                            }
                            type="submit"
                        >
                            {fundingSource === 'balance'
                                ? 'Recibir enlace y confirmar inversión con saldo'
                                : reinvestMode
                                  ? 'Recibir enlace y confirmar reinversión'
                                  : 'Recibir enlace y registrar inversión'}
                        </Button>
                        {!canSubmitInvestment ? (
                            <p className="text-center text-destructive text-xs">
                                No puedes enviar inversiones hasta completar tu verificación KYC.
                            </p>
                        ) : null}
                        <Button
                            className="h-11 w-full"
                            disabled={form.processing}
                            onClick={onCancel}
                            type="button"
                            variant="outline"
                        >
                            <ArrowLeft />
                            Cancelar
                        </Button>
                    </div>
                </form>
            </CardContent>
        </Card>
    );
}
