import { Form, Head, Link } from '@inertiajs/react';
import {
    BriefcaseBusiness,
    KeyRound,
    ShieldCheck,
    UserCheck,
    UserRound,
} from 'lucide-react';
import UserController from '@/actions/App/Http/Controllers/UserController';
import { FormField } from '@/components/crm/native-select';
import { PageHeader, SectionCard } from '@/components/crm/page-header';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { index as usersIndex } from '@/routes/users';
import type { RoleOption } from '@/types';

type Props = {
    roleOptions: RoleOption[];
};

export default function UsersCreate({ roleOptions }: Props) {
    return (
        <>
            <Head title="Add staff" />

            <PageHeader
                eyebrow={<span>New account</span>}
                title="Add staff"
                description="Create the account, then give it the role that matches the job the person does."
            />

            <Form {...UserController.store.form()} className="grid gap-5">
                {({ processing, errors }) => (
                    <>
                        <SectionCard
                            title="Account"
                            description="Who this person is and how they sign in."
                            icon={UserRound}
                            tone="solar"
                        >
                            <div className="grid gap-4 sm:grid-cols-2">
                                <FormField
                                    label="Full name"
                                    htmlFor="name"
                                    error={errors.name}
                                    required
                                >
                                    <Input
                                        id="name"
                                        name="name"
                                        required
                                        autoComplete="name"
                                        placeholder="Jane Citizen"
                                    />
                                </FormField>

                                <FormField
                                    label="Email address"
                                    htmlFor="email"
                                    error={errors.email}
                                    hint="This is their sign in name."
                                    required
                                >
                                    <Input
                                        id="email"
                                        name="email"
                                        type="email"
                                        required
                                        autoComplete="email"
                                        placeholder="jane@solarcompany.com.au"
                                    />
                                </FormField>

                                <FormField
                                    label="Password"
                                    htmlFor="password"
                                    error={errors.password}
                                    hint="Leave both password fields blank and the system generates a temporary password."
                                >
                                    <Input
                                        id="password"
                                        name="password"
                                        type="password"
                                        autoComplete="new-password"
                                    />
                                </FormField>

                                <FormField
                                    label="Confirm password"
                                    htmlFor="password_confirmation"
                                    error={errors.password_confirmation}
                                >
                                    <Input
                                        id="password_confirmation"
                                        name="password_confirmation"
                                        type="password"
                                        autoComplete="new-password"
                                    />
                                </FormField>
                            </div>

                            <p className="text-muted-foreground mt-4 flex items-start gap-2 text-xs">
                                <KeyRound className="mt-0.5 size-3.5 shrink-0" />
                                A generated password is shown once after saving.
                                Passwords are stored hashed and cannot be
                                read back.
                            </p>
                        </SectionCard>

                        <SectionCard
                            title="Employment and contact"
                            description="How they appear on jobs and how the office reaches them."
                            icon={BriefcaseBusiness}
                        >
                            <div className="grid gap-4 sm:grid-cols-2">
                                <FormField
                                    label="Employee code"
                                    htmlFor="employee_code"
                                    error={errors.employee_code}
                                >
                                    <Input
                                        id="employee_code"
                                        name="employee_code"
                                        placeholder="EMP-014"
                                    />
                                </FormField>

                                <FormField
                                    label="Phone"
                                    htmlFor="phone"
                                    error={errors.phone}
                                >
                                    <Input
                                        id="phone"
                                        name="phone"
                                        placeholder="0400 000 000"
                                    />
                                </FormField>

                                <FormField
                                    label="Job title"
                                    htmlFor="job_title"
                                    error={errors.job_title}
                                >
                                    <Input
                                        id="job_title"
                                        name="job_title"
                                        placeholder="Solar Consultant"
                                    />
                                </FormField>

                                <FormField
                                    label="Department"
                                    htmlFor="department"
                                    error={errors.department}
                                >
                                    <Input
                                        id="department"
                                        name="department"
                                        placeholder="Operations"
                                    />
                                </FormField>
                            </div>
                        </SectionCard>

                        <SectionCard
                            title="Availability"
                            description="Deactivating keeps the account and its job history but blocks sign in."
                            icon={UserCheck}
                            tone="success"
                        >
                            {/* The hidden field makes an unticked box submit "0" */}
                            <input type="hidden" name="is_active" value="0" />
                            <label className="ring-hairline hover:bg-accent/40 flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2.5 ring-1 ring-inset">
                                <input
                                    type="checkbox"
                                    name="is_active"
                                    value="1"
                                    defaultChecked
                                    className="border-input size-4 shrink-0 rounded-[4px] border shadow-xs"
                                />
                                <span className="text-sm">
                                    Active, this person can sign in
                                </span>
                            </label>
                        </SectionCard>

                        <SectionCard
                            title="Role"
                            description="Roles decide what a person can see and do. Pick at least one."
                            icon={ShieldCheck}
                            tone="violet"
                        >
                            <RolePicker
                                roleOptions={roleOptions}
                                error={errors.roles}
                            />
                        </SectionCard>

                        <div className="bg-background/85 supports-[backdrop-filter]:bg-background/70 sticky bottom-0 z-10 -mx-4 flex items-center gap-2 border-t px-4 py-3 backdrop-blur sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8">
                            <Button disabled={processing}>Add staff member</Button>
                            <Button variant="ghost" asChild>
                                <Link href={usersIndex()}>Cancel</Link>
                            </Button>
                            <span className="text-muted-foreground ml-auto hidden text-xs sm:block">
                                The account is emailed its sign in details by the
                                office.
                            </span>
                        </div>
                    </>
                )}
            </Form>
        </>
    );
}

/**
 * Roles are chosen with checkboxes rather than a multi select, so each role's
 * description can be shown next to it.
 */
function RolePicker({
    roleOptions,
    defaultSelected = [],
    error,
}: {
    roleOptions: RoleOption[];
    defaultSelected?: string[];
    error?: string;
}) {
    return (
        <div className="grid gap-2">
            <div className="grid gap-2 sm:grid-cols-2">
                {roleOptions.map((role) => (
                    <label
                        key={role.value}
                        className="hover:bg-accent/40 ring-hairline hover:ring-foreground/20 flex cursor-pointer items-start gap-3 rounded-lg px-3 py-2.5 ring-1 ring-inset transition-colors"
                    >
                        <input
                            type="checkbox"
                            name="roles[]"
                            value={role.value}
                            defaultChecked={defaultSelected.includes(role.value)}
                            className="border-input mt-0.5 size-4 shrink-0 rounded-[4px] border shadow-xs"
                        />
                        <span className="min-w-0">
                            <span className="block text-sm font-medium">
                                {role.label}
                            </span>
                            {role.description ? (
                                <span className="text-muted-foreground block text-xs leading-relaxed">
                                    {role.description}
                                </span>
                            ) : null}
                        </span>
                    </label>
                ))}
            </div>
            {error ? (
                <p className="text-destructive text-sm">{error}</p>
            ) : null}
        </div>
    );
}

UsersCreate.layout = {
    breadcrumbs: [
        {
            title: 'Staff',
            href: usersIndex(),
        },
        {
            title: 'Add staff',
            href: '',
        },
    ],
};
