import { Form, Head } from '@inertiajs/react';
import {
    CheckCircle2,
    Clock,
    FileUp,
    ShieldAlert,
    ShieldCheck,
    XCircle,
} from 'lucide-react';
import type { ReactNode } from 'react';
import KycController from '@/actions/App/Http/Controllers/KycController';
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 { formatDate } from '@/lib/format';
import { cn } from '@/lib/utils';
import { show } from '@/routes/kyc';
import { file } from '@/routes/kyc/documents';
import { RequiredMark } from '@/components/required-mark';

type Requirement = {
    key: string;
    label: string;
    state: 'approved' | 'pending' | 'rejected' | 'missing';
};

type KycDocumentItem = {
    id: number;
    type: string;
    typeLabel: string;
    status: 'pending' | 'approved' | 'rejected';
    statusLabel: string;
    rejectionReason: string | null;
    originalName: string;
    uploadedAt: string | null;
};

type DocumentTypeOption = { value: string; label: string; requirement: string };

type Props = {
    status: 'unverified' | 'pending' | 'verified' | 'rejected';
    statusLabel: string;
    requirements: Requirement[];
    documents: KycDocumentItem[];
    documentTypes: DocumentTypeOption[];
};

const statusCopy: Record<
    Props['status'],
    { title: string; body: string; icon: typeof ShieldCheck; tone: string }
> = {
    verified: {
        title: 'You are verified',
        body: 'Your identity has been confirmed. All member features are available to you.',
        icon: ShieldCheck,
        tone: 'border-highlight/30 bg-highlight-faint text-highlight-dark',
    },
    pending: {
        title: 'Your documents are under review',
        body: 'We usually review documents within 24–48 hours. We will notify you when it is done.',
        icon: Clock,
        tone: 'border-amber-200 bg-amber-50 text-amber-800',
    },
    rejected: {
        title: 'Some documents need attention',
        body: 'Check the reason below and upload a new copy.',
        icon: ShieldAlert,
        tone: 'border-red-200 bg-red-50 text-red-800',
    },
    unverified: {
        title: 'Verify your identity',
        body: 'Upload one document for each requirement below to unlock savings, financing and transfers.',
        icon: ShieldAlert,
        tone: 'border-brand-border bg-brand-faint text-brand',
    },
};

const requirementState: Record<
    Requirement['state'],
    { icon: ReactNode; text: string }
> = {
    approved: {
        icon: <CheckCircle2 className="size-5 text-highlight" />,
        text: 'Approved',
    },
    pending: {
        icon: <Clock className="size-5 text-amber-600" />,
        text: 'Under review',
    },
    rejected: {
        icon: <XCircle className="size-5 text-red-600" />,
        text: 'Upload again',
    },
    missing: {
        icon: <span className="size-5 rounded-full border-2 border-ink-200" />,
        text: 'Not uploaded',
    },
};

const documentTone: Record<KycDocumentItem['status'], BadgeTone> = {
    approved: 'success',
    pending: 'pending',
    rejected: 'failed',
};

