import { Form, Head } from '@inertiajs/react';
import SiteSettingsController from '@/actions/App/Http/Controllers/Settings/SiteSettingsController';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import NairaInput from '@/components/member/naira-input';
import {
    SettingsSectionNav,
    ShowSectionWithError,
    useSettingsSections,
} from '@/components/settings-sections';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
import { edit } from '@/routes/admin/settings';
import type { Organisation } from '@/types';

const limitGroups: {
    title: string;
    description: string;
    fields: { name: LimitField; label: string }[];
}[] = [
    {
        title: 'Withdrawals',
        description: 'What members may request to take out at once.',
        fields: [
            { name: 'withdrawal_min', label: 'Smallest withdrawal' },
            { name: 'withdrawal_max', label: 'Largest withdrawal' },
        ],
    },
    {
        title: 'Member-to-member transfers',
        description: 'Per transfer, and in total per member each day.',
        fields: [
            { name: 'transfer_min', label: 'Smallest transfer' },
            { name: 'transfer_max', label: 'Largest transfer' },
            { name: 'transfer_daily_limit', label: 'Daily limit' },
        ],
    },
    {
        title: 'Counter deposits',
        description: 'Cash, POS and bank transfers recorded by staff.',
        fields: [
            { name: 'deposit_min', label: 'Smallest deposit' },
            { name: 'deposit_max', label: 'Largest deposit' },
        ],
    },
];

type LimitField =
    | 'withdrawal_min'
    | 'withdrawal_max'
    | 'transfer_min'
    | 'transfer_max'
    | 'transfer_daily_limit'
    | 'deposit_min'
    | 'deposit_max';

const tabs: { id: Tab; label: string; description: string }[] = [
    {
        id: 'organisation',
        label: 'Organisation',
        description: 'Name, contact details and complaints inbox',
    },
    {
        id: 'limits',
        label: 'Money limits',
        description: 'Withdrawals, transfers, deposits and guarantors',
    },
    {
        id: 'alerts',
        label: 'Member alerts',
        description: 'Email and SMS alerts to members',
    },
    {
        id: 'security',
        label: 'Sign-in security',
        description: 'Staff two-factor and idle sign-out',
    },
];

type Tab = 'organisation' | 'limits' | 'alerts' | 'security';

/** Which tab holds each field, so a failed save opens the right one. */
const fieldTab: Record<string, Tab> = {
    organisation_name: 'organisation',
    organisation_address: 'organisation',
    organisation_phone: 'organisation',
    organisation_email: 'organisation',
    complaints_email: 'organisation',
    withdrawal_min: 'limits',
    withdrawal_max: 'limits',
    transfer_min: 'limits',
    transfer_max: 'limits',
    transfer_daily_limit: 'limits',
    deposit_min: 'limits',
    deposit_max: 'limits',
    guarantor_limit: 'limits',
    email_alerts: 'alerts',
    sms_alerts: 'alerts',
    require_staff_two_factor: 'security',
    idle_timeout_minutes: 'security',
};

type Props = {
    organisation: Organisation;
    limits: Record<LimitField, number>;
    complaintsEmail: string | null;
    guarantorLimit: number;
    emailAlerts: boolean;
    smsAlerts: boolean;
    smsConfigured: boolean;
    requireStaffTwoFactor: boolean;
    idleTimeoutMinutes: number;
};

