import { Head, Link, useForm } from '@inertiajs/react';
import { ChevronRight, Sprout } from 'lucide-react';
import { useState } from 'react';
import InvestmentController from '@/actions/App/Http/Controllers/InvestmentController';
import InputError from '@/components/input-error';
import EmptyState from '@/components/member/empty-state';
import MemberPage from '@/components/member/member-page';
import NairaInput from '@/components/member/naira-input';
import StatusBadge from '@/components/member/status-badge';
import { PinField } from '@/components/member/transfer-parts';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { formatDate, formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import { index, show } from '@/routes/investments';
import { show as kycShow } from '@/routes/kyc';
import type { InvestmentItem, InvestmentProductItem } from '@/types';

function months(count: number): string {
    return `${count} ${count === 1 ? 'month' : 'months'}`;
}

export default function InvestmentsIndex({
    investments,
    products,
    isVerified,
    hasPin,
    walletBalance,
}: {
    investments: InvestmentItem[];
    products: InvestmentProductItem[];
    isVerified: boolean;
    hasPin: boolean;
    walletBalance: number;
}) {
    const [chosen, setChosen] = useState<InvestmentProductItem | null>(null);
    const form = useForm({
        investment_product_id: '',
        amount: '',
        pin: '',
        acknowledge_risk: false,
    });

    const choose = (product: InvestmentProductItem) => {
        setChosen(product);
        form.clearErrors();
        form.setData({
            investment_product_id: String(product.id),
            amount: String(product.minimumAmount / 100),
            pin: '',
            acknowledge_risk: false,
        });
    };

    const submit = (event: React.FormEvent) => {
        event.preventDefault();
        form.submit(InvestmentController.store(), {
            preserveScroll: true,
            onFinish: () => form.reset('pin'),
        });
    };

    const active = investments.filter((item) => item.status === 'active');
    const invested = active.reduce((sum, item) => sum + item.amount, 0);

    return (
        <>
            <Head title="Investments" />

            <MemberPage
                title="Investments"
                description="Profit-sharing pools. Your money works in a real business and you share the profit or loss — returns are never guaranteed."
            >
                <section className="grid gap-3 sm:grid-cols-2">
                    <div className="rounded-landing-lg bg-brand-dark p-5 text-white">
                        <p className="text-sm text-white/70">
                            Currently invested
                        </p>
                        <p className="mt-1 font-display text-3xl font-semibold tabular-nums">
                            {formatNaira(invested)}
                        </p>
                        <p className="mt-1 text-sm text-white/70">
                            {active.length} active{' '}
                            {active.length === 1 ? 'investment' : 'investments'}
                        </p>
                    </div>
                    <div className="rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm">
                        <p className="text-sm text-ink-400">Wallet balance</p>
                        <p className="mt-1 font-display text-3xl font-semibold text-ink tabular-nums">
                            {formatNaira(walletBalance)}
                        </p>
                        <p className="mt-1 text-sm text-ink-400">
                            Investments are paid from your wallet.
                        </p>
                    </div>
                </section>

                {investments.length > 0 && (
                    <section className="rounded-landing-lg border border-surface-200 bg-white shadow-landing-sm">
                        <h2 className="border-b border-surface-200 px-5 py-3 font-semibold text-ink">
                            My investments
                        </h2>
                        <ul className="divide-y divide-surface-200">
                            {investments.map((item) => (
                                <li key={item.id}>
                                    <Link
                                        href={show(item.id)}
                                        className="flex items-center gap-3 px-5 py-3 hover:bg-surface-50"
                                    >
                                        <span className="min-w-0 flex-1">
                                            <span className="block truncate font-medium text-ink">
                                                {item.productName}
                                            </span>
                                            <span className="block text-xs text-ink-400">
                                                {item.reference} · matures{' '}
                                                {formatDate(item.maturityDate)}
                                            </span>
                                        </span>
                                        <span className="text-right">
                                            <span className="block font-semibold text-ink tabular-nums">
                                                {formatNaira(
                                                    item.payoutAmount ??
                                                        item.amount,
                                                )}
                                            </span>
                                            <StatusBadge
                                                tone={
                                                    item.status === 'paid_out'
                                                        ? 'success'
                                                        : item.hasMatured
                                                          ? 'pending'
                                                          : 'info'
                                                }
                                            >
                                                {item.status === 'active' &&
                                                item.hasMatured
                                                    ? 'Awaiting payout'
                                                    : item.statusLabel}
                                            </StatusBadge>
                                        </span>
                                        <ChevronRight className="size-4 text-ink-400" />
                                    </Link>
                                </li>
                            ))}
                        </ul>
                    </section>
                )}

                <section className="grid gap-3">
                    <h2 className="font-semibold text-ink">Open products</h2>

                    {!isVerified && (
                        <p className="rounded-landing border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900">
                            <Link
                                href={kycShow()}
                                className="font-semibold underline-offset-4 hover:underline"
                            >
                                Verify your identity
                            </Link>{' '}
                            before you invest.
                        </p>
                    )}

                    {products.length === 0 ? (
                        <EmptyState
                            icon={Sprout}
                            title="No products open right now"
                            description="New investment pools will appear here."
                        />
                    ) : (
                        <ul className="grid gap-3 lg:grid-cols-2">
                            {products.map((product) => (
                                <li
                                    key={product.id}
                                    className={cn(
                                        'flex flex-col gap-3 rounded-landing-lg border bg-white p-5 shadow-landing-sm',
                                        chosen?.id === product.id
                                            ? 'border-brand'
                                            : 'border-surface-200',
                                    )}
                                >
                                    <div>
                                        <p className="font-semibold text-ink">
                                            {product.name}
                                        </p>
                                        <p className="text-xs text-ink-400">
                                            {product.contractLabel}
                                        </p>
                                    </div>
                                    <p className="text-sm text-ink-700">
                                        {product.description}
                                    </p>
                                    <dl className="grid grid-cols-3 gap-2 text-sm">
                                        <div>
                                            <dt className="text-xs text-ink-400">
                                                Minimum
                                            </dt>
                                            <dd className="font-medium text-ink">
                                                {formatNaira(
                                                    product.minimumAmount,
                                                )}
                                            </dd>
                                        </div>
                                        <div>
                                            <dt className="text-xs text-ink-400">
                                                Term
                                            </dt>
                                            <dd className="font-medium text-ink">
                                                {months(product.tenorMonths)}
                                            </dd>
                                        </div>
                                        <div>
                                            <dt className="text-xs text-ink-400">
                                                Your profit share
                                            </dt>
                                            <dd className="font-medium text-ink">
                                                {product.memberProfitShare}%
                                            </dd>
                                        </div>
                                    </dl>
                                    <p className="text-xs text-ink-500">
                                        {product.projectionNote}
                                    </p>
                                    {isVerified &&
                                        chosen?.id !== product.id && (
                                            <Button
                                                type="button"
                                                variant="outline"
                                                className="self-start"
                                                onClick={() => choose(product)}
                                            >
                                                Invest
                                            </Button>
                                        )}
                                    {isVerified &&
                                        chosen?.id === product.id && (
                                            <form
                                                onSubmit={submit}
                                                className="grid gap-3 border-t border-surface-200 pt-3"
                                            >
                                                <div className="grid gap-2">
                                                    <Label
                                                        htmlFor="amount"
                                                        required
                                                    >
                                                        Amount
                                                    </Label>
                                                    <NairaInput
                                                        id="amount"
                                                        value={form.data.amount}
                                                        onChange={(event) =>
                                                            form.setData(
                                                                'amount',
                                                                event.target.value.replace(
                                                                    /[^\d.]/g,
                                                                    '',
                                                                ),
                                                            )
                                                        }
                                                    />
                                                    <InputError
                                                        message={
                                                            form.errors
                                                                .amount ??
                                                            form.errors
                                                                .investment_product_id
                                                        }
                                                    />
                                                </div>
                                                <PinField
                                                    hasPin={hasPin}
                                                    value={form.data.pin}
                                                    error={form.errors.pin}
                                                    onChange={(pin) =>
                                                        form.setData('pin', pin)
                                                    }
                                                />
                                                <label className="flex items-start gap-2 text-sm text-ink-700">
                                                    <input
                                                        type="checkbox"
                                                        checked={
                                                            form.data
                                                                .acknowledge_risk
                                                        }
                                                        onChange={(event) =>
                                                            form.setData(
                                                                'acknowledge_risk',
                                                                event.target
                                                                    .checked,
                                                            )
                                                        }
                                                        className="mt-0.5 size-4 accent-brand"
                                                    />
                                                    I understand returns are not
                                                    guaranteed and I may get
                                                    back less than I put in.
                                                </label>
                                                <InputError
                                                    message={
                                                        form.errors
                                                            .acknowledge_risk
                                                    }
                                                />
                                                <div className="flex gap-2">
                                                    <Button
                                                        disabled={
                                                            form.processing ||
                                                            !hasPin ||
                                                            form.data.pin
                                                                .length !== 4 ||
                                                            !form.data.amount
                                                        }
                                                    >
                                                        Invest from wallet
                                                    </Button>
                                                    <Button
                                                        type="button"
                                                        variant="ghost"
                                                        onClick={() =>
                                                            setChosen(null)
                                                        }
                                                    >
                                                        Cancel
                                                    </Button>
                                                </div>
                                            </form>
                                        )}
                                </li>
                            ))}
                        </ul>
                    )}
                </section>
            </MemberPage>
        </>
    );
}

InvestmentsIndex.layout = {
    breadcrumbs: [{ title: 'Investments', href: index() }],
};