export default function KycShow({
    status,
    requirements,
    documents,
    documentTypes,
}: Props) {
    const banner = statusCopy[status];
    const BannerIcon = banner.icon;

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

            <MemberPage
                title="Identity verification"
                description="We verify every member to keep the cooperative safe."
            >
                <div
                    className={cn(
                        'flex items-start gap-3 rounded-landing-lg border px-5 py-4',
                        banner.tone,
                    )}
                >
                    <BannerIcon className="mt-0.5 size-5 shrink-0" />
                    <div>
                        <p className="font-semibold">{banner.title}</p>
                        <p className="mt-0.5 text-sm opacity-90">
                            {banner.body}
                        </p>
                    </div>
                </div>

                <section aria-labelledby="requirements-heading">
                    <h2 id="requirements-heading" className="sr-only">
                        Requirements
                    </h2>
                    <ul className="grid gap-3 sm:grid-cols-3">
                        {requirements.map((requirement) => (
                            <li
                                key={requirement.key}
                                className="flex items-center gap-3 rounded-landing-lg border border-surface-200 bg-white p-4"
                            >
                                {requirementState[requirement.state].icon}
                                <div>
                                    <p className="text-sm font-semibold text-ink">
                                        {requirement.label}
                                    </p>
                                    <p className="text-xs text-ink-400">
                                        {
                                            requirementState[requirement.state]
                                                .text
                                        }
                                    </p>
                                </div>
                            </li>
                        ))}
                    </ul>
                </section>

                {status !== 'verified' && (
                    <section
                        aria-labelledby="upload-heading"
                        className="rounded-landing-lg border border-surface-200 bg-white p-5 sm:p-6"
                    >
                        <h2
                            id="upload-heading"
                            className="font-display text-lg font-semibold text-ink"
                        >
                            Upload a document
                        </h2>
                        <p className="mt-1 text-sm text-ink-500">
                            Clear photo or scan, all four corners visible. JPG,
                            PNG or PDF up to 5 MB.
                        </p>

                        <Form
                            {...KycController.store.form()}
                            resetOnSuccess
                            options={{ preserveScroll: true }}
                            className="mt-5 grid gap-4 sm:grid-cols-[1fr_1fr_auto] sm:items-start"
                        >
                            {({ processing, errors, progress }) => (
                                <>
                                    <div className="grid gap-1.5">
                                        <label
                                            htmlFor="type"
                                            className="text-sm font-semibold text-ink-700"
                                        >
                                            Document type
                                            <RequiredMark />
                                        </label>
                                        <select
                                            id="type"
                                            name="type"
                                            required
                                            defaultValue=""
                                            className="h-10 rounded-md border border-input bg-white px-3 text-sm text-ink shadow-xs outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15"
                                        >
                                            <option value="" disabled>
                                                Choose…
                                            </option>
                                            {requirements.map((requirement) => (
                                                <optgroup
                                                    key={requirement.key}
                                                    label={requirement.label}
                                                >
                                                    {documentTypes
                                                        .filter(
                                                            (type) =>
                                                                type.requirement ===
                                                                requirement.key,
                                                        )
                                                        .map((type) => (
                                                            <option
                                                                key={type.value}
                                                                value={
                                                                    type.value
                                                                }
                                                            >
                                                                {type.label}
                                                            </option>
                                                        ))}
                                                </optgroup>
                                            ))}
                                        </select>
                                        <InputError message={errors.type} />
                                    </div>

                                    <div className="grid gap-1.5">
                                        <label
                                            htmlFor="document"
                                            className="text-sm font-semibold text-ink-700"
                                        >
                                            File
                                            <RequiredMark />
                                        </label>
                                        <input
                                            id="document"
                                            name="document"
                                            type="file"
                                            required
                                            accept=".jpg,.jpeg,.png,.pdf"
                                            className="block w-full text-sm text-ink-500 file:mr-3 file:rounded-full file:border-0 file:bg-brand-faint file:px-4 file:py-2 file:text-sm file:font-semibold file:text-brand hover:file:bg-brand-border"
                                        />
                                        {progress && (
                                            <progress
                                                value={progress.percentage}
                                                max="100"
                                                className="h-1.5 w-full"
                                            >
                                                {progress.percentage}%
                                            </progress>
                                        )}
                                        <InputError message={errors.document} />
                                    </div>

                                    <Button
                                        disabled={processing}
                                        className="sm:mt-6.5"
                                    >
                                        <FileUp className="size-4" />
                                        Upload
                                    </Button>
                                </>
                            )}
                        </Form>
                    </section>
                )}

                {documents.length > 0 && (
                    <section
                        aria-labelledby="documents-heading"
                        className="overflow-hidden rounded-landing-lg border border-surface-200 bg-white"
                    >
                        <h2
                            id="documents-heading"
                            className="px-5 py-4 font-display text-lg font-semibold text-ink"
                        >
                            Your documents
                        </h2>
                        <ul className="divide-y divide-surface-100 border-t border-surface-100">
                            {documents.map((document) => (
                                <li
                                    key={document.id}
                                    className="flex flex-wrap items-center gap-3 px-5 py-3.5"
                                >
                                    <div className="min-w-0 flex-1">
                                        <p className="text-sm font-semibold text-ink">
                                            {document.typeLabel}
                                        </p>
                                        <p className="truncate text-xs text-ink-400">
                                            {document.originalName} · uploaded{' '}
                                            {formatDate(document.uploadedAt)}
                                        </p>
                                        {document.rejectionReason && (
                                            <p className="mt-1 text-xs text-red-700">
                                                {document.rejectionReason}
                                            </p>
                                        )}
                                    </div>
                                    <StatusBadge
                                        tone={documentTone[document.status]}
                                    >
                                        {document.statusLabel}
                                    </StatusBadge>
                                    <a
                                        href={file.url(document.id)}
                                        target="_blank"
                                        rel="noopener"
                                        className="text-sm font-semibold text-brand hover:text-highlight-dark"
                                    >
                                        View
                                    </a>
                                </li>
                            ))}
                        </ul>
                    </section>
                )}
            </MemberPage>
        </>
    );
}

KycShow.layout = {
    breadcrumbs: [{ title: 'Verification', href: show() }],
};