export default function SiteSettings({
    organisation,
    limits,
    complaintsEmail,
    guarantorLimit,
    emailAlerts,
    smsAlerts,
    smsConfigured,
    requireStaffTwoFactor,
    idleTimeoutMinutes,
}: Props) {
    const sections = useSettingsSections(tabs);

    const tabHasError = (errors: Record<string, string | undefined>, id: Tab) =>
        Object.keys(errors).some((field) => fieldTab[field] === id);

    return (
        <>
            <Head title="System settings" />

            <h1 className="sr-only">System settings</h1>

            <div className="space-y-6">
                <Form
                    {...SiteSettingsController.update.form()}
                    options={{
                        preserveScroll: true,
                    }}
                    noValidate
                    className="space-y-6"
                >
                    {({ processing, errors }) => (
                        <>
                            <ShowSectionWithError
                                errors={errors}
                                fieldSection={(field) => fieldTab[field]}
                                show={sections.show}
                            />

                            <SettingsSectionNav
                                sections={tabs}
                                state={sections}
                                label="Settings sections"
                                hasError={(id) => tabHasError(errors, id)}
                            />

                            <section
                                role="tabpanel"
                                id="panel-organisation"
                                aria-labelledby="tab-organisation"
                                className={sections.panelClass(
                                    'organisation',
                                    'space-y-6',
                                )}
                            >
                                <div className="grid gap-4">
                                    <Heading
                                        variant="small"
                                        title="Organisation"
                                        description="Shown across the site and printed on receipts and statements."
                                    />
                                    <div className="grid gap-2">
                                        <Label
                                            htmlFor="organisation_name"
                                            required
                                        >
                                            Name
                                        </Label>
                                        <Input
                                            id="organisation_name"
                                            name="organisation_name"
                                            defaultValue={organisation.name}
                                            maxLength={120}
                                            required
                                        />
                                        <InputError
                                            message={errors.organisation_name}
                                        />
                                    </div>
                                    <div className="grid gap-2">
                                        <Label htmlFor="organisation_address">
                                            Office address
                                        </Label>
                                        <Input
                                            id="organisation_address"
                                            name="organisation_address"
                                            defaultValue={
                                                organisation.address ?? ''
                                            }
                                            maxLength={255}
                                        />
                                        <InputError
                                            message={
                                                errors.organisation_address
                                            }
                                        />
                                    </div>
                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <div className="grid gap-2">
                                            <Label htmlFor="organisation_phone">
                                                Phone
                                            </Label>
                                            <Input
                                                id="organisation_phone"
                                                name="organisation_phone"
                                                type="tel"
                                                defaultValue={
                                                    organisation.phone ?? ''
                                                }
                                                maxLength={30}
                                            />
                                            <InputError
                                                message={
                                                    errors.organisation_phone
                                                }
                                            />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label htmlFor="organisation_email">
                                                Email
                                            </Label>
                                            <Input
                                                id="organisation_email"
                                                name="organisation_email"
                                                type="email"
                                                defaultValue={
                                                    organisation.email ?? ''
                                                }
                                                maxLength={255}
                                            />
                                            <InputError
                                                message={
                                                    errors.organisation_email
                                                }
                                            />
                                        </div>
                                    </div>
                                </div>

                                <div className="grid gap-2 border-t pt-6">
                                    <Heading
                                        variant="small"
                                        title="Complaints inbox"
                                        description="Complaints submitted on the public complaints page are emailed to this address"
                                    />
                                    <Label htmlFor="complaints_email" required>
                                        Complaints email
                                    </Label>

                                    <Input
                                        id="complaints_email"
                                        type="email"
                                        className="mt-1 block w-full"
                                        defaultValue={complaintsEmail ?? ''}
                                        name="complaints_email"
                                        required
                                        placeholder="complaints@example.com"
                                    />

                                    <InputError
                                        className="mt-2"
                                        message={errors.complaints_email}
                                    />

                                    {complaintsEmail === null && (
                                        <p className="text-sm text-muted-foreground">
                                            Not set yet — complaints currently
                                            go to the default sender address.
                                        </p>
                                    )}
                                </div>
                            </section>

                            <section
                                role="tabpanel"
                                id="panel-limits"
                                aria-labelledby="tab-limits"
                                className={sections.panelClass(
                                    'limits',
                                    'space-y-6',
                                )}
                            >
                                <div className="grid gap-5">
                                    <Heading
                                        variant="small"
                                        title="Money limits"
                                        description="Whole naira. Changes apply to new requests straight away."
                                    />
                                    {limitGroups.map((group) => (
                                        <fieldset
                                            key={group.title}
                                            className="grid gap-3"
                                        >
                                            <legend className="mb-1 text-sm font-semibold text-ink">
                                                {group.title}
                                                <span className="block text-xs font-normal text-ink-400">
                                                    {group.description}
                                                </span>
                                            </legend>
                                            <div className="grid gap-3 sm:grid-cols-3">
                                                {group.fields.map((field) => (
                                                    <div
                                                        key={field.name}
                                                        className="grid content-start gap-2"
                                                    >
                                                        <Label
                                                            htmlFor={field.name}
                                                            required
                                                        >
                                                            {field.label}
                                                        </Label>
                                                        <NairaInput
                                                            id={field.name}
                                                            name={field.name}
                                                            defaultValue={
                                                                limits[
                                                                    field.name
                                                                ]
                                                            }
                                                            required
                                                        />
                                                        <InputError
                                                            message={
                                                                errors[
                                                                    field.name
                                                                ]
                                                            }
                                                        />
                                                    </div>
                                                ))}
                                            </div>
                                        </fieldset>
                                    ))}
                                </div>

                                <div className="grid gap-2 border-t pt-6">
                                    <Heading
                                        variant="small"
                                        title="Guarantors"
                                        description="How many open loans one person may guarantee at the same time"
                                    />
                                    <Label htmlFor="guarantor_limit" required>
                                        Loans per guarantor
                                    </Label>
                                    <Input
                                        id="guarantor_limit"
                                        type="number"
                                        min={1}
                                        max={20}
                                        className="mt-1 block w-32"
                                        defaultValue={guarantorLimit}
                                        name="guarantor_limit"
                                        required
                                    />
                                    <InputError
                                        className="mt-2"
                                        message={errors.guarantor_limit}
                                    />
                                </div>
                            </section>

                            <section
                                role="tabpanel"
                                id="panel-alerts"
                                aria-labelledby="tab-alerts"
                                className={sections.panelClass(
                                    'alerts',
                                    'space-y-6',
                                )}
                            >
                                <div className="grid gap-3">
                                    <Heading
                                        variant="small"
                                        title="Member alerts"
                                        description="Alerts always appear in the app. Choose whether members also get them by email and SMS: deposits, withdrawals, loan decisions, repayment and contribution reminders, overdue loans and account changes."
                                    />
                                    <input
                                        type="hidden"
                                        name="email_alerts"
                                        value="0"
                                    />
                                    <label className="flex items-center gap-2 text-sm">
                                        <input
                                            type="checkbox"
                                            name="email_alerts"
                                            value="1"
                                            defaultChecked={emailAlerts}
                                            className="size-4 accent-brand"
                                        />
                                        Send alerts by email (to verified
                                        addresses)
                                    </label>
                                    <input
                                        type="hidden"
                                        name="sms_alerts"
                                        value="0"
                                    />
                                    <label className="flex items-center gap-2 text-sm">
                                        <input
                                            type="checkbox"
                                            name="sms_alerts"
                                            value="1"
                                            defaultChecked={smsAlerts}
                                            disabled={!smsConfigured}
                                            className="size-4 accent-brand"
                                        />
                                        Send alerts by SMS
                                    </label>
                                    {!smsConfigured && (
                                        <p className="text-sm text-muted-foreground">
                                            SMS is not set up on the server yet
                                            (SMS_DRIVER, SMS_API_KEY and
                                            SMS_SENDER_ID in .env).
                                        </p>
                                    )}
                                </div>
                            </section>

                            <section
                                role="tabpanel"
                                id="panel-security"
                                aria-labelledby="tab-security"
                                className={sections.panelClass(
                                    'security',
                                    'space-y-6',
                                )}
                            >
                                <div className="grid gap-3">
                                    <Heading
                                        variant="small"
                                        title="Sign-in security"
                                        description="Protect staff accounts and unattended screens."
                                    />
                                    <input
                                        type="hidden"
                                        name="require_staff_two_factor"
                                        value="0"
                                    />
                                    <label className="flex items-center gap-2 text-sm">
                                        <input
                                            type="checkbox"
                                            name="require_staff_two_factor"
                                            value="1"
                                            defaultChecked={
                                                requireStaffTwoFactor
                                            }
                                            className="size-4 accent-brand"
                                        />
                                        Staff must use two-factor sign-in to
                                        open admin pages
                                    </label>
                                    <Label
                                        htmlFor="idle_timeout_minutes"
                                        required
                                    >
                                        Sign out after this many minutes of
                                        inactivity (0 = never)
                                    </Label>
                                    <Input
                                        id="idle_timeout_minutes"
                                        type="number"
                                        min={0}
                                        max={240}
                                        className="block w-32"
                                        defaultValue={idleTimeoutMinutes}
                                        name="idle_timeout_minutes"
                                        required
                                    />
                                    <InputError
                                        message={errors.idle_timeout_minutes}
                                    />
                                </div>
                            </section>

                            <div
                                className={cn(
                                    'flex items-center gap-4 border-t pt-6',
                                    sections.hiddenOnList,
                                )}
                            >
                                <Button
                                    disabled={processing}
                                    data-test="update-site-settings-button"
                                >
                                    Save settings
                                </Button>
                                <p className="text-xs text-ink-400">
                                    Saves every tab at once.
                                </p>
                            </div>
                        </>
                    )}
                </Form>
            </div>
        </>
    );
}

SiteSettings.layout = {
    breadcrumbs: [
        {
            title: 'System settings',
            href: edit(),
        },
    ],
};
