import { Form, Head, router } from '@inertiajs/react';
import { Layers } from 'lucide-react';
import { useState } from 'react';
import SavingsPlanTypeController from '@/actions/App/Http/Controllers/Admin/SavingsPlanTypeController';
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/savings-plan-types';
import type { SelectOption } from '@/types';

type SavingsPlanTypeRow = {
    id: number;
    name: string;
    description: string | null;
    rule: string;
    ruleLabel: string;
    isActive: boolean;
    plans: number;
};

function TypeDialog({
    type,
    rules,
    open,
    onOpenChange,
}: {
    type: SavingsPlanTypeRow | null;
    rules: SelectOption[];
    open: boolean;
    onOpenChange: (open: boolean) => void;
}) {
    const editing = type !== null;
    const action = editing
        ? SavingsPlanTypeController.update.form(type.id)
        : SavingsPlanTypeController.store.form();

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-lg">
                <DialogHeader>
                    <DialogTitle>
                        {editing
                            ? `Edit ${type.name}`
                            : 'New savings plan type'}
                    </DialogTitle>
                    <DialogDescription>
                        Members choose from the types shown here when they open
                        a plan. Plans keep the name and withdrawal rule they
                        were opened 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. School fees"
                                    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. Build up school fees ahead of each term."
                                    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>

                            <div className="grid gap-1.5">
                                <Label htmlFor="withdrawal_rule" required>
                                    Members can withdraw
                                </Label>
                                <select
                                    id="withdrawal_rule"
                                    name="withdrawal_rule"
                                    defaultValue={type?.rule ?? rules[0]?.value}
                                    className="h-9 rounded-md border border-input bg-white px-3 text-sm"
                                >
                                    {rules.map((rule) => (
                                        <option
                                            key={rule.value}
                                            value={rule.value}
                                        >
                                            {rule.label}
                                        </option>
                                    ))}
                                </select>
                                <InputError message={errors.withdrawal_rule} />
                            </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 hide it from new plans.
                                    </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 SavingsPlanTypesIndex({
    types,
    rules,
}: {
    types: SavingsPlanTypeRow[];
    rules: SelectOption[];
}) {
    const [open, setOpen] = useState(false);
    const [editing, setEditing] = useState<SavingsPlanTypeRow | null>(null);

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

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

    const columns: DataTableColumn<SavingsPlanTypeRow>[] = [
        {
            key: 'name',
            header: 'Type',
            sortable: true,
            cell: (type) => (
                <CatalogNameCell
                    name={type.name}
                    description={type.description}
                    isActive={type.isActive}
                />
            ),
        },
        {
            key: 'rule',
            header: 'Members can withdraw',
            hideOnMobile: true,
            className: 'text-xs text-ink-500',
            cell: (type) => type.ruleLabel,
        },
        {
            key: 'plans',
            header: 'Plans',
            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.plans === 0 ? () => remove(type) : undefined}
                />
            ),
        },
    ];

    return (
        <>
            <Head title="Savings plan types" />

            <MemberPage
                title="Savings plan types"
                description="The kinds of savings plans members can open, and when they can withdraw. Each business keeps its own list."
                actions={
                    <CatalogNewButton
                        label="New type"
                        onClick={() => openDialog(null)}
                    />
                }
            >
                <DataTable
                    title="All types"
                    description="Hidden types stay on existing plans but are not offered."
                    columns={columns}
                    data={types}
                    getRowId={(type) => type.id}
                    searchable
                    searchPlaceholder="Search types"
                    searchText={(type) =>
                        `${type.name} ${type.description ?? ''}`
                    }
                    empty={{
                        icon: Layers,
                        title: 'No savings plan types yet',
                        description:
                            'Add the plans you offer, such as Flexible savings, School fees or Festive & Sallah.',
                    }}
                />
            </MemberPage>

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

SavingsPlanTypesIndex.layout = {
    breadcrumbs: [{ title: 'Savings plan types', href: index() }],
};
