import { useRef, useState } from "react";
import { Form, Head, Link, router, usePage } from "@inertiajs/react";
import {
    AlertTriangle,
    BriefcaseBusiness,
    CalendarDays,
    Camera,
    KeyRound,
    MailCheck,
    ShieldCheck,
    Sparkles,
    Trash2,
    UserRound,
} from "lucide-react";
import ProfileController from "@/actions/App/Http/Controllers/Settings/ProfileController";
import { Field } from "@/components/crm/form-field";
import { KpiTile } from "@/components/crm/kpi-tile";
import {
    Callout,
    MetaStrip,
    PageHeader,
    SectionCard,
} from "@/components/crm/page-header";
import { StatusPill } from "@/components/crm/status-badge";
import DeleteUser from "@/components/delete-user";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useInitials } from "@/hooks/use-initials";
import { formatDate, formatDateTime } from "@/lib/format";
import { edit as appearanceEdit } from "@/routes/appearance";
import { edit as profileEdit } from "@/routes/profile";
import { destroy as destroyAvatar } from "@/routes/profile/avatar";
import { edit as securityEdit } from "@/routes/security";
import { send } from "@/routes/verification";
import type { Auth } from "@/types";

type Profile = {
    phone: string | null;
    job_title: string | null;
    department: string | null;
    employee_code: string | null;
    roles: string[];
    created_at: string | null;
    last_login_at: string | null;
    email_verified_at: string | null;
    stats: {
        customers: number;
        active_jobs: number;
        open_tickets: number;
    };
};

type PageProps = {
    auth: Auth;
};

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",
};

