import { Head, Link, useForm } from '@inertiajs/react';
import { ArrowLeft, Save } from 'lucide-react';
import type { FormEvent } from 'react';

import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import AppLayout from '@/layouts/app-layout';
import accountingRoutes from '@/routes/accounting';
import type { BreadcrumbItem } from '@/types';
import type {
    Account,
    AccountClassification,
    NormalBalance,
} from '@/types/accounting';

interface PageProps {
    parent_accounts: Account[];
}

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Akuntansi',
        href: accountingRoutes.accounts.index().url,
    },
    {
        title: 'Daftar Akun',
        href: accountingRoutes.accounts.index().url,
    },
    {
        title: 'Tambah Akun',
        href: accountingRoutes.accounts.create().url,
    },
];

export default function CreateAccount({ parent_accounts }: PageProps) {
    const { data, setData, post, processing, errors } = useForm({
        code: '',
        name: '',
        parent_id: '' as string | number,
        classification: 'asset',
        normal_balance: 'debit',
        level: 3,
        is_header: false,
        is_active: true,
        description: '',
        currency: 'IDR',
    });

    const handleSubmit = (e: FormEvent) => {
        e.preventDefault();
        post(accountingRoutes.accounts.store().url);
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Tambah Akun Baru" />

            <div className="mx-auto flex h-full w-full max-w-3xl flex-col gap-4 p-4">
                <div className="flex items-center gap-4">
                    <Button variant="outline" size="icon" asChild>
                        <Link href={accountingRoutes.accounts.index().url}>
                            <ArrowLeft className="h-4 w-4" />
                        </Link>
                    </Button>
                    <div className="flex flex-col gap-1">
                        <h1 className="text-2xl font-black">
                            Tambah Akun Baru
                        </h1>
                        <p className="text-sm text-muted-foreground">
                            Buat akun baru dalam Bagan Akun (COA).
                        </p>
                    </div>
                </div>

                <form onSubmit={handleSubmit}>
                    <Card>
                        <CardHeader>
                            <CardTitle>Informasi Akun</CardTitle>
                            <CardDescription>
                                Masukkan detail akun keuangan di bawah ini.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="grid gap-6">
                            <div className="grid gap-4 md:grid-cols-2">
                                <div className="space-y-2">
                                    <Label htmlFor="code">
                                        Kode Akun{' '}
                                        <span className="text-red-500">*</span>
                                    </Label>
                                    <Input
                                        id="code"
                                        placeholder="Contoh: 110101"
                                        value={data.code}
                                        onChange={(e) =>
                                            setData('code', e.target.value)
                                        }
                                        className={
                                            errors.code ? 'border-red-500' : ''
                                        }
                                    />
                                    {errors.code && (
                                        <p className="text-xs text-red-500">
                                            {errors.code}
                                        </p>
                                    )}
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="level">
                                        Level{' '}
                                        <span className="text-red-500">*</span>
                                    </Label>
                                    <Select
                                        value={data.level.toString()}
                                        onValueChange={(v) =>
                                            setData('level', parseInt(v))
                                        }
                                    >
                                        <SelectTrigger id="level">
                                            <SelectValue placeholder="Pilih Level" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="1">
                                                Level 1 (Tipe)
                                            </SelectItem>
                                            <SelectItem value="2">
                                                Level 2 (Grup)
                                            </SelectItem>
                                            <SelectItem value="3">
                                                Level 3 (Detail)
                                            </SelectItem>
                                        </SelectContent>
                                    </Select>
                                    {errors.level && (
                                        <p className="text-xs text-red-500">
                                            {errors.level}
                                        </p>
                                    )}
                                </div>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="name">
                                    Nama Akun{' '}
                                    <span className="text-red-500">*</span>
                                </Label>
                                <Input
                                    id="name"
                                    placeholder="Contoh: Kas Utama"
                                    value={data.name}
                                    onChange={(e) =>
                                        setData('name', e.target.value)
                                    }
                                    className={
                                        errors.name ? 'border-red-500' : ''
                                    }
                                />
                                {errors.name && (
                                    <p className="text-xs text-red-500">
                                        {errors.name}
                                    </p>
                                )}
                            </div>

                            <div className="grid gap-4 md:grid-cols-2">
                                <div className="space-y-2">
                                    <Label htmlFor="classification">
                                        Klasifikasi{' '}
                                        <span className="text-red-500">*</span>
                                    </Label>
                                    <Select
                                        value={data.classification}
                                        onValueChange={(
                                            v: AccountClassification,
                                        ) => setData('classification', v)}
                                    >
                                        <SelectTrigger id="classification">
                                            <SelectValue placeholder="Pilih Klasifikasi" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="asset">
                                                Aset (Asset)
                                            </SelectItem>
                                            <SelectItem value="liability">
                                                Kewajiban (Liability)
                                            </SelectItem>
                                            <SelectItem value="equity">
                                                Ekuitas (Equity)
                                            </SelectItem>
                                            <SelectItem value="revenue">
                                                Pendapatan (Revenue)
                                            </SelectItem>
                                            <SelectItem value="expense">
                                                Beban (Expense)
                                            </SelectItem>
                                        </SelectContent>
                                    </Select>
                                    {errors.classification && (
                                        <p className="text-xs text-red-500">
                                            {errors.classification}
                                        </p>
                                    )}
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="normal_balance">
                                        Saldo Normal{' '}
                                        <span className="text-red-500">*</span>
                                    </Label>
                                    <Select
                                        value={data.normal_balance}
                                        onValueChange={(v: NormalBalance) =>
                                            setData('normal_balance', v)
                                        }
                                    >
                                        <SelectTrigger id="normal_balance">
                                            <SelectValue placeholder="Pilih Saldo Normal" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="debit">
                                                Debit
                                            </SelectItem>
                                            <SelectItem value="credit">
                                                Kredit
                                            </SelectItem>
                                        </SelectContent>
                                    </Select>
                                    {errors.normal_balance && (
                                        <p className="text-xs text-red-500">
                                            {errors.normal_balance}
                                        </p>
                                    )}
                                </div>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="parent_id">
                                    Akun Induk (Parent)
                                </Label>
                                <Select
                                    value={data.parent_id.toString()}
                                    onValueChange={(v) =>
                                        setData('parent_id', v)
                                    }
                                >
                                    <SelectTrigger id="parent_id">
                                        <SelectValue placeholder="Pilih Akun Induk (Opsional)" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value=" ">
                                            Tidak Ada Induk
                                        </SelectItem>
                                        {parent_accounts.map((acc) => (
                                            <SelectItem
                                                key={acc.id}
                                                value={acc.id.toString()}
                                            >
                                                {acc.code} - {acc.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                {errors.parent_id && (
                                    <p className="text-xs text-red-500">
                                        {errors.parent_id}
                                    </p>
                                )}
                            </div>

                            <div className="flex items-center space-x-2">
                                <Checkbox
                                    id="is_header"
                                    checked={data.is_header}
                                    onCheckedChange={(checked) =>
                                        setData('is_header', checked as boolean)
                                    }
                                />
                                <div className="grid gap-1.5 leading-none">
                                    <Label
                                        htmlFor="is_header"
                                        className="font-bold"
                                    >
                                        Akun Header
                                    </Label>
                                    <p className="text-xs text-muted-foreground">
                                        Akun header tidak dapat menerima
                                        transaksi langsung.
                                    </p>
                                </div>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="description">Deskripsi</Label>
                                <Textarea
                                    id="description"
                                    placeholder="Penjelasan singkat mengenai kegunaan akun ini..."
                                    value={data.description}
                                    onChange={(e) =>
                                        setData('description', e.target.value)
                                    }
                                />
                                {errors.description && (
                                    <p className="text-xs text-red-500">
                                        {errors.description}
                                    </p>
                                )}
                            </div>

                            <div className="flex justify-end gap-2 pt-4">
                                <Button
                                    type="button"
                                    variant="outline"
                                    asChild
                                    disabled={processing}
                                >
                                    <Link
                                        href={
                                            accountingRoutes.accounts.index()
                                                .url
                                        }
                                    >
                                        Batal
                                    </Link>
                                </Button>
                                <Button type="submit" disabled={processing}>
                                    <Save className="mr-2 h-4 w-4" />
                                    Simpan Akun
                                </Button>
                            </div>
                        </CardContent>
                    </Card>
                </form>
            </div>
        </AppLayout>
    );
}
