import { Head, Link, useForm } from '@inertiajs/react';
import { ArrowLeft } from 'lucide-react';
import type { FormEvent } from 'react';
import { 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,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

type Props = {
    investment_summary: {
        id: number;
        txid: string;
        capital_available_usd: string;
        investor_email: string | null | undefined;
        investor_name: string | null | undefined;
    };
};

export default function InvestmentWithdrawal({ investment_summary }: Props) {
    const form = useForm({ amount: '' });
    const [confirmOpen, setConfirmOpen] = useState(false);

    function submit(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        setConfirmOpen(true);
    }

    function executeWithdraw() {
        form.post(`/admin/inversiones/${investment_summary.id}/retiro`, {
            preserveScroll: true,
            onFinish: () => setConfirmOpen(false),
        });
    }

    return (
        <>
            <ConfirmActionModal
                cancelLabel="Revisar"
                confirmLabel="Sí, registrar retiro"
                confirmVariant="destructive"
                description="El capital vigente disponible de esta inversión se reducirá por el monto indicado."
                open={confirmOpen}
                processing={form.processing}
                title="¿Registrar este retiro administrativo?"
                onConfirm={executeWithdraw}
                onOpenChange={setConfirmOpen}
            >
                <div className="space-y-2 text-sm text-muted-foreground">
                    <p>
                        <span className="font-medium text-foreground">Monto:</span>{' '}
                        <span className="tabular-nums text-foreground">{form.data.amount.trim() || '—'} US$</span>
                    </p>
                    <p>
                        <span className="font-medium text-foreground">Inversionista:</span>{' '}
                        {investment_summary.investor_name ?? '—'} ({investment_summary.investor_email ?? '—'})
                    </p>
                </div>
            </ConfirmActionModal>

            <Head title="Registrar retiro" />

            <div className="mx-auto max-w-lg space-y-8">
                <Button asChild variant="ghost" size="sm" className="-ml-2">
                    <Link href="/admin/inversiones">
                        <ArrowLeft className="size-4" />
                        Volver
                    </Link>
                </Button>

                <Card>
                    <CardHeader>
                        <CardTitle>Registrar retiro</CardTitle>
                        <CardDescription>
                            Reduce el capital vigente disponible para futuras
                            acreditaciones mensuales. TXID{' '}
                            <code className="rounded bg-muted px-1 text-xs">
                                {investment_summary.txid}
                            </code>
                            .
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        <div className="rounded-md border bg-muted/30 p-4 text-sm">
                            <p>
                                <span className="text-muted-foreground">Inversionista:</span>{' '}
                                <strong>
                                    {investment_summary.investor_name ??
                                        '(sin nombre)'}
                                </strong>
                            </p>
                            <p className="text-muted-foreground text-xs mt-1">
                                {investment_summary.investor_email}
                            </p>
                            <p className="mt-3 tabular-nums">
                                Capital disponible:{' '}
                                <strong className="text-lg text-primary">
                                    {investment_summary.capital_available_usd} US$
                                </strong>
                            </p>
                        </div>

                        <form className="space-y-4" onSubmit={submit}>
                            <div className="space-y-2">
                                <Label htmlFor="amount">Monto retirado (US$)</Label>
                                <Input
                                    id="amount"
                                    inputMode="decimal"
                                    min="0.01"
                                    name="amount"
                                    placeholder="Ej. 50.00"
                                    required
                                    step="any"
                                    value={form.data.amount}
                                    onChange={(event) =>
                                        form.setData('amount', event.target.value)
                                    }
                                />
                                <InputError message={form.errors.amount} />
                            </div>
                            <Button disabled={form.processing} type="submit">
                                {form.processing ? 'Guardando…' : 'Registrar retiro'}
                            </Button>
                        </form>
                    </CardContent>
                </Card>
            </div>
        </>
    );
}

InvestmentWithdrawal.layout = {
    breadcrumbs: [
        { title: 'Administración', href: '/admin' },
        { title: 'Inversiones', href: '/admin/inversiones' },
        {
            title: 'Retiro',
            href: '#',
        },
    ],
};
