import { Form, Head, Link } from '@inertiajs/react';
import { ArrowLeft, Check, Download, FileText, X } from 'lucide-react';
import { useState } from 'react';
import KycReviewController from '@/actions/App/Http/Controllers/Admin/KycReviewController';
import InputError from '@/components/input-error';
import MemberPage from '@/components/member/member-page';
import StatusBadge from '@/components/member/status-badge';
import type { BadgeTone } from '@/components/member/status-badge';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { formatDate, formatDateTime } from '@/lib/format';
import { index, show } from '@/routes/admin/kyc';
import { show as userShow } from '@/routes/admin/users';

type KycDocumentItem = {
    id: number;
    typeLabel: string;
    status: string;
    statusLabel: string;
    rejectionReason: string | null;
    originalName: string;
    uploadedAt: string | null;
    reviewedAt: string | null;
};

const tones: Record<string, BadgeTone> = {
    approved: 'success',
    pending: 'pending',
    rejected: 'failed',
};

export default function KycDocumentShow({
    document,
    member,
    otherDocuments,
    canReview,
}: {
    document: KycDocumentItem & {
        mimeType: string;
        size: number;
        fileUrl: string;
    };
    member: {
        id: number;
        name: string;
        memberId: string;
        email: string;
        phone: string | null;
        idNumber: string | null;
        dateOfBirth: string | null;
        address: string | null;
        avatar: string | null;
        kycStatus: string;
    };
    otherDocuments: KycDocumentItem[];
    canReview: boolean;
}) {
    const [rejecting, setRejecting] = useState(false);
    const isImage = document.mimeType.startsWith('image/');
    const isPdf = document.mimeType === 'application/pdf';

    const details: [string, string][] = [
        ['Member ID', member.memberId],
        ['Email', member.email],
        ['Phone', member.phone ?? '—'],
        ['ID number', member.idNumber ?? '—'],
        ['Date of birth', formatDate(member.dateOfBirth)],
        ['Address', member.address ?? '—'],
        ['Verification', member.kycStatus],
    ];

    return (
        <>
            <Head title={`${document.typeLabel} — ${member.name}`} />

            <MemberPage
                title={document.typeLabel}
                description={`${member.name} · uploaded ${formatDateTime(document.uploadedAt)}`}
                actions={
                    <Link
                        href={index()}
                        className="inline-flex items-center gap-1.5 rounded-full border border-surface-200 bg-white px-3.5 py-1.5 text-sm font-semibold text-ink-700 hover:border-brand/40"
                    >
                        <ArrowLeft className="size-4" />
                        Back to queue
                    </Link>
                }
            >
                <div className="grid gap-4 lg:grid-cols-[1fr_20rem]">
                    <section className="grid gap-3 rounded-landing-lg border border-surface-200 bg-white p-4 shadow-landing-sm">
                        <div className="flex flex-wrap items-center justify-between gap-2">
                            <span className="flex min-w-0 items-center gap-2 text-sm text-ink-700">
                                <FileText className="size-4 shrink-0 text-ink-400" />
                                <span className="truncate">
                                    {document.originalName}
                                </span>
                                <span className="shrink-0 text-xs text-ink-400">
                                    {Math.max(
                                        1,
                                        Math.round(document.size / 1024),
                                    )}{' '}
                                    KB
                                </span>
                            </span>
                            <StatusBadge
                                tone={tones[document.status] ?? 'neutral'}
                            >
                                {document.statusLabel}
                            </StatusBadge>
                        </div>

                        <div className="flex min-h-96 items-center justify-center overflow-hidden rounded-landing bg-surface-100">
                            {isImage ? (
                                <img
                                    src={document.fileUrl}
                                    alt={`${document.typeLabel} uploaded by ${member.name}`}
                                    className="max-h-[75vh] w-auto object-contain"
                                />
                            ) : isPdf ? (
                                <iframe
                                    src={document.fileUrl}
                                    title={`${document.typeLabel} uploaded by ${member.name}`}
                                    className="h-[75vh] w-full border-0 bg-white"
                                />
                            ) : (
                                <p className="p-6 text-sm text-ink-500">
                                    This file type cannot be shown here.
                                </p>
                            )}
                        </div>

                        <a
                            href={document.fileUrl}
                            download={document.originalName}
                            className="inline-flex w-fit items-center gap-1.5 text-sm font-semibold text-brand hover:underline"
                        >
                            <Download className="size-4" />
                            Download file
                        </a>
                    </section>

                    <aside className="grid content-start gap-4">
                        <section className="rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm">
                            <div className="flex items-center gap-3">
                                {member.avatar ? (
                                    <img
                                        src={member.avatar}
                                        alt=""
                                        className="size-12 rounded-full object-cover"
                                    />
                                ) : (
                                    <span className="flex size-12 items-center justify-center rounded-full bg-brand-faint font-semibold text-brand">
                                        {member.name.charAt(0)}
                                    </span>
                                )}
                                <Link
                                    href={userShow(member.id)}
                                    className="min-w-0 font-semibold text-ink hover:text-brand"
                                >
                                    {member.name}
                                </Link>
                            </div>
                            <dl className="mt-4 grid gap-2 text-sm">
                                {details.map(([term, detail]) => (
                                    <div
                                        key={term}
                                        className="flex justify-between gap-3"
                                    >
                                        <dt className="shrink-0 text-ink-400">
                                            {term}
                                        </dt>
                                        <dd className="text-right font-medium break-words text-ink">
                                            {detail}
                                        </dd>
                                    </div>
                                ))}
                            </dl>
                        </section>

                        {canReview ? (
                            <section className="grid gap-3 rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm">
                                <h2 className="font-semibold text-ink">
                                    Decision
                                </h2>
                                {!rejecting ? (
                                    <div className="flex gap-2">
                                        <Form
                                            {...KycReviewController.approve.form(
                                                document.id,
                                            )}
                                        >
                                            {({ processing }) => (
                                                <Button disabled={processing}>
                                                    <Check className="size-4" />
                                                    Approve
                                                </Button>
                                            )}
                                        </Form>
                                        <Button
                                            type="button"
                                            variant="outline"
                                            onClick={() => setRejecting(true)}
                                        >
                                            <X className="size-4" />
                                            Reject
                                        </Button>
                                    </div>
                                ) : (
                                    <Form
                                        {...KycReviewController.reject.form(
                                            document.id,
                                        )}
                                        className="grid gap-3"
                                    >
                                        {({ processing, errors }) => (
                                            <>
                                                <div className="grid gap-2">
                                                    <Label
                                                        htmlFor="reason"
                                                        required
                                                    >
                                                        Reason the member will
                                                        see
                                                    </Label>
                                                    <textarea
                                                        id="reason"
                                                        name="reason"
                                                        required
                                                        minLength={5}
                                                        maxLength={500}
                                                        rows={3}
                                                        autoFocus
                                                        className="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"
                                                        placeholder="e.g. The photo is blurry — please upload a clearer copy."
                                                    />
                                                    <InputError
                                                        message={errors.reason}
                                                    />
                                                </div>
                                                <div className="flex gap-2">
                                                    <Button
                                                        variant="destructive"
                                                        disabled={processing}
                                                    >
                                                        Reject document
                                                    </Button>
                                                    <Button
                                                        type="button"
                                                        variant="ghost"
                                                        onClick={() =>
                                                            setRejecting(false)
                                                        }
                                                    >
                                                        Cancel
                                                    </Button>
                                                </div>
                                            </>
                                        )}
                                    </Form>
                                )}
                            </section>
                        ) : (
                            document.status === 'pending' && (
                                <p className="rounded-landing border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900">
                                    You cannot review your own document.
                                </p>
                            )
                        )}

                        {document.rejectionReason && (
                            <p className="rounded-landing border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800">
                                Rejected: {document.rejectionReason}
                            </p>
                        )}

                        {otherDocuments.length > 0 && (
                            <section className="rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm">
                                <h2 className="font-semibold text-ink">
                                    Other documents
                                </h2>
                                <ul className="mt-3 grid gap-2 text-sm">
                                    {otherDocuments.map((other) => (
                                        <li key={other.id}>
                                            <Link
                                                href={show(other.id)}
                                                className="flex items-center justify-between gap-2 hover:text-brand"
                                            >
                                                <span className="truncate">
                                                    {other.typeLabel}
                                                </span>
                                                <StatusBadge
                                                    tone={
                                                        tones[other.status] ??
                                                        'neutral'
                                                    }
                                                >
                                                    {other.statusLabel}
                                                </StatusBadge>
                                            </Link>
                                        </li>
                                    ))}
                                </ul>
                            </section>
                        )}
                    </aside>
                </div>
            </MemberPage>
        </>
    );
}

KycDocumentShow.layout = {
    breadcrumbs: [{ title: 'KYC review', href: index() }],
};