export default function Profile({
    mustVerifyEmail,
    status,
    profile,
}: {
    mustVerifyEmail: boolean;
    status?: string;
    profile: Profile;
}) {
    const { auth } = usePage<PageProps>().props;
    const getInitials = useInitials();
    const fileInput = useRef<HTMLInputElement>(null);
    const [preview, setPreview] = useState<string | null>(null);

    const user = auth.user;
    const roles = profile.roles;

    const removePhoto = (): void => {
        if (
            window.confirm(
                "Remove your photo? Your initials will be shown instead, everywhere your name appears.",
            )
        ) {
            router.delete(destroyAvatar(), { preserveScroll: true });
        }
    };

    return (
        <>
            <Head title="Your profile" />

            <Form
                {...ProfileController.update.form()}
                options={{ preserveScroll: true }}
                className="mx-auto flex w-full max-w-4xl flex-col gap-5"
                encType="multipart/form-data"
            >
                {({ processing, errors }) => (
                    <>
                        <PageHeader
                            eyebrow={
                                <>
                                    <Sparkles className="size-3.5 text-solar" />
                                    <span>Your account</span>
                                    {profile.employee_code ? (
                                        <>
                                            <span
                                                aria-hidden
                                                className="text-muted-foreground/50"
                                            >
                                                ·
                                            </span>
                                            <span className="font-mono">
                                                {profile.employee_code}
                                            </span>
                                        </>
                                    ) : null}
                                </>
                            }
                            title="Your profile"
                            description="The details your team sees, and the ones we use to reach you. Only you and an administrator can change these."
                            actions={
                                <Button
                                    type="submit"
                                    disabled={processing}
                                    data-test="update-profile-button"
                                >
                                    {processing ? "Saving…" : "Save changes"}
                                </Button>
                            }
                        />

                        {/* The hero is the page's own summary: photo, name and
                            how this person fits into the business, before any
                            form field asks them to type anything. */}
                        <section className="shadow-card relative overflow-hidden rounded-2xl bg-gradient-to-br from-solar-soft/70 via-card to-card ring-1 ring-hairline">
                            <div className="pointer-events-none absolute -top-24 -right-16 size-64 rounded-full bg-solar/10 blur-3xl" />
                            <div className="relative flex flex-col gap-5 p-5 sm:flex-row sm:items-center">
                                <div className="relative shrink-0">
                                    <span className="flex size-20 items-center justify-center overflow-hidden rounded-2xl bg-solar-soft text-2xl font-semibold text-solar-ink ring-1 ring-solar/20">
                                        {(preview ?? user.avatar) ? (
                                            <img
                                                src={
                                                    preview ??
                                                    (user.avatar as string)
                                                }
                                                alt={user.name}
                                                className="size-full object-cover"
                                            />
                                        ) : (
                                            getInitials(user.name)
                                        )}
                                    </span>
                                    <span className="absolute -right-1.5 -bottom-1.5 flex size-7 items-center justify-center rounded-full bg-card text-solar-ink ring-1 ring-hairline">
                                        <Camera className="size-3.5" />
                                    </span>
                                </div>

                                <div className="min-w-0 flex-1">
                                    <div className="flex flex-wrap items-center gap-2">
                                        <h2 className="text-xl font-semibold tracking-tight">
                                            {user.name}
                                        </h2>
                                        {roles.length === 0 ? (
                                            <StatusPill tone="slate">
                                                No role assigned
                                            </StatusPill>
                                        ) : (
                                            roles.map((role) => (
                                                <StatusPill
                                                    key={role}
                                                    tone={
                                                        roleTones[role] ??
                                                        "slate"
                                                    }
                                                >
                                                    {role}
                                                </StatusPill>
                                            ))
                                        )}
                                    </div>

                                    <p className="text-muted-foreground mt-1 text-sm">
                                        {profile.job_title ??
                                            "Add your job title so the team knows what you do"}
                                        {profile.department
                                            ? ` · ${profile.department}`
                                            : ""}
                                    </p>

                                    <MetaStrip
                                        className="mt-3"
                                        items={[
                                            {
                                                label: "Email",
                                                value: user.email,
                                            },
                                            {
                                                label: "Member since",
                                                value: formatDate(
                                                    profile.created_at,
                                                ),
                                            },
                                            {
                                                label: "Last sign in",
                                                value: formatDateTime(
                                                    profile.last_login_at,
                                                ),
                                            },
                                        ]}
                                    />
                                </div>
                            </div>
                        </section>

                        <div className="flex flex-col gap-4">
                            <div className="flex flex-col gap-4">
                                <SectionCard
                                    icon={Camera}
                                    tone="solar"
                                    title="Your photo"
                                    description="A face beside your name makes the CRM feel like a team rather than a list of logins."
                                >
                                    <div className="flex flex-wrap items-center gap-4">
                                        <span className="flex size-16 shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted text-lg font-semibold ring-1 ring-hairline">
                                            {(preview ?? user.avatar) ? (
                                                <img
                                                    src={
                                                        preview ??
                                                        (user.avatar as string)
                                                    }
                                                    alt=""
                                                    className="size-full object-cover"
                                                />
                                            ) : (
                                                getInitials(user.name)
                                            )}
                                        </span>

                                        <div className="min-w-0 flex-1">
                                            <div className="flex flex-wrap items-center gap-2">
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    size="sm"
                                                    onClick={() =>
                                                        fileInput.current?.click()
                                                    }
                                                >
                                                    <Camera />
                                                    {(preview ?? user.avatar)
                                                        ? "Change photo"
                                                        : "Add a photo"}
                                                </Button>

                                                {user.avatar ? (
                                                    <Button
                                                        type="button"
                                                        variant="ghost"
                                                        size="sm"
                                                        onClick={removePhoto}
                                                    >
                                                        <Trash2 />
                                                        Remove
                                                    </Button>
                                                ) : null}
                                            </div>

                                            <p className="text-muted-foreground mt-2 text-xs">
                                                JPG, PNG or WebP, up to 4 MB. It
                                                is saved when you save the
                                                profile.
                                            </p>

                                            {errors.avatar ? (
                                                <p
                                                    className="text-danger mt-1 text-xs font-medium"
                                                    role="alert"
                                                >
                                                    {errors.avatar}
                                                </p>
                                            ) : null}
                                        </div>

                                        <input
                                            ref={fileInput}
                                            type="file"
                                            name="avatar"
                                            accept="image/jpeg,image/png,image/webp"
                                            className="sr-only"
                                            onChange={(event) => {
                                                const file =
                                                    event.target.files?.[0];

                                                setPreview(
                                                    file
                                                        ? URL.createObjectURL(
                                                              file,
                                                          )
                                                        : null,
                                                );
                                            }}
                                        />
                                    </div>
                                </SectionCard>

                                <SectionCard
                                    icon={UserRound}
                                    tone="info"
                                    title="Personal details"
                                    description="Your name as it appears on jobs, tickets and the audit trail, and the address you sign in with."
                                >
                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <Field
                                            label="Full name"
                                            htmlFor="name"
                                            error={errors.name}
                                            required
                                            className="sm:col-span-2"
                                        >
                                            <Input
                                                id="name"
                                                name="name"
                                                defaultValue={user.name}
                                                required
                                                autoComplete="name"
                                                placeholder="Full name"
                                            />
                                        </Field>

                                        <Field
                                            label="Email address"
                                            htmlFor="email"
                                            error={errors.email}
                                            hint="This is your sign-in"
                                            required
                                        >
                                            <Input
                                                id="email"
                                                type="email"
                                                name="email"
                                                defaultValue={user.email}
                                                required
                                                autoComplete="username"
                                                placeholder="Email address"
                                            />
                                        </Field>

                                        <Field
                                            label="Phone"
                                            htmlFor="phone"
                                            error={errors.phone}
                                            hint="For the office and crews"
                                        >
                                            <Input
                                                id="phone"
                                                name="phone"
                                                type="tel"
                                                defaultValue={
                                                    profile.phone ?? ""
                                                }
                                                autoComplete="tel"
                                                placeholder="0400 000 000"
                                            />
                                        </Field>
                                    </div>

                                    {mustVerifyEmail &&
                                    user.email_verified_at === null ? (
                                        <Callout
                                            className="mt-4"
                                            tone="warning"
                                            icon={AlertTriangle}
                                            title="Your email address is unverified"
                                        >
                                            <p className="flex flex-wrap items-center gap-x-1.5">
                                                Confirm your address to secure
                                                your account and receive account
                                                email.
                                                <Link
                                                    href={send()}
                                                    as="button"
                                                    className="text-warning font-medium underline underline-offset-4"
                                                >
                                                    Re-send the verification
                                                    email
                                                </Link>
                                            </p>

                                            {status ===
                                            "verification-link-sent" ? (
                                                <p className="mt-1 font-medium">
                                                    A new verification link has
                                                    been sent to your email
                                                    address.
                                                </p>
                                            ) : null}
                                        </Callout>
                                    ) : profile.email_verified_at ? (
                                        <p className="text-muted-foreground mt-4 flex items-center gap-1.5 text-xs">
                                            <MailCheck className="size-3.5 text-success" />
                                            Email confirmed{" "}
                                            {formatDate(
                                                profile.email_verified_at,
                                            )}
                                        </p>
                                    ) : null}
                                </SectionCard>

                                <SectionCard
                                    icon={BriefcaseBusiness}
                                    tone="teal"
                                    title="Work details"
                                    description="How you are listed internally. These appear beside your name on assignments and reports."
                                >
                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <Field
                                            label="Job title"
                                            htmlFor="job_title"
                                            error={errors.job_title}
                                        >
                                            <Input
                                                id="job_title"
                                                name="job_title"
                                                defaultValue={
                                                    profile.job_title ?? ""
                                                }
                                                placeholder="e.g. Site electrician"
                                            />
                                        </Field>

                                        <Field
                                            label="Department"
                                            htmlFor="department"
                                            error={errors.department}
                                        >
                                            <Input
                                                id="department"
                                                name="department"
                                                defaultValue={
                                                    profile.department ?? ""
                                                }
                                                placeholder="e.g. Installations"
                                            />
                                        </Field>

                                        <Field
                                            label="Employee code"
                                            htmlFor="employee_code"
                                            error={errors.employee_code}
                                            hint="Payroll and rosters"
                                        >
                                            <Input
                                                id="employee_code"
                                                name="employee_code"
                                                defaultValue={
                                                    profile.employee_code ?? ""
                                                }
                                                placeholder="e.g. SL-014"
                                            />
                                        </Field>

                                        <Field
                                            label="Roles"
                                            htmlFor="roles"
                                            hint="Set by an administrator"
                                        >
                                            <div className="flex h-9 flex-wrap items-center gap-1.5">
                                                {roles.length === 0 ? (
                                                    <span className="text-muted-foreground text-xs">
                                                        No role assigned yet
                                                    </span>
                                                ) : (
                                                    roles.map((role) => (
                                                        <StatusPill
                                                            key={role}
                                                            tone={
                                                                roleTones[
                                                                    role
                                                                ] ?? "slate"
                                                            }
                                                        >
                                                            {role}
                                                        </StatusPill>
                                                    ))
                                                )}
                                            </div>
                                        </Field>
                                    </div>
                                </SectionCard>

                                <div className="bg-card/85 shadow-raised ring-hairline sticky bottom-4 z-10 flex flex-wrap items-center gap-3 rounded-xl px-4 py-3 ring-1 backdrop-blur">
                                    <Button
                                        type="submit"
                                        disabled={processing}
                                        data-test="update-profile-footer-button"
                                    >
                                        {processing
                                            ? "Saving…"
                                            : "Save changes"}
                                    </Button>
                                    <span className="text-muted-foreground text-xs">
                                        Changes are visible to your team
                                        immediately.
                                    </span>
                                </div>
                            </div>

                            <div className="flex flex-col gap-4">
                                <div className="grid gap-3 sm:grid-cols-3">
                                    <KpiTile
                                        label="Customers you manage"
                                        value={profile.stats.customers}
                                        icon={UserRound}
                                        tone="blue"
                                        hint="Accounts where you are the account manager"
                                        href="/customers"
                                    />
                                    <KpiTile
                                        label="Active jobs"
                                        value={profile.stats.active_jobs}
                                        icon={BriefcaseBusiness}
                                        tone="solar"
                                        hint="Jobs in your name that are still moving"
                                        href="/jobs"
                                    />
                                    <KpiTile
                                        label="Open tickets"
                                        value={profile.stats.open_tickets}
                                        icon={KeyRound}
                                        tone="amber"
                                        hint="Support work assigned to you"
                                        href="/tickets"
                                    />
                                </div>

                                <SectionCard
                                    icon={ShieldCheck}
                                    tone="success"
                                    title="Sign-in & security"
                                    description="Your password, two-factor authentication and passkeys."
                                >
                                    <div className="grid gap-2 sm:grid-cols-2">
                                        <Link
                                            href={securityEdit()}
                                            className="ring-hairline hover:bg-accent/40 flex items-center gap-3 rounded-lg px-3 py-2.5 ring-1 ring-inset transition-colors"
                                        >
                                            <ShieldCheck className="text-success size-4" />
                                            <span className="min-w-0 flex-1">
                                                <span className="block text-sm font-medium">
                                                    Password & two-factor
                                                </span>
                                                <span className="text-muted-foreground block text-xs">
                                                    Change your password or add
                                                    an authenticator app
                                                </span>
                                            </span>
                                        </Link>

                                        <Link
                                            href={appearanceEdit()}
                                            className="ring-hairline hover:bg-accent/40 flex items-center gap-3 rounded-lg px-3 py-2.5 ring-1 ring-inset transition-colors"
                                        >
                                            <Sparkles className="text-solar size-4" />
                                            <span className="min-w-0 flex-1">
                                                <span className="block text-sm font-medium">
                                                    Appearance
                                                </span>
                                                <span className="text-muted-foreground block text-xs">
                                                    Light, dark, or follow your
                                                    system
                                                </span>
                                            </span>
                                        </Link>
                                    </div>

                                    <dl className="border-hairline mt-4 grid gap-3 border-t pt-4 sm:grid-cols-3">
                                        <div className="flex items-baseline justify-between gap-3">
                                            <dt className="text-muted-foreground text-xs">
                                                Signed in as
                                            </dt>
                                            <dd className="truncate text-xs font-medium">
                                                {user.email}
                                            </dd>
                                        </div>
                                        <div className="flex items-baseline justify-between gap-3">
                                            <dt className="text-muted-foreground text-xs">
                                                Last sign in
                                            </dt>
                                            <dd className="text-xs font-medium">
                                                {formatDateTime(
                                                    profile.last_login_at,
                                                )}
                                            </dd>
                                        </div>
                                        <div className="flex items-baseline justify-between gap-3">
                                            <dt className="text-muted-foreground flex items-center gap-1.5 text-xs">
                                                <CalendarDays className="size-3.5" />
                                                Member since
                                            </dt>
                                            <dd className="text-xs font-medium">
                                                {formatDate(profile.created_at)}
                                            </dd>
                                        </div>
                                    </dl>
                                </SectionCard>

                                <Callout
                                    tone="info"
                                    icon={ShieldCheck}
                                    title="Your profile, your record"
                                    className="text-xs"
                                >
                                    Your photo and contact details follow your
                                    name everywhere in the CRM. Roles, access
                                    and whether the account is active are
                                    managed by an administrator on the{" "}
                                    <Link
                                        href="/users"
                                        className="font-medium underline underline-offset-4"
                                    >
                                        staff screen
                                    </Link>
                                    .
                                </Callout>
                            </div>
                        </div>
                    </>
                )}
            </Form>

            <div className="mx-auto mt-6 w-full max-w-4xl">
                <DeleteUser />
            </div>
        </>
    );
}

Profile.layout = {
    breadcrumbs: [
        {
            title: "Your profile",
            href: profileEdit(),
        },
    ],
};
