import { Form, Head, Link } from '@inertiajs/react';
import { Printer } from 'lucide-react';
import { useState } from 'react';
import WithdrawalController from '@/actions/App/Http/Controllers/Admin/WithdrawalController';
import InputError from '@/components/input-error';
import MemberPage from '@/components/member/member-page';
import WithdrawalDetails from '@/components/member/withdrawal-details';
import type { WithdrawalItem } from '@/components/member/withdrawal-status';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useInitials } from '@/hooks/use-initials';
import { formatNaira } from '@/lib/format';
import { index } from '@/routes/admin/withdrawals';
import { show as userShow } from '@/routes/admin/users';

type Member = {
    id: number;
    name: string;
    memberId: string;
    phone: string | null;
    kycStatusLabel: string;
    membershipStatusLabel: string;
    photoUrl: string | null;
    signatureUrl: string | null;
    walletBalance: number;
};

const textareaClasses =
    'w-full rounded-md border border-input bg-white px-3 py-2 text-sm outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15';

export default function AdminWithdrawalShow({
    withdrawal,
    member,
    canDecide,
}: {
    withdrawal: WithdrawalItem & {
        reviewedBy: string | null;
        paidBy: string | null;
    };
    member: Member;
    canDecide: boolean;
}) {
    const getInitials = useInitials();
    const [isRejecting, setIsRejecting] = useState(false);
    const isOpen =
        withdrawal.status === 'pending' || withdrawal.status === 'approved';

    return (
        <>
            <Head title={`Withdrawal ${withdrawal.reference}`} />

            <MemberPage
                title={`${member.name} · ${formatNaira(withdrawal.amount)}`}
                description={`${withdrawal.reference} · ${member.memberId}`}
                actions={
                    withdrawal.status === 'paid' && (
                        <button
                            type="button"
                            onClick={() => window.print()}
                            className="print-hidden inline-flex items-center gap-1.5 rounded-full bg-brand px-3.5 py-1.5 text-sm font-semibold text-white hover:bg-brand-hover"
                        >
                            <Printer className="size-4" />
                            Print receipt
                        </button>
                    )
                }
            >
                <div className="grid gap-4 lg:grid-cols-3">
                    <div className="lg:col-span-2">
                        <WithdrawalDetails
                            withdrawal={withdrawal}
                            reviewedBy={withdrawal.reviewedBy}
                            paidBy={withdrawal.paidBy}
                            memberLine={`${member.name} (${member.memberId})`}
                        />
                    </div>

                    <aside className="print-hidden grid content-start gap-4">
                        <section className="rounded-landing-lg border border-surface-200 bg-white p-4 shadow-landing-sm">
                            <h2 className="text-sm font-semibold text-ink">
                                Verify the member
                            </h2>
                            <div className="mt-3 flex items-center gap-3">
                                {member.photoUrl ? (
                                    <img
                                        src={member.photoUrl}
                                        alt={`Photo of ${member.name}`}
                                        className="size-14 rounded-full object-cover"
                                    />
                                ) : (
                                    <span className="flex size-14 items-center justify-center rounded-full bg-brand font-semibold text-white">
                                        {getInitials(member.name)}
                                    </span>
                                )}
                                <div className="min-w-0 text-sm">
                                    <Link
                                        href={userShow(member.id)}
                                        className="block truncate font-semibold text-ink hover:text-brand"
                                    >
                                        {member.name}
                                    </Link>
                                    <p className="text-xs text-ink-400">
                                        {member.phone ?? 'No phone'}
                                    </p>
                                    <p className="text-xs text-ink-400">
                                        {member.kycStatusLabel} ·{' '}
                                        {member.membershipStatusLabel}
                                    </p>
                                </div>
                            </div>
                            {member.signatureUrl ? (
                                <img
                                    src={member.signatureUrl}
                                    alt="Member signature"
                                    className="mt-3 h-16 w-full rounded-landing bg-surface-50 object-contain p-1"
                                />
                            ) : (
                                <p className="mt-3 rounded-landing bg-surface-50 px-3 py-2 text-xs text-ink-400">
                                    No signature on file.
                                </p>
                            )}
                            <p className="mt-3 text-xs text-ink-500">
                                Wallet after hold:{' '}
                                <strong className="text-ink">
                                    {formatNaira(member.walletBalance)}
                                </strong>
                            </p>
                        </section>

                        {isOpen && !canDecide && (
                            <p className="rounded-landing-lg border border-surface-200 bg-white p-4 text-sm text-ink-500">
                                Only staff who approve withdrawals, and who did
                                not request this one, can act on it.
                            </p>
                        )}

                        {canDecide &&
                            withdrawal.status === 'pending' &&
                            !isRejecting && (
                                <Form
                                    {...WithdrawalController.approve.form(
                                        withdrawal.id,
                                    )}
                                    className="grid gap-2 rounded-landing-lg border border-surface-200 bg-white p-4 shadow-landing-sm"
                                >
                                    {({ processing, errors }) => (
                                        <>
                                            <Label htmlFor="note">
                                                Note (optional)
                                            </Label>
                                            <textarea
                                                id="note"
                                                name="note"
                                                rows={2}
                                                maxLength={500}
                                                className={textareaClasses}
                                            />
                                            <InputError
                                                message={
                                                    errors.note ??
                                                    errors.withdrawal
                                                }
                                            />
                                            <div className="flex gap-2">
                                                <Button disabled={processing}>
                                                    Approve
                                                </Button>
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    onClick={() =>
                                                        setIsRejecting(true)
                                                    }
                                                >
                                                    Reject…
                                                </Button>
                                            </div>
                                        </>
                                    )}
                                </Form>
                            )}

                        {canDecide &&
                            withdrawal.status === 'approved' &&
                            !isRejecting && (
                                <Form
                                    {...WithdrawalController.pay.form(
                                        withdrawal.id,
                                    )}
                                    className="grid gap-2 rounded-landing-lg border-2 border-brand bg-white p-4 shadow-landing-sm"
                                >
                                    {({ processing, errors }) => (
                                        <>
                                            <p className="text-sm text-ink-700">
                                                Pay{' '}
                                                {formatNaira(withdrawal.amount)}{' '}
                                                as{' '}
                                                {withdrawal.paymentMethodLabel.toLowerCase()}
                                                , then record it here.
                                            </p>
                                            <Label
                                                htmlFor="payment_reference"
                                                required
                                            >
                                                {withdrawal.paymentMethod ===
                                                'bank_transfer'
                                                    ? 'Bank transfer reference'
                                                    : 'Cash voucher number'}
                                            </Label>
                                            <Input
                                                id="payment_reference"
                                                name="payment_reference"
                                                required
                                                minLength={3}
                                                maxLength={60}
                                            />
                                            <InputError
                                                message={
                                                    errors.payment_reference ??
                                                    errors.withdrawal
                                                }
                                            />
                                            <div className="flex gap-2">
                                                <Button disabled={processing}>
                                                    Mark as paid
                                                </Button>
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    onClick={() =>
                                                        setIsRejecting(true)
                                                    }
                                                >
                                                    Reject…
                                                </Button>
                                            </div>
                                        </>
                                    )}
                                </Form>
                            )}

                        {canDecide && isOpen && isRejecting && (
                            <Form
                                {...WithdrawalController.reject.form(
                                    withdrawal.id,
                                )}
                                className="grid gap-2 rounded-landing-lg border border-red-200 bg-white p-4 shadow-landing-sm"
                            >
                                {({ processing, errors }) => (
                                    <>
                                        <Label htmlFor="reason" required>
                                            Reason the member will see
                                        </Label>
                                        <textarea
                                            id="reason"
                                            name="reason"
                                            rows={3}
                                            required
                                            minLength={5}
                                            maxLength={500}
                                            autoFocus
                                            className={textareaClasses}
                                        />
                                        <p className="text-xs text-ink-400">
                                            The held money goes back to the
                                            member’s wallet.
                                        </p>
                                        <InputError
                                            message={
                                                errors.reason ??
                                                errors.withdrawal
                                            }
                                        />
                                        <div className="flex gap-2">
                                            <Button
                                                variant="destructive"
                                                disabled={processing}
                                            >
                                                Reject withdrawal
                                            </Button>
                                            <Button
                                                type="button"
                                                variant="ghost"
                                                onClick={() =>
                                                    setIsRejecting(false)
                                                }
                                            >
                                                Back
                                            </Button>
                                        </div>
                                    </>
                                )}
                            </Form>
                        )}
                    </aside>
                </div>
            </MemberPage>
        </>
    );
}

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