import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectLabel,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import AppLayout from '@/layouts/app-layout';
import { formatIDR } from '@/lib/formatters';
import savingsRoutes from '@/routes/savings';
import type { BreadcrumbItem, Member } from '@/types';
import type { SavingsProduct } from '@/types/savings';
import { Head, Link, router, useForm } from '@inertiajs/react';
import { AlertCircle, ArrowLeft, User, Wallet } from 'lucide-react';
import type { FormEvent } from 'react';

interface PageProps {
    member: Member;
    products: SavingsProduct[];
}

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Simpanan', href: '/savings' },
    { title: 'Buka Rekening', href: '#' },
];

export default function OpenAccount({ member, products }: PageProps) {
    const form = useForm({
        member_id: member.id,
        savings_product_id: '',
        account_name: member.name || '',
    });

    const handleSubmit = (e: FormEvent) => {
        e.preventDefault();
        form.post(savingsRoutes.open().url);
    };

    const selectedProduct = products.find(
        (p) => p.id === Number(form.data.savings_product_id),
    );

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Buka Rekening Simpanan" />

            <div className="flex h-full flex-1 items-center justify-center overflow-x-auto rounded-xl p-4">
                <Card className="w-full max-w-2xl">
                    <CardHeader>
                        <div className="flex items-center gap-2">
                            <Button
                                variant="ghost"
                                size="icon"
                                asChild
                                className="mr-2"
                            >
                                <Link href={savingsRoutes.index().url}>
                                    <ArrowLeft className="h-4 w-4" />
                                </Link>
                            </Button>
                            <Wallet className="h-6 w-6" />
                            <div>
                                <CardTitle>Buka Rekening Simpanan</CardTitle>
                                <CardDescription>
                                    Buka rekening simpanan baru untuk anggota
                                </CardDescription>
                            </div>
                        </div>
                    </CardHeader>
                    <CardContent>
                        {/* Member Info */}
                        <div className="mb-6 rounded-lg bg-muted p-4">
                            <div className="mb-2 flex items-center gap-2">
                                <User className="h-4 w-4 text-muted-foreground" />
                                <h3 className="font-semibold">
                                    Informasi Anggota
                                </h3>
                            </div>
                            <div className="grid gap-2 text-sm">
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">
                                        Nomor Identitas:
                                    </span>
                                    <span className="font-medium">
                                        {member.id_number || '-'}
                                    </span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">
                                        Nama Lengkap:
                                    </span>
                                    <span className="font-medium">
                                        {member.name}
                                    </span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">
                                        Cabang:
                                    </span>
                                    <span className="font-medium">
                                        {member.branch?.name || '-'}
                                    </span>
                                </div>
                            </div>
                        </div>

                        <form onSubmit={handleSubmit} className="space-y-6">
                            {/* Product Selection */}
                            <div className="space-y-2">
                                <Label htmlFor="savings_product_id">
                                    Produk Simpanan{' '}
                                    <span className="text-destructive">*</span>
                                </Label>
                                <Select
                                    value={form.data.savings_product_id}
                                    onValueChange={(value) =>
                                        form.setData(
                                            'savings_product_id',
                                            value,
                                        )
                                    }
                                    required
                                >
                                    <SelectTrigger id="savings_product_id">
                                        <SelectValue placeholder="Pilih produk simpanan" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectGroup>
                                            <SelectLabel>
                                                Produk Simpanan
                                            </SelectLabel>
                                            {products.map((product) => (
                                                <SelectItem
                                                    key={product.id}
                                                    value={product.id.toString()}
                                                >
                                                    {product.name} (
                                                    {product.code})
                                                </SelectItem>
                                            ))}
                                        </SelectGroup>
                                    </SelectContent>
                                </Select>
                                {form.errors.savings_product_id && (
                                    <InputError
                                        message={form.errors.savings_product_id}
                                    />
                                )}
                            </div>

                            {/* Product Info */}
                            {selectedProduct && (
                                <div className="space-y-2 rounded-lg border bg-muted p-4">
                                    <h4 className="font-semibold">
                                        {selectedProduct.name}
                                    </h4>
                                    <div className="grid gap-2 text-sm">
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">
                                                Kode:
                                            </span>
                                            <span>{selectedProduct.code}</span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">
                                                Jenis:
                                            </span>
                                            <span className="capitalize">
                                                {selectedProduct.type}
                                            </span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">
                                                Saldo Minimum:
                                            </span>
                                            <span className="font-medium">
                                                {formatIDR(
                                                    selectedProduct.minimum_balance,
                                                )}
                                            </span>
                                        </div>
                                        {selectedProduct.has_administrative_fee && (
                                            <div className="flex justify-between">
                                                <span className="text-muted-foreground">
                                                    Biaya Admin:
                                                </span>
                                                <span className="font-medium">
                                                    {formatIDR(
                                                        selectedProduct.administrative_fee ??
                                                            0,
                                                    )}
                                                </span>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            )}

                            {/* Account Name */}
                            <div className="space-y-2">
                                <Label htmlFor="account_name">
                                    Nama Rekening{' '}
                                    <span className="text-destructive">*</span>
                                </Label>
                                <Input
                                    id="account_name"
                                    value={form.data.account_name}
                                    onChange={(e) =>
                                        form.setData(
                                            'account_name',
                                            e.target.value,
                                        )
                                    }
                                    placeholder="Masukkan nama rekening"
                                    required
                                />
                                <p className="text-xs text-muted-foreground">
                                    Nama rekening biasanya menggunakan nama
                                    lengkap anggota
                                </p>
                                {form.errors.account_name && (
                                    <InputError
                                        message={form.errors.account_name}
                                    />
                                )}
                            </div>

                            {/* Important Notice */}
                            {selectedProduct &&
                                selectedProduct.minimum_balance > 0 && (
                                    <div className="flex gap-3 rounded-lg bg-yellow-50 p-4 dark:bg-yellow-900/20">
                                        <AlertCircle className="mt-0.5 h-5 w-5 shrink-0 text-yellow-600 dark:text-yellow-500" />
                                        <div className="text-sm">
                                            <p className="font-medium text-yellow-800 dark:text-yellow-200">
                                                Saldo Minimum Awal
                                            </p>
                                            <p className="mt-1 text-yellow-700 dark:text-yellow-300">
                                                Setoran awal minimum sebesar{' '}
                                                <strong>
                                                    {formatIDR(
                                                        selectedProduct.minimum_balance,
                                                    )}
                                                </strong>{' '}
                                                diperlukan untuk membuka
                                                rekening ini.
                                            </p>
                                        </div>
                                    </div>
                                )}

                            {/* Actions */}
                            <div className="flex gap-3">
                                <Button
                                    type="button"
                                    variant="outline"
                                    className="flex-1"
                                    onClick={() =>
                                        router.visit(savingsRoutes.index().url)
                                    }
                                >
                                    Batal
                                </Button>
                                <Button
                                    type="submit"
                                    className="flex-1"
                                    disabled={
                                        form.processing ||
                                        !form.data.savings_product_id
                                    }
                                >
                                    {form.processing
                                        ? 'Memproses...'
                                        : 'Buka Rekening'}
                                </Button>
                            </div>
                        </form>
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}
