import { Head, useForm } from '@inertiajs/react';
import { Pencil, Plus, Sprout } from 'lucide-react';
import { useState } from 'react';
import InvestmentPayoutController from '@/actions/App/Http/Controllers/Admin/InvestmentPayoutController';
import InvestmentProductController from '@/actions/App/Http/Controllers/Admin/InvestmentProductController';
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 { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { formatDate, formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import { index } from '@/routes/admin/investments';
import type {
    InvestmentItem,
    InvestmentProductItem,
    SelectOption,
} from '@/types';

type Product = InvestmentProductItem & {
    activeCount: number;
    activeTotal: number;
};

type Matured = InvestmentItem & {
    memberProfitShare: number;
    member: { name: string; email: string };
};

const fieldClasses =
    'h-9 w-full rounded-md border border-input bg-white px-3 text-sm text-ink shadow-xs';

function ProductForm({
    product,
    contracts,
    onDone,
}: {
    product: Product | null;
    contracts: SelectOption[];
    onDone: () => void;
}) {
    const form = useForm({
        name: product?.name ?? '',
        contract: product?.contract ?? contracts[0]?.value ?? '',
        description: product?.description ?? '',
        minimum_amount: product ? String(product.minimumAmount / 100) : '',
        tenor_months: product ? String(product.tenorMonths) : '12',
        member_profit_share: product ? String(product.memberProfitShare) : '60',
        projection_note: product?.projectionNote ?? '',
        is_active: product?.isActive ?? true,
    });

    const submit = (event: React.FormEvent) => {
        event.preventDefault();
        form.submit(
            product
                ? InvestmentProductController.update(product.id)
                : InvestmentProductController.store(),
            { preserveScroll: true, onSuccess: onDone },
        );
    };

    return (
        <form
            onSubmit={submit}
            className="grid gap-4 rounded-landing-lg border border-brand/30 bg-white p-5 shadow-landing-sm"
        >
            <h2 className="font-semibold text-ink">
                {product ? `Edit ${product.name}` : 'New product'}
            </h2>
            <div className="grid gap-4 sm:grid-cols-2">
                <div className="grid gap-2">
                    <Label htmlFor="name" required>
                        Name
                    </Label>
                    <Input
                        id="name"
                        value={form.data.name}
                        onChange={(event) =>
                            form.setData('name', event.target.value)
                        }
                    />
                    <InputError message={form.errors.name} />
                </div>
                <div className="grid gap-2">
                    <Label htmlFor="contract" required>
                        Contract
                    </Label>
                    <select
                        id="contract"
                        value={form.data.contract}
                        onChange={(event) =>
                            form.setData('contract', event.target.value)
                        }
                        className={fieldClasses}
                    >
                        {contracts.map((contract) => (
                            <option key={contract.value} value={contract.value}>
                                {contract.label}
                            </option>
                        ))}
                    </select>
                    <InputError message={form.errors.contract} />
                </div>
            </div>
            <div className="grid gap-2">
                <Label htmlFor="description" required>
                    What the money is used for
                </Label>
                <textarea
                    id="description"
                    rows={3}
                    value={form.data.description}
                    onChange={(event) =>
                        form.setData('description', event.target.value)
                    }
                    className="w-full rounded-md border border-input bg-white px-3 py-2 text-sm text-ink shadow-xs"
                />
                <InputError message={form.errors.description} />
            </div>
            <div className="grid gap-4 sm:grid-cols-3">
                <div className="grid content-start gap-2">
                    <Label htmlFor="minimum_amount" required>
                        Minimum amount
                    </Label>
                    <NairaInput
                        id="minimum_amount"
                        value={form.data.minimum_amount}
                        onChange={(event) =>
                            form.setData(
                                'minimum_amount',
                                event.target.value.replace(/[^\d.]/g, ''),
                            )
                        }
                    />
                    <InputError message={form.errors.minimum_amount} />
                </div>
                <div className="grid content-start gap-2">
                    <Label htmlFor="tenor_months" required>
                        Term (months)
                    </Label>
                    <Input
                        id="tenor_months"
                        type="number"
                        min={1}
                        max={60}
                        value={form.data.tenor_months}
                        onChange={(event) =>
                            form.setData('tenor_months', event.target.value)
                        }
                    />
                    <InputError message={form.errors.tenor_months} />
                </div>
                <div className="grid content-start gap-2">
                    <Label htmlFor="member_profit_share" required>
                        Members' profit share (%)
                    </Label>
                    <Input
                        id="member_profit_share"
                        type="number"
                        min={1}
                        max={99}
                        value={form.data.member_profit_share}
                        onChange={(event) =>
                            form.setData(
                                'member_profit_share',
                                event.target.value,
                            )
                        }
                    />
                    <InputError message={form.errors.member_profit_share} />
                </div>
            </div>
            <div className="grid gap-2">
                <Label htmlFor="projection_note" required>
                    Projection note
                </Label>
                <Input
                    id="projection_note"
                    value={form.data.projection_note}
                    placeholder="e.g. Projected 8–12% over nine months. Not guaranteed."
                    onChange={(event) =>
                        form.setData('projection_note', event.target.value)
                    }
                />
                <InputError message={form.errors.projection_note} />
            </div>
            <label className="flex items-center gap-2 text-sm text-ink-700">
                <input
                    type="checkbox"
                    checked={form.data.is_active}
                    onChange={(event) =>
                        form.setData('is_active', event.target.checked)
                    }
                    className="size-4 accent-brand"
                />
                Open to members
            </label>
            <div className="flex gap-2">
                <Button disabled={form.processing}>
                    {product ? 'Save changes' : 'Create product'}
                </Button>
                <Button type="button" variant="ghost" onClick={onDone}>
                    Cancel
                </Button>
            </div>
        </form>
    );
}

function PayoutRow({ investment }: { investment: Matured }) {
    const form = useForm({ payout_amount: String(investment.amount / 100) });

    const submit = (event: React.FormEvent) => {
        event.preventDefault();

        if (
            window.confirm(
                `Post ₦${form.data.payout_amount} to ${investment.member.name}'s wallet for ${investment.reference}?`,
            )
        ) {
            form.submit(InvestmentPayoutController(investment.id), {
                preserveScroll: true,
            });
        }
    };

    return (
        <li className="grid gap-3 px-5 py-4 sm:grid-cols-[1fr_auto] sm:items-end">
            <div className="min-w-0">
                <p className="truncate font-medium text-ink">
                    {investment.member.name}
                </p>
                <p className="text-xs text-ink-400">
                    {investment.productName} · {investment.reference} ·{' '}
                    {formatNaira(investment.amount)} invested · matured{' '}
                    {formatDate(investment.maturityDate)} · members get{' '}
                    {investment.memberProfitShare}% of profit
                </p>
            </div>
            <form onSubmit={submit} className="flex items-start gap-2">
                <div className="grid gap-1">
                    <Label
                        htmlFor={`payout-${investment.id}`}
                        className="sr-only"
                    >
                        Final value for {investment.reference}
                    </Label>
                    <NairaInput
                        id={`payout-${investment.id}`}
                        value={form.data.payout_amount}
                        onChange={(event) =>
                            form.setData(
                                'payout_amount',
                                event.target.value.replace(/[^\d.]/g, ''),
                            )
                        }
                        className="w-40"
                    />
                    <InputError message={form.errors.payout_amount} />
                </div>
                <Button
                    size="sm"
                    className="h-10"
                    disabled={form.processing || !form.data.payout_amount}
                >
                    Pay out
                </Button>
            </form>
        </li>
    );
}

export default function AdminInvestmentsIndex({
    products,
    maturedInvestments,
    contracts,
}: {
    products: Product[];
    maturedInvestments: Matured[];
    contracts: SelectOption[];
}) {
    const [editing, setEditing] = useState<Product | 'new' | null>(null);

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

            <MemberPage
                title="Investments"
                description="Profit-sharing products members can join, and matured investments waiting for their final value."
                actions={
                    editing === null && (
                        <Button size="sm" onClick={() => setEditing('new')}>
                            <Plus className="size-4" />
                            New product
                        </Button>
                    )
                }
            >
                {editing !== null && (
                    <ProductForm
                        key={editing === 'new' ? 'new' : editing.id}
                        product={editing === 'new' ? null : editing}
                        contracts={contracts}
                        onDone={() => setEditing(null)}
                    />
                )}

                <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">
                        Matured, awaiting payout ({maturedInvestments.length})
                    </h2>
                    {maturedInvestments.length === 0 ? (
                        <p className="px-5 py-4 text-sm text-ink-400">
                            Nothing to pay out. Investments appear here on their
                            maturity date.
                        </p>
                    ) : (
                        <ul className="divide-y divide-surface-200">
                            {maturedInvestments.map((investment) => (
                                <PayoutRow
                                    key={investment.id}
                                    investment={investment}
                                />
                            ))}
                        </ul>
                    )}
                </section>

                {products.length === 0 ? (
                    <EmptyState
                        icon={Sprout}
                        title="No investment products yet"
                        description="Create a Mudarabah or Musharakah pool for members to join."
                    />
                ) : (
                    <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 border-surface-200 bg-white p-5 shadow-landing-sm',
                                    !product.isActive && 'opacity-70',
                                )}
                            >
                                <div className="flex items-start gap-3">
                                    <div className="min-w-0 flex-1">
                                        <p className="flex flex-wrap items-center gap-1.5 font-semibold text-ink">
                                            {product.name}
                                            {!product.isActive && (
                                                <StatusBadge tone="neutral">
                                                    Closed
                                                </StatusBadge>
                                            )}
                                        </p>
                                        <p className="text-xs text-ink-400">
                                            {product.contractLabel}
                                        </p>
                                    </div>
                                    <button
                                        type="button"
                                        onClick={() => setEditing(product)}
                                        className="rounded-full p-1.5 text-ink-400 hover:bg-surface-100 hover:text-ink"
                                        aria-label={`Edit ${product.name}`}
                                    >
                                        <Pencil className="size-4" />
                                    </button>
                                </div>
                                <p className="text-sm text-ink-700">
                                    {product.description}
                                </p>
                                <dl className="grid grid-cols-2 gap-2 text-sm sm:grid-cols-4">
                                    {[
                                        [
                                            'Minimum',
                                            formatNaira(product.minimumAmount),
                                        ],
                                        [
                                            'Term',
                                            `${product.tenorMonths} months`,
                                        ],
                                        [
                                            'Members get',
                                            `${product.memberProfitShare}%`,
                                        ],
                                        [
                                            'Active',
                                            `${product.activeCount} · ${formatNaira(product.activeTotal)}`,
                                        ],
                                    ].map(([term, detail]) => (
                                        <div key={term}>
                                            <dt className="text-xs text-ink-400">
                                                {term}
                                            </dt>
                                            <dd className="font-medium text-ink">
                                                {detail}
                                            </dd>
                                        </div>
                                    ))}
                                </dl>
                            </li>
                        ))}
                    </ul>
                )}
            </MemberPage>
        </>
    );
}

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