import { Form, Head, router } from '@inertiajs/react';
import { Shapes } from 'lucide-react';
import { useState } from 'react';
import FinancingTypeController from '@/actions/App/Http/Controllers/Admin/FinancingTypeController';
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/financing-types';

type FinancingTypeRow = {
    id: number;
    name: string;
    description: string | null;
    allowsMarkup: boolean;
    isActive: boolean;
    applications: number;
};

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

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-lg">
                <DialogHeader>
                    <DialogTitle>
                        {editing ? `Edit ${type.name}` : 'New financing type'}
                    </DialogTitle>
                    <DialogDescription>
                        Members choose from the types shown here when they
                        apply. Applications keep the name and terms they were
                        made with.
                    </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. Asset financing"
                                    required
                                    autoFocus
                                />
                                <InputError message={errors.name} />
                            </div>

                            <div className="grid gap-1.5">
                                <Label htmlFor="description">
                                    What it means for members
                                </Label>
                                <textarea
                                    id="description"
                                    name="description"
                                    defaultValue={type?.description ?? ''}
                                    maxLength={500}
                                    rows={3}
                                    placeholder="e.g. We buy the item you need and sell it to you at an agreed price, paid in instalments."
                                    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="allows_markup"
                                    value="1"
                                    defaultChecked={type?.allowsMarkup ?? true}
                                    className="mt-0.5 size-4 accent-brand"
                                />
                                <span>
                                    <span className="font-semibold text-ink">
                                        Agreed profit, price or rent
                                    </span>
                                    <span className="block text-xs text-ink-400">
                                        Untick for types repaid at exactly the
                                        amount paid out, like a Qard Hasan loan.
                                    </span>
                                </span>
                            </label>

                            <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 hide it from new applications.
                                    </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 type'}
                                </Button>
                            </div>
                        </>
                    )}
                </Form>
            </DialogContent>
        </Dialog>
    );
}

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

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

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

    const columns: DataTableColumn<FinancingTypeRow>[] = [
        {
            key: 'name',
            header: 'Type',
            sortable: true,
            cell: (type) => (
                <CatalogNameCell
                    name={type.name}
                    description={type.description}
                    isActive={type.isActive}
                />
            ),
        },
        {
            key: 'allowsMarkup',
            header: 'Repayment',
            hideOnMobile: true,
            className: 'text-xs text-ink-500',
            cell: (type) =>
                type.allowsMarkup
                    ? 'Agreed profit, price or rent'
                    : 'Exactly the amount paid out',
        },
        {
            key: 'applications',
            header: 'Applications',
            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.applications === 0 ? () => remove(type) : undefined
                    }
                />
            ),
        },
    ];

    return (
        <>
            <Head title="Financing types" />

            <MemberPage
                title="Financing types"
                description="The kinds of financing members can apply for. Each business keeps its own list."
                actions={
                    <CatalogNewButton
                        label="New type"
                        onClick={() => openDialog(null)}
                    />
                }
            >
                <DataTable
                    title="All types"
                    description="Hidden types stay on past applications but are not offered."
                    columns={columns}
                    data={types}
                    getRowId={(type) => type.id}
                    searchable
                    searchPlaceholder="Search types"
                    searchText={(type) =>
                        `${type.name} ${type.description ?? ''}`
                    }
                    empty={{
                        icon: Shapes,
                        title: 'No financing types yet',
                        description:
                            'Add the types you offer, such as Asset financing, Equipment lease or Qard Hasan loan.',
                    }}
                />
            </MemberPage>

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

FinancingTypesIndex.layout = {
    breadcrumbs: [{ title: 'Financing types', href: index() }],
};
