import { Head, Link, router } from '@inertiajs/react';
import { ArrowDownToLine, ArrowLeft } from 'lucide-react';
import { useState, type ReactNode } from 'react';
import { documentDownload } from '@/routes/admin/kyc';
import { ConfirmActionModal } from '@/components/confirm-action-modal';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardFooter,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';

type Props = {
    user: {
        id: number;
        name: string;
        email: string;
    };
    profile: {
        legal_first_name: string;
        legal_last_name: string;
        date_of_birth: string;
        document_type: string;
        document_number: string;
        document_issuing_country: string;
        country_of_residence: string;
        address_line1: string;
        address_line2: string | null;
        city: string;
        region_state: string;
        postal_code: string;
        occupation: string | null;
        document_front_path: string;
        document_back_path: string | null;
        selfie_document_path: string | null;
        submitted_at: string | null;
    };
};

const DOC_LABELS: Record<string, string> = {
    national_id: 'Documento nacional de identidad',
    passport: 'Pasaporte',
    drivers_license: 'Licencia de conducir',
    residence_card: 'Tarjeta de residencia / permiso migratorio',
};

export default function AdminKycDetail({ user, profile }: Props) {
    const [rejectReason, setRejectReason] = useState('');
    const [rejecting, setRejecting] = useState(false);
    const [approving, setApproving] = useState(false);
    const [approveConfirmOpen, setApproveConfirmOpen] = useState(false);
    const [rejectConfirmOpen, setRejectConfirmOpen] = useState(false);

    function approve() {
        setApproving(true);
        router.patch(`/admin/verificacion-kyc/usuarios/${user.id}/aprobar`, {}, {
            preserveScroll: true,
            onFinish: () => {
                setApproving(false);
                setApproveConfirmOpen(false);
            },
        });
    }

    function reject(e: React.FormEvent) {
        e.preventDefault();
        if (rejectReason.trim() === '') {
            return;
        }
        setRejectConfirmOpen(true);
    }

    function executeReject() {
        setRejecting(true);
        router.patch(`/admin/verificacion-kyc/usuarios/${user.id}/rechazar`, { reason: rejectReason.trim() }, {
            preserveScroll: true,
            onFinish: () => {
                setRejecting(false);
                setRejectConfirmOpen(false);
            },
        });
    }

    const docLabel = DOC_LABELS[profile.document_type] ?? profile.document_type;

    return (
        <>
            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, aprobar identidad"
                description="El usuario podrá invertir y operar según la política KYC vigente."
                open={approveConfirmOpen}
                processing={approving}
                title="¿Aprobar la verificación de identidad?"
                onConfirm={approve}
                onOpenChange={setApproveConfirmOpen}
            >
                <p className="text-sm text-muted-foreground">
                    Cuenta: <strong className="text-foreground">{user.email}</strong>
                </p>
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Volver"
                confirmLabel="Sí, rechazar"
                confirmVariant="destructive"
                description="El usuario deberá corregir su expediente y volver a enviar documentación si aplica."
                open={rejectConfirmOpen}
                processing={rejecting}
                title="¿Rechazar esta verificación de identidad?"
                onConfirm={executeReject}
                onOpenChange={setRejectConfirmOpen}
            >
                <div className="space-y-2 text-sm text-muted-foreground">
                    <p>
                        Cuenta: <strong className="text-foreground">{user.email}</strong>
                    </p>
                    {rejectReason.trim() ? (
                        <p className="border-t pt-2 whitespace-pre-wrap text-xs">
                            <span className="font-medium text-foreground">Motivo:</span> {rejectReason.trim()}
                        </p>
                    ) : null}
                </div>
            </ConfirmActionModal>

            <Head title={`Expediente de identidad · ${user.name}`} />

            <div className="mx-auto flex w-full max-w-5xl flex-col gap-6">
                <Button asChild className="-ml-2 w-fit" size="sm" variant="ghost">
                    <Link href="/admin/verificacion-kyc" preserveScroll prefetch>
                        <ArrowLeft aria-hidden className="size-4" />
                        Volver al listado de identidad
                    </Link>
                </Button>

                <div className="space-y-1">
                    <h1 className="text-3xl font-bold tracking-tight">Expediente de identidad</h1>
                    <p className="text-muted-foreground text-sm">{user.email}</p>
                </div>

                <Card>
                    <CardHeader>
                        <CardTitle>Datos declarados por el cliente</CardTitle>
                        <CardDescription>
                            Enviado:{' '}
                            {profile.submitted_at
                                ? new Date(profile.submitted_at).toLocaleString('es', {
                                      dateStyle: 'medium',
                                      timeStyle: 'short',
                                  })
                                : '—'}
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="grid gap-4 md:grid-cols-2">
                        <Detail label="Nombre legal">{profile.legal_first_name}</Detail>
                        <Detail label="Apellidos">{profile.legal_last_name}</Detail>
                        <Detail label="Fecha de nacimiento">{profile.date_of_birth}</Detail>
                        <Detail label="Documento">{docLabel}</Detail>
                        <Detail label="Número de documento">{profile.document_number}</Detail>
                        <Detail label="País emisor">{profile.document_issuing_country}</Detail>
                        <Detail label="Residencia habitual">{profile.country_of_residence}</Detail>
                        <Detail label="Dirección 1">{profile.address_line1}</Detail>
                        <Detail label="Dirección 2">{profile.address_line2 ?? '—'}</Detail>
                        <Detail label="Ciudad">{profile.city}</Detail>
                        <Detail label="Provincia / estado">{profile.region_state}</Detail>
                        <Detail label="Código postal">{profile.postal_code}</Detail>
                        <Detail label="Ocupación">{profile.occupation ?? '—'}</Detail>

                        <div className="md:col-span-2 space-y-3 border-t pt-4">
                            <p className="text-muted-foreground text-xs font-semibold uppercase tracking-wide">
                                Documentación adjunta
                            </p>
                            <div className="flex flex-wrap gap-x-6 gap-y-2">
                                <KycDownloadLink
                                    label="Frontal del documento"
                                    href={
                                        documentDownload.url({
                                            user: user.id,
                                            document: 'front',
                                        })
                                    }
                                />
                                {profile.document_back_path ? (
                                    <KycDownloadLink
                                        label="Reverso"
                                        href={
                                            documentDownload.url({
                                                user: user.id,
                                                document: 'back',
                                            })
                                        }
                                    />
                                ) : (
                                    <p className="text-muted-foreground text-sm italic">Sin reverso</p>
                                )}
                                {profile.selfie_document_path ? (
                                    <KycDownloadLink
                                        label="Selfie con ID"
                                        href={
                                            documentDownload.url({
                                                user: user.id,
                                                document: 'selfie',
                                            })
                                        }
                                    />
                                ) : (
                                    <p className="text-muted-foreground text-sm italic">
                                        Sin selfie con documento
                                    </p>
                                )}
                            </div>
                        </div>
                    </CardContent>
                    <CardFooter className="flex flex-col gap-6 border-t bg-muted/20 py-8">
                        <form className="w-full space-y-3 max-w-xl" onSubmit={reject}>
                            <Label htmlFor="reason">Motivo de rechazo (obligatorio para devolver)</Label>
                            <Textarea
                                id="reason"
                                name="reason"
                                placeholder="Describe qué inconsistencia encuentras o qué documentos faltan…"
                                value={rejectReason}
                                rows={5}
                                onChange={(event) => setRejectReason(event.target.value)}
                                required
                            />
                            <div className="flex flex-wrap gap-2 pt-2">
                                <Button
                                    disabled={approving || rejecting}
                                    size="lg"
                                    type="button"
                                    variant="secondary"
                                    onClick={() => setApproveConfirmOpen(true)}
                                >
                                    {approving ? 'Aprobando…' : 'Aprobar cuenta'}
                                </Button>
                                <Button
                                    disabled={rejecting || approving || rejectReason.trim() === ''}
                                    size="lg"
                                    type="submit"
                                    variant="destructive"
                                >
                                    {rejecting ? 'Reenviando…' : 'Rechazar solicitud'}
                                </Button>
                            </div>
                        </form>
                    </CardFooter>
                </Card>
            </div>
        </>
    );
}

function Detail({ label, children }: { label: string; children: ReactNode }) {
    return (
        <div>
            <p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">{label}</p>
            <p className="mt-0.5 whitespace-pre-wrap text-sm leading-snug">{children}</p>
        </div>
    );
}

function KycDownloadLink({ label, href }: { label: string; href: string }) {
    return (
        <a
            download
            className="hover:text-primary inline-flex items-center gap-1.5 text-sm font-medium underline-offset-4 transition-colors hover:underline"
            href={href}
            rel="noopener noreferrer"
        >
            <ArrowDownToLine aria-hidden className="size-4 shrink-0" />
            Descargar {label}
        </a>
    );
}

AdminKycDetail.layout = {
    breadcrumbs: [
        { title: 'Administración', href: '/admin' },
        { title: 'Verificación de identidad', href: '/admin/verificacion-kyc' },
        { title: 'Expediente', href: '#' },
    ],
};
