import { Form, Head, router } from '@inertiajs/react';
import { Tags } from 'lucide-react';
import { useState } from 'react';
import LoanCategoryController from '@/actions/App/Http/Controllers/Admin/LoanCategoryController';
import {
    CatalogActions,
    CatalogNameCell,
    CatalogNewButton,
} from '@/components/catalog-table';
import DataTable from '@/components/data-table';
import type { DataTableColumn } from '@/components/data-table';
import InputError from '@/components/input-error';
import MemberPage from '@/components/member/member-page';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { index } from '@/routes/admin/loan-categories';

type LoanCategoryRow = {
    id: number;
    name: string;
    description: string | null;
    isActive: boolean;
    products: number;
};

function TypeDialog({
    type,
    open,
    onOpenChange,
}: {
    type: LoanCategoryRow | null;
    open: boolean;
    onOpenChange: (open: boolean) => void;
}) {
    const editing = type !== null;
    const action = editing
        ? LoanCategoryController.update.form(type.id)
        : LoanCategoryController.store.form();

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-lg">
                <DialogHeader>
                    <DialogTitle>
                        {editing ? `Edit ${type.name}` : 'New loan category'}
                    </DialogTitle>
                    <DialogDescription>
                        Categories group your loan products for members and
                        staff.
                    </DialogDescription>
                </DialogHeader>

                <Form
                    {...action}
                    key={type?.id ?? 'new'}
                    onSuccess={() => onOpenChange(false)}
                    className="grid gap-4"
                >
                    {({ processing, errors }) => (
                        <>
                            <div className="grid gap-1.5">
                                <Label htmlFor="name" required>
                                    Name
                                </Label>
                                <Input
                                    id="name"
                                    name="name"
                                    defaultValue={type?.name}
                                    maxLength={80}
                                    placeholder="e.g. Business loan"
                                    required
                                    autoFocus
                                />
                                <InputError message={errors.name} />
                            </div>

                            <div className="grid gap-1.5">
                                <Label htmlFor="description">Description</Label>
                                <textarea
                                    id="description"
                                    name="description"
                                    defaultValue={type?.description ?? ''}
                                    maxLength={500}
                                    rows={3}
                                    placeholder="e.g. For traders and small businesses that need stock or equipment."
                                    className="rounded-md border border-input bg-white px-3 py-2 text-sm shadow-xs outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15"
                                />
                                <InputError message={errors.description} />
                            </div>

                            <label className="flex items-start gap-2.5 text-sm">
                                <input
                                    type="checkbox"
                                    name="is_active"
                                    value="1"
                                    defaultChecked={type?.isActive ?? true}
                                    className="mt-0.5 size-4 accent-brand"
                                />
                                <span>
                                    <span className="font-semibold text-ink">
                                        Offer to members
                                    </span>
                                    <span className="block text-xs text-ink-400">
                                        Untick to stop using it for new or
                                        edited products.
                                    </span>
                                </span>
                            </label>

                            <div className="flex justify-end gap-2">
                                <Button
                                    type="button"
                                    variant="ghost"
                                    onClick={() => onOpenChange(false)}
                                >
                                    Cancel
                                </Button>
                                <Button disabled={processing}>
                                    {editing ? 'Save' : 'Add category'}
                                </Button>
                            </div>
                        </>
                    )}
                </Form>
            </DialogContent>
        </Dialog>
    );
}

export default function LoanCategoriesIndex({
    categories,
}: {
    categories: LoanCategoryRow[];
}) {
    const [open, setOpen] = useState(false);
    const [editing, setEditing] = useState<LoanCategoryRow | null>(null);

    const openDialog = (type: LoanCategoryRow | null) => {
        setEditing(type);
        setOpen(true);
    };

    const remove = (type: LoanCategoryRow) => {
        if (window.confirm(`Delete ${type.name}?`)) {
            router.delete(LoanCategoryController.destroy.url(type.id), {
                preserveScroll: true,
            });
        }
    };

    const columns: DataTableColumn<LoanCategoryRow>[] = [
        {
            key: 'name',
            header: 'Category',
            sortable: true,
            cell: (type) => (
                <CatalogNameCell
                    name={type.name}
                    description={type.description}
                    isActive={type.isActive}
                />
            ),
        },
        {
            key: 'products',
            header: 'Products',
            sortable: true,
            align: 'right',
            className: 'tabular-nums',
        },
        {
            key: 'actions',
            header: <span className="sr-only">Actions</span>,
            align: 'right',
            className: 'w-px whitespace-nowrap',
            cell: (type) => (
                <CatalogActions
                    name={type.name}
                    onEdit={() => openDialog(type)}
                    onDelete={
                        type.products === 0 ? () => remove(type) : undefined
                    }
                />
            ),
        },
    ];

    return (
        <>
            <Head title="Loan categories" />

            <MemberPage
                title="Loan categories"
                description="The groups your loan products are sorted into. Each business keeps its own list."
                actions={
                    <CatalogNewButton
                        label="New category"
                        onClick={() => openDialog(null)}
                    />
                }
            >
                <DataTable
                    title="All categories"
                    description="Hidden categories stay on their products but cannot be picked for others."
                    columns={columns}
                    data={categories}
                    getRowId={(type) => type.id}
                    searchable
                    searchPlaceholder="Search categories"
                    searchText={(type) =>
                        `${type.name} ${type.description ?? ''}`
                    }
                    empty={{
                        icon: Tags,
                        title: 'No loan categories yet',
                        description:
                            'Add categories such as Emergency, Business, Salary or School fees loans.',
                    }}
                />
            </MemberPage>

            <TypeDialog type={editing} open={open} onOpenChange={setOpen} />
        </>
    );
}

LoanCategoriesIndex.layout = {
    breadcrumbs: [{ title: 'Loan categories', href: index() }],
};
