import { Form, Head, Link, router } 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 {
    Callout,
    KeyValueGrid,
    PageHeader,
    SectionCard,
} from '@/components/crm/page-header';
import { StatusLabel, StatusPill } from '@/components/crm/status-badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { formatDateTime } from '@/lib/format';
import { destroy as userDestroy, index as usersIndex } from '@/routes/users';
import type { RoleOption, UserSummary } from '@/types';

type Props = {
    staffMember: UserSummary;
    roleOptions: RoleOption[];
    can: {
        assignRoles: boolean;
        delete: boolean;
    };
};

const roleTones: Record<string, string> = {
    'Super Admin': 'violet',
    'Managing Director': 'teal',
    Admin: 'blue',
    'Admin Support': 'indigo',
    'Operations Manager': 'amber',
    'Sales Manager': 'cyan',
    Sales: 'emerald',
    Installer: 'orange',
    Warehouse: 'slate',
    Finance: 'green',
};

function roleTone(role: string): string {
    return roleTones[role] ?? 'slate';
}

export default function UsersEdit({ staffMember, roleOptions, can }: Props) {
    const removeStaff = (): void => {
        const confirmed = window.confirm(
            `Hide ${staffMember.name}? Their sign-in stops immediately and everything they did stays on record. Nothing is destroyed — a Super Admin can restore the account from the recycle bin.`,
        );

        if (confirmed) {
            router.delete(userDestroy(staffMember.id).url);
        }
    };

    return (
        <>
            <Head title={`Edit ${staffMember.name}`} />

            <PageHeader
                eyebrow={
                    <>
                        <span>{staffMember.email}</span>
                        {staffMember.employee_code ? (
                            <>
                                <span
                                    aria-hidden
                                    className="text-muted-foreground/50"
                                >
                                    ·
                                </span>
                                <span className="font-mono">
                                    {staffMember.employee_code}
                                </span>
                            </>
                        ) : null}
                        <span aria-hidden className="text-muted-foreground/50">
                            ·
                        </span>
                        <span>Added {formatDateTime(staffMember.created_at)}</span>
                    </>
                }
                title={staffMember.name}
                description={
                    staffMember.job_title
                        ? `${staffMember.job_title}${
                              staffMember.department
                                  ? ` · ${staffMember.department}`
                                  : ''
                          }`
                        : 'Staff account and access'
                }
                actions={
                    <>
                        <StatusLabel
                            tone={staffMember.is_active ? 'success' : 'slate'}
                            quiet={!staffMember.is_active}
                        >
                            {staffMember.is_active ? 'Active' : 'Deactivated'}
                        </StatusLabel>
                        <Button variant="outline" size="sm" asChild>
                            <Link href={usersIndex()}>Back to staff</Link>
                        </Button>
                    </>
                }
            />

            <Form
                {...UserController.update.form({ user: staffMember.id })}
                className="grid gap-5"
            >
                {({ processing, errors }) => (
                    <>
                        <SectionCard
                            title="Account"
                            description="Change the account details. Leave the password fields blank to keep the current password."
                            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"
                                        defaultValue={staffMember.name}
                                    />
                                </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"
                                        defaultValue={staffMember.email}
                                    />
                                </FormField>

                                <FormField
                                    label="New password"
                                    htmlFor="password"
                                    error={errors.password}
                                    hint="Only fill this in to reset their password."
                                >
                                    <Input
                                        id="password"
                                        name="password"
                                        type="password"
                                        autoComplete="new-password"
                                    />
                                </FormField>

                                <FormField
                                    label="Confirm new 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" />
                                Resetting a password signs the person out of
                                their other sessions.
                            </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"
                                        defaultValue={
                                            staffMember.employee_code ?? ''
                                        }
                                    />
                                </FormField>

                                <FormField
                                    label="Phone"
                                    htmlFor="phone"
                                    error={errors.phone}
                                >
                                    <Input
                                        id="phone"
                                        name="phone"
                                        defaultValue={staffMember.phone ?? ''}
                                    />
                                </FormField>

                                <FormField
                                    label="Job title"
                                    htmlFor="job_title"
                                    error={errors.job_title}
                                >
                                    <Input
                                        id="job_title"
                                        name="job_title"
                                        defaultValue={
                                            staffMember.job_title ?? ''
                                        }
                                    />
                                </FormField>

                                <FormField
                                    label="Department"
                                    htmlFor="department"
                                    error={errors.department}
                                >
                                    <Input
                                        id="department"
                                        name="department"
                                        defaultValue={
                                            staffMember.department ?? ''
                                        }
                                    />
                                </FormField>
                            </div>
                        </SectionCard>

                        <SectionCard
                            title="Availability"
                            description="Deactivating keeps the account and its job history but blocks sign in."
                            icon={UserCheck}
                            tone="success"
                        >
                            <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={staffMember.is_active}
                                    className="border-input size-4 shrink-0 rounded-[4px] border shadow-xs"
                                />
                                <span className="text-sm">
                                    Active, this person can sign in
                                </span>
                            </label>

                            <KeyValueGrid
                                className="mt-5"
                                items={[
                                    {
                                        label: 'Last sign in',
                                        value: formatDateTime(
                                            staffMember.last_login_at,
                                        ),
                                    },
                                    {
                                        label: 'Email verified',
                                        value: formatDateTime(
                                            staffMember.email_verified_at,
                                        ),
                                    },
                                ]}
                            />
                        </SectionCard>

                        <SectionCard
                            title="Roles"
                            description="Roles decide what this person can see and do."
                            icon={ShieldCheck}
                            tone="violet"
                        >
                            {can.assignRoles ? (
                                <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={staffMember.roles.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>
                            ) : (
                                <div className="grid gap-3">
                                    <div className="flex flex-wrap gap-1.5">
                                        {staffMember.roles.length === 0 ? (
                                            <span className="text-muted-foreground text-sm">
                                                No roles assigned.
                                            </span>
                                        ) : (
                                            staffMember.roles.map((role) => (
                                                <StatusPill
                                                    key={role}
                                                    tone={roleTone(role)}
                                                >
                                                    {role}
                                                </StatusPill>
                                            ))
                                        )}
                                    </div>
                                    <Callout tone="info">
                                        You do not have permission to change
                                        roles. Only a user with the roles.manage
                                        permission can. The current roles are
                                        submitted unchanged when you save.
                                    </Callout>
                                    {/* Keep the submitted role list intact so validation
                                        still passes when the picker is read only. */}
                                    {staffMember.roles.map((role) => (
                                        <input
                                            key={role}
                                            type="hidden"
                                            name="roles[]"
                                            value={role}
                                        />
                                    ))}
                                </div>
                            )}

                            {errors.roles ? (
                                <p className="text-destructive mt-2 text-sm">
                                    {errors.roles}
                                </p>
                            ) : null}
                        </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}>Save changes</Button>
                            <Button variant="ghost" asChild>
                                <Link href={usersIndex()}>Cancel</Link>
                            </Button>
                        </div>
                    </>
                )}
            </Form>

            {can.delete ? (
                <Callout
                    tone="danger"
                    title="Remove this staff account"
                    actions={
                        <Button
                            type="button"
                            variant="destructive"
                            size="sm"
                            onClick={removeStaff}
                        >
                            Hide this account
                        </Button>
                    }
                >
                    Someone who has worked on jobs is deactivated instead of
                    deleted, because job status history records who made each
                    change.
                </Callout>
            ) : null}
        </>
    );
}

UsersEdit.layout = {
    breadcrumbs: [
        {
            title: 'Staff',
            href: usersIndex(),
        },
        {
            title: 'Edit staff member',
            href: '',
        },
    ],
};
