import { Head, Link, useForm } from '@inertiajs/react';
import { AlertCircle, ArrowLeft, Calculator, User } from 'lucide-react';
import { useMemo, useState } from 'react';

import InputError from '@/components/input-error';
import {
    MemberSelector,
    type MemberSearchResult,
} from '@/components/members/MemberSelector';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { CurrencyInput } from '@/components/ui/currency-input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectLabel,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { StatusBadge } from '@/components/ui/status-badge';
import { Textarea } from '@/components/ui/textarea';
import { usePermissions } from '@/hooks/use-permissions';
import AppLayout from '@/layouts/app-layout';
import { formatIDR } from '@/lib/formatters';
import { calculateFinancing } from '@/lib/helpers/financing';
import { toastError, toastLoading, toastSuccess } from '@/lib/toast';
import financingsRoutes from '@/routes/financing';
import membersRoutes from '@/routes/members';
import type { BreadcrumbItem } from '@/types';
import type { FinancingProduct } from '@/types/financing';

interface PageProps {
    products: FinancingProduct[];
    collectors?: { id: number; name: string }[];
    auth: {
        user: {
            role: string;
        };
    };
}

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Pembiayaan',
        href: financingsRoutes.index().url,
    },
    {
        title: 'Ajukan Pembiayaan',
        href: '',
    },
];

export default function Create({ products, collectors = [] }: PageProps) {
    const { can, isAdmin: checkIsAdmin } = usePermissions();

    const isAdmin = checkIsAdmin();
    const isTeller = can('financing.propose') || isAdmin;

    const [selectedMember, setSelectedMember] =
        useState<MemberSearchResult | null>(null);
    const form = useForm({
        member_id: '',
        branch_id: '',
        financing_product_id: '',
        requested_amount: '',
        purpose: '',
        collector_id: '',
        notes: '',
    });

    // Real-time calculation
    const calculation = useMemo(() => {
        return calculateFinancing(
            form.data.financing_product_id,
            form.data.requested_amount,
            products,
        );
    }, [form.data.financing_product_id, form.data.requested_amount, products]);

    if (!isTeller) {
        return (
            <AppLayout breadcrumbs={breadcrumbs}>
                <Head title="Akses Ditolak" />
                <div className="flex h-full items-center justify-center">
                    <Card className="max-w-md">
                        <CardHeader>
                            <CardTitle className="text-destructive">
                                Akses Ditolak
                            </CardTitle>
                        </CardHeader>
                        <CardContent>
                            <p>
                                Anda tidak memiliki izin untuk mengajukan
                                pembiayaan.
                            </p>
                        </CardContent>
                    </Card>
                </div>
            </AppLayout>
        );
    }

    const handleMemberChange = (
        memberId: number | null,
        memberData?: MemberSearchResult,
    ) => {
        if (memberId && memberData) {
            setSelectedMember(memberData);
            form.setData('member_id', memberId.toString());
            form.setData('branch_id', memberData.branch_id.toString());
        } else {
            setSelectedMember(null);
            form.setData('member_id', '');
            form.setData('branch_id', '');
        }
    };

    const handleSubmit = (e: { preventDefault: () => void }) => {
        e.preventDefault();

        // Check if member is selected
        if (!selectedMember) {
            toastError('Silakan pilih anggota terlebih dahulu.');
            return;
        }

        // Check if member has a branch assigned
        if (!selectedMember.branch_id) {
            toastError(
                'Anggota ini belum memiliki cabang. Silakan hubungi administrator untuk menetapkan cabang anggota.',
            );
            return;
        }

        // Check if member already has active/pending financing
        if (selectedMember.active_financings_count > 0) {
            toastError(
                'Anggota ini sudah memiliki pembiayaan aktif. Harap selesaikan pembiayaan yang ada terlebih dahulu.',
            );
            return;
        }

        // Validate calculation
        if (calculation && !calculation.valid) {
            toastError(calculation.error || 'Perhitungan tidak valid');
            return;
        }

        const submitUrl = financingsRoutes.store().url;

        form.post(submitUrl, {
            onStart: () => {
                toastLoading('Mengajukan pembiayaan...');
            },
            onSuccess: () => {
                toastSuccess('Pembiayaan berhasil diajukan');
            },
            onError: () => {
                toastError('Gagal mengajukan pembiayaan');
            },
        });
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Ajukan Pembiayaan" />

            <div className="flex h-full flex-1 flex-col gap-4 rounded-xl p-4">
                {/* Header */}
                <div className="flex items-center gap-4">
                    <Button variant="outline" size="icon" asChild>
                        <Link href={financingsRoutes.index().url}>
                            <ArrowLeft className="h-4 w-4" />
                        </Link>
                    </Button>
                    <div className="flex flex-col gap-1">
                        <h1 className="text-2xl font-black">
                            Ajukan Pembiayaan Baru
                        </h1>
                        <span className="text-sm text-muted-foreground">
                            Isi formulir di bawah untuk mengajukan pembiayaan
                            baru.
                        </span>
                    </div>
                </div>

                <div className="grid gap-6 lg:grid-cols-3">
                    {/* Form Column */}
                    <div className="lg:col-span-2">
                        <form onSubmit={handleSubmit} className="space-y-6">
                            {/* Member Selection Card (when no member selected) */}
                            {!selectedMember && (
                                <Card>
                                    <CardHeader>
                                        <CardTitle className="flex items-center gap-2">
                                            <User className="h-5 w-5" />
                                            Pilih Anggota
                                        </CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <p className="mb-4 text-sm text-muted-foreground">
                                            Cari anggota untuk mengajukan
                                            pembiayaan
                                        </p>
                                        <MemberSelector
                                            value={null}
                                            onChange={handleMemberChange}
                                            error={form.errors.member_id}
                                        />
                                    </CardContent>
                                </Card>
                            )}

                            {/* Member Info Card (when member selected) */}
                            {selectedMember && (
                                <Card>
                                    <CardHeader>
                                        <CardTitle>Informasi Anggota</CardTitle>
                                    </CardHeader>
                                    <CardContent className="space-y-3">
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">
                                                Nama
                                            </span>
                                            <Link
                                                href={
                                                    membersRoutes.show({
                                                        member: selectedMember.id,
                                                    }).url
                                                }
                                                className="font-medium text-primary hover:underline"
                                            >
                                                {selectedMember.name}
                                            </Link>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">
                                                NIK
                                            </span>
                                            <span className="font-medium">
                                                {selectedMember.id_number ||
                                                    '-'}
                                            </span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">
                                                Telepon
                                            </span>
                                            <span>
                                                {selectedMember.phone || '-'}
                                            </span>
                                        </div>
                                        {selectedMember.branch && (
                                            <div className="flex justify-between">
                                                <span className="text-muted-foreground">
                                                    Cabang
                                                </span>
                                                <span className="font-medium">
                                                    {selectedMember.branch}
                                                </span>
                                            </div>
                                        )}
                                        {selectedMember.collectibility_score !=
                                            null && (
                                            <div className="flex justify-between">
                                                <span className="text-muted-foreground">
                                                    Kolektibilitas
                                                </span>
                                                <StatusBadge
                                                    type="collectibility"
                                                    status={selectedMember.collectibility_score.toString()}
                                                />
                                            </div>
                                        )}
                                        {selectedMember.active_financings_count >
                                            0 && (
                                            <div className="flex gap-3 rounded-lg bg-destructive/10 p-3">
                                                <AlertCircle className="h-5 w-5 shrink-0 text-destructive" />
                                                <div>
                                                    <div className="font-medium text-destructive">
                                                        Pembiayaan Aktif Ada
                                                    </div>
                                                    <div className="text-sm text-muted-foreground">
                                                        Anggota ini memiliki{' '}
                                                        {
                                                            selectedMember.active_financings_count
                                                        }{' '}
                                                        pembiayaan aktif. Tidak
                                                        dapat mengajukan
                                                        pembiayaan baru.
                                                    </div>
                                                </div>
                                            </div>
                                        )}
                                        <div className="pt-2">
                                            <Button
                                                type="button"
                                                variant="outline"
                                                size="sm"
                                                onClick={() => {
                                                    setSelectedMember(null);
                                                    form.setData(
                                                        'member_id',
                                                        '',
                                                    );
                                                    // form.setData('branch_id', '');
                                                }}
                                            >
                                                Ganti Anggota
                                            </Button>
                                        </div>
                                    </CardContent>
                                </Card>
                            )}

                            {/* Financing Details Form */}
                            <Card>
                                <CardHeader>
                                    <CardTitle>Detail Pembiayaan</CardTitle>
                                </CardHeader>
                                <CardContent className="space-y-4">
                                    {!selectedMember && (
                                        <div className="rounded-lg bg-muted p-8 text-center text-muted-foreground">
                                            <User className="mx-auto mb-2 h-12 w-12 opacity-50" />
                                            <p>
                                                Silakan pilih anggota terlebih
                                                dahulu
                                            </p>
                                        </div>
                                    )}
                                    {selectedMember && (
                                        <>
                                            {/* Financing Product */}
                                            <div className="space-y-2">
                                                <Label htmlFor="financing_product_id">
                                                    Produk Pembiayaan{' '}
                                                    <span className="text-destructive">
                                                        *
                                                    </span>
                                                </Label>
                                                <Select
                                                    value={
                                                        form.data
                                                            .financing_product_id
                                                    }
                                                    onValueChange={(value) =>
                                                        form.setData(
                                                            'financing_product_id',
                                                            value,
                                                        )
                                                    }
                                                    required
                                                >
                                                    <SelectTrigger>
                                                        <SelectValue placeholder="Pilih produk pembiayaan" />
                                                    </SelectTrigger>
                                                    <SelectContent>
                                                        <SelectGroup>
                                                            <SelectLabel>
                                                                Produk Tersedia
                                                            </SelectLabel>
                                                            {products
                                                                .filter(
                                                                    (p) =>
                                                                        p.is_active,
                                                                )
                                                                .map(
                                                                    (
                                                                        product,
                                                                    ) => (
                                                                        <SelectItem
                                                                            key={
                                                                                product.id
                                                                            }
                                                                            value={product.id.toString()}
                                                                        >
                                                                            {
                                                                                product.code
                                                                            }{' '}
                                                                            -{' '}
                                                                            {
                                                                                product.name
                                                                            }{' '}
                                                                            (
                                                                            {
                                                                                product.margin_rate
                                                                            }
                                                                            %)
                                                                        </SelectItem>
                                                                    ),
                                                                )}
                                                        </SelectGroup>
                                                    </SelectContent>
                                                </Select>
                                                {form.errors
                                                    .financing_product_id && (
                                                    <InputError
                                                        message={
                                                            form.errors
                                                                .financing_product_id
                                                        }
                                                    />
                                                )}
                                            </div>

                                            {/* Requested Amount */}
                                            <div className="space-y-2">
                                                <Label htmlFor="requested_amount">
                                                    Jumlah Pengajuan{' '}
                                                    <span className="text-destructive">
                                                        *
                                                    </span>
                                                </Label>

                                                <CurrencyInput
                                                    id="requested_amount"
                                                    prefix="Rp "
                                                    thousandSeparator="."
                                                    placeholder="Rp 0"
                                                    value={
                                                        form.data
                                                            .requested_amount
                                                    }
                                                    onValueChange={(values) => {
                                                        form.setData(
                                                            'requested_amount',
                                                            values.floatValue
                                                                ? values.floatValue.toString()
                                                                : '',
                                                        );
                                                    }}
                                                    required
                                                />

                                                {/* Quick Amount Selection */}
                                                <div className="flex flex-wrap gap-2 pt-1">
                                                    {[
                                                        1000000, 2000000,
                                                        3000000, 5000000,
                                                        10000000,
                                                    ].map((amount) => (
                                                        <Button
                                                            key={amount}
                                                            type="button"
                                                            variant="outline"
                                                            size="xs"
                                                            className={`h-7 px-2 text-xs font-semibold ${
                                                                form.data
                                                                    .requested_amount ===
                                                                amount.toString()
                                                                    ? 'border-primary bg-primary/10 text-primary hover:bg-primary/20 hover:text-primary'
                                                                    : 'text-muted-foreground'
                                                            }`}
                                                            onClick={() =>
                                                                form.setData(
                                                                    'requested_amount',
                                                                    amount.toString(),
                                                                )
                                                            }
                                                        >
                                                            {formatIDR(amount)}
                                                        </Button>
                                                    ))}
                                                </div>

                                                {form.errors
                                                    .requested_amount && (
                                                    <InputError
                                                        message={
                                                            form.errors
                                                                .requested_amount
                                                        }
                                                    />
                                                )}
                                                {calculation &&
                                                    !calculation.valid && (
                                                        <InputError
                                                            message={
                                                                calculation.error
                                                            }
                                                        />
                                                    )}
                                            </div>

                                            {/* Purpose */}
                                            <div className="space-y-2">
                                                <Label htmlFor="purpose">
                                                    Tujuan Pembiayaan{' '}
                                                    <span className="text-destructive">
                                                        *
                                                    </span>
                                                </Label>
                                                <Textarea
                                                    id="purpose"
                                                    value={form.data.purpose}
                                                    onChange={(e) =>
                                                        form.setData(
                                                            'purpose',
                                                            e.target.value,
                                                        )
                                                    }
                                                    placeholder="Jelaskan tujuan pengajuan pembiayaan..."
                                                    rows={3}
                                                    required
                                                />
                                                {form.errors.purpose && (
                                                    <InputError
                                                        message={
                                                            form.errors.purpose
                                                        }
                                                    />
                                                )}
                                            </div>

                                            {/* Collector (Optional) */}
                                            <div className="space-y-2">
                                                <Label htmlFor="collector_id">
                                                    Staf Lapangan (Opsional)
                                                </Label>
                                                <Select
                                                    value={
                                                        form.data.collector_id
                                                    }
                                                    onValueChange={(value) =>
                                                        form.setData(
                                                            'collector_id',
                                                            value,
                                                        )
                                                    }
                                                >
                                                    <SelectTrigger>
                                                        <SelectValue placeholder="Pilih Staf Lapangan (opsional)" />
                                                    </SelectTrigger>
                                                    <SelectContent>
                                                        <SelectGroup>
                                                            <SelectLabel>
                                                                Daftar Staf Lapangan
                                                            </SelectLabel>
                                                            {collectors.map(
                                                                (collector) => (
                                                                    <SelectItem
                                                                        key={
                                                                            collector.id
                                                                        }
                                                                        value={collector.id.toString()}
                                                                    >
                                                                        {
                                                                            collector.name
                                                                        }
                                                                    </SelectItem>
                                                                ),
                                                            )}
                                                        </SelectGroup>
                                                    </SelectContent>
                                                </Select>
                                                {form.errors.collector_id && (
                                                    <InputError
                                                        message={
                                                            form.errors
                                                                .collector_id
                                                        }
                                                    />
                                                )}
                                            </div>

                                            {/* Notes (Optional) */}
                                            <div className="space-y-2">
                                                <Label htmlFor="notes">
                                                    Catatan (Opsional)
                                                </Label>
                                                <Textarea
                                                    id="notes"
                                                    value={form.data.notes}
                                                    onChange={(e) =>
                                                        form.setData(
                                                            'notes',
                                                            e.target.value,
                                                        )
                                                    }
                                                    placeholder="Catatan tambahan..."
                                                    rows={2}
                                                />
                                                {form.errors.notes && (
                                                    <InputError
                                                        message={
                                                            form.errors.notes
                                                        }
                                                    />
                                                )}
                                            </div>
                                        </>
                                    )}
                                </CardContent>
                            </Card>

                            {/* Submit Button */}
                            <div className="flex gap-3">
                                <Button
                                    type="button"
                                    variant="outline"
                                    asChild
                                    disabled={form.processing}
                                >
                                    <Link href={financingsRoutes.index().url}>
                                        Batal
                                    </Link>
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={
                                        form.processing ||
                                        !selectedMember ||
                                        (selectedMember?.active_financings_count ??
                                            0) > 0
                                    }
                                >
                                    {form.processing
                                        ? 'Memproses...'
                                        : 'Ajukan Pembiayaan'}
                                </Button>
                            </div>
                        </form>
                    </div>

                    {/* Calculation Preview Column */}
                    <div className="lg:col-span-1">
                        <Card className="sticky top-4">
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Calculator className="h-5 w-5" />
                                    Perhitungan
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                {!calculation ? (
                                    <div className="py-8 text-center text-muted-foreground">
                                        Pilih produk dan masukkan jumlah untuk
                                        melihat perhitungan.
                                    </div>
                                ) : calculation.valid ? (
                                    <div className="space-y-4">
                                        <div className="space-y-2">
                                            <div className="flex justify-between text-sm">
                                                <span className="text-muted-foreground">
                                                    Jumlah Pokok
                                                </span>
                                                <span className="font-medium">
                                                    {formatIDR(
                                                        calculation.principal,
                                                    )}
                                                </span>
                                            </div>
                                            <div className="flex justify-between text-sm">
                                                <span className="text-muted-foreground">
                                                    Margin (
                                                    {calculation.marginRate}%)
                                                </span>
                                                <span className="font-medium">
                                                    {formatIDR(
                                                        calculation.margin,
                                                    )}
                                                </span>
                                            </div>
                                            <div className="flex justify-between border-t pt-2 text-lg font-bold">
                                                <span>Total Pengembalian</span>
                                                <span>
                                                    {formatIDR(
                                                        calculation.total,
                                                    )}
                                                </span>
                                            </div>
                                        </div>

                                        <div className="space-y-2 rounded-lg bg-primary/10 p-4">
                                            <div className="flex justify-between text-sm">
                                                <span className="text-muted-foreground">
                                                    Angsuran Harian
                                                </span>
                                                <span className="text-lg font-bold">
                                                    {formatIDR(
                                                        calculation.daily,
                                                    )}
                                                </span>
                                            </div>
                                            <div className="flex justify-between text-sm">
                                                <span className="text-muted-foreground">
                                                    Jangka Waktu
                                                </span>
                                                <span className="font-medium">
                                                    {
                                                        calculation.installmentCount
                                                    }{' '}
                                                    hari
                                                </span>
                                            </div>
                                        </div>

                                        <div className="space-y-2 border-t pt-4">
                                            <div className="mb-2 text-sm font-medium">
                                                Biaya-biaya:
                                            </div>
                                            <div className="flex justify-between text-xs">
                                                <span className="text-muted-foreground">
                                                    Admin
                                                </span>
                                                <span>
                                                    {formatIDR(
                                                        calculation.adminFee,
                                                    )}
                                                </span>
                                            </div>
                                            <div className="flex justify-between text-xs">
                                                <span className="text-muted-foreground">
                                                    Provisi (
                                                    {products.find(
                                                        (p) =>
                                                            p.id.toString() ===
                                                            form.data
                                                                .financing_product_id,
                                                    )?.provision_fee || 0}
                                                    %)
                                                </span>
                                                <span>
                                                    {formatIDR(
                                                        calculation.provisiFee,
                                                    )}
                                                </span>
                                            </div>
                                            <div className="flex justify-between text-xs">
                                                <span className="text-muted-foreground">
                                                    Notaris
                                                </span>
                                                <span>
                                                    {formatIDR(
                                                        calculation.notaryFee,
                                                    )}
                                                </span>
                                            </div>
                                            <div className="flex justify-between text-xs">
                                                <span className="text-muted-foreground">
                                                    Survey
                                                </span>
                                                <span>
                                                    {formatIDR(
                                                        calculation.surveyFee,
                                                    )}
                                                </span>
                                            </div>
                                            <div className="mt-2 flex justify-between border-t pt-2 text-sm font-bold">
                                                <span>Total Biaya</span>
                                                <span>
                                                    {formatIDR(
                                                        calculation.totalFees,
                                                    )}
                                                </span>
                                            </div>
                                        </div>

                                        <div className="space-y-2 rounded-lg bg-green-100 p-4 dark:bg-green-900/20">
                                            <div className="flex justify-between text-sm">
                                                <span className="text-muted-foreground">
                                                    Pencairan Bersih
                                                </span>
                                                <span className="font-bold text-green-700 dark:text-green-400">
                                                    {formatIDR(
                                                        calculation.totalDisbursement,
                                                    )}
                                                </span>
                                            </div>
                                            <div className="text-xs text-green-600 dark:text-green-500">
                                                Jumlah yang akan diterima
                                                anggota setelah biaya
                                            </div>
                                        </div>
                                    </div>
                                ) : (
                                    <div className="rounded-lg bg-destructive/10 p-4 text-destructive">
                                        {calculation.error}
                                    </div>
                                )}
                            </CardContent>
                        </Card>
                    </div>
                </div>
            </div>
        </AppLayout>
    );
}
