import { Head, useForm } from '@inertiajs/react';
import {
    ClipboardList,
    Eye,
    EyeOff,
    KeyRound,
    Lock,
    Mail,
    ShieldAlert,
    ShieldCheck,
    UserRound,
    Wrench,
} from 'lucide-react';
import { useState } from 'react';
import { Callout } from '@/components/crm/page-header';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinner';
import { cn } from '@/lib/utils';
import type { TicketStatusLoginProps } from '@/types';

type Mode = 'staff' | 'link';

/**
 * The front door of the shared status board.
 *
 * Two doors, clearly labelled. A colleague types the details they already use
 * for the CRM and gets the queues their ticket access covers. A crew, or anyone
 * else outside the company, types the username and password the office issued.
 *
 * Written for somebody holding a phone in a ute: one card, two fields, and the
 * plain statement that this is not the CRM and cannot be used to change
 * anything.
 *
 * The staff door is optional. The office switches it in Settings -> Status link,
 * and until they do the card is the issued link alone — a colleague who is
 * signed in to the CRM never sees this page, and one who is not signs in there
 * first. The switch is off by default, so nothing here assumes a form that just
 * arrived with a password field for company accounts.
 */
export default function TicketStatusLogin({
    status,
    staff_account: staffAccount,
    staff_login: staffLogin,
}: TicketStatusLoginProps) {
    const [mode, setMode] = useState<Mode>(staffLogin ? 'staff' : 'link');
    const [reveal, setReveal] = useState(false);

    const staff = useForm({ email: '', password: '' });
    const link = useForm({ username: '', password: '' });

    const submit = (event: React.FormEvent) => {
        event.preventDefault();

        if (mode === 'staff') {
            staff.post('/ticket-status/staff', {
                onFinish: () => staff.reset('password'),
            });

            return;
        }

        link.post('/ticket-status', {
            onFinish: () => link.reset('password'),
        });
    };

    const busy = mode === 'staff' ? staff.processing : link.processing;

    return (
        <>
            <Head title="Ticket status board">
                <meta name="robots" content="noindex,nofollow" />
            </Head>

            <div className="mx-auto grid w-full max-w-5xl gap-6 pt-4 lg:grid-cols-[minmax(0,1fr)_22rem] lg:items-start lg:gap-10">
                <div className="order-2 lg:order-1">
                    <p className="text-solar-ink bg-solar-soft ring-solar/25 inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-medium ring-1 ring-inset">
                        <Wrench className="size-3" />
                        Installer-facing queue
                    </p>

                    <h1 className="mt-4 text-2xl font-semibold tracking-tight sm:text-3xl">
                        Where the faults are up to
                    </h1>

                    <p className="text-muted-foreground mt-2 max-w-prose text-sm leading-relaxed">
                        This board shows the support tickets that are waiting on
                        an installer or on the install itself — the jobs that
                        need somebody on site, not the ones the office is still
                        working. It is read-only and it shows no prices, no
                        contact details beyond a phone number, and no customer
                        history.
                    </p>

                    <ul className="mt-5 grid gap-2.5 sm:grid-cols-2">
                        {[
                            ...(staffLogin
                                ? [
                                      {
                                          icon: ShieldCheck,
                                          title: 'Staff use their own login',
                                          body: 'Your CRM email and password. The queues follow the access you already have.',
                                      },
                                  ]
                                : []),
                            {
                                icon: KeyRound,
                                title: 'Everyone else gets a link',
                                body: 'A username and password from the office, with only the queues it was issued for.',
                            },
                            {
                                icon: Lock,
                                title: 'Temporary',
                                body: 'A shared link can be switched off, or left to run out on its own.',
                            },
                        ].map((item) => (
                            <li
                                key={item.title}
                                className="ring-hairline bg-card shadow-card rounded-xl px-3.5 py-3 ring-1"
                            >
                                <span className="flex items-center gap-2 text-[13px] font-medium">
                                    <item.icon className="text-solar size-3.5" />
                                    {item.title}
                                </span>
                                <p className="text-muted-foreground mt-1 text-[11px] leading-relaxed">
                                    {item.body}
                                </p>
                            </li>
                        ))}
                    </ul>
                </div>

                <div className="order-1 w-full lg:order-2">
                    <div className="ring-hairline bg-card shadow-card overflow-hidden rounded-xl ring-1">
                        <div
                            className={cn(
                                'border-hairline grid gap-1 border-b p-1.5',
                                staffLogin ? 'grid-cols-2' : 'hidden',
                            )}
                            role="tablist"
                            aria-label="How you sign in"
                        >
                            {(
                                [
                                    {
                                        value: 'staff',
                                        label: 'Staff login',
                                        icon: ShieldCheck,
                                    },
                                    {
                                        value: 'link',
                                        label: 'Shared link',
                                        icon: KeyRound,
                                    },
                                ] as const
                            ).map((tab) => (
                                <button
                                    key={tab.value}
                                    type="button"
                                    role="tab"
                                    aria-selected={mode === tab.value}
                                    onClick={() => setMode(tab.value)}
                                    className={cn(
                                        'inline-flex items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-colors',
                                        mode === tab.value
                                            ? 'bg-muted text-foreground ring-hairline ring-1'
                                            : 'text-muted-foreground hover:bg-accent/50 hover:text-foreground',
                                    )}
                                >
                                    <tab.icon className="size-3.5" />
                                    {tab.label}
                                </button>
                            ))}
                        </div>

                        <form
                            className="grid gap-3.5 px-4 py-4"
                            onSubmit={submit}
                        >
                            {status ? (
                                <Callout tone="info" icon={ShieldCheck}>
                                    {status}
                                </Callout>
                            ) : null}

                            {mode === 'staff' && staffAccount ? (
                                <Callout tone="warning" icon={ShieldAlert}>
                                    {staffAccount.name} is signed in, but that
                                    account cannot read support tickets. Use a
                                    shared link password, or ask an
                                    administrator for ticket access.
                                </Callout>
                            ) : null}

                            {mode === 'staff' ? (
                                <>
                                    <div className="grid gap-1.5">
                                        <Label htmlFor="email">
                                            Work email
                                        </Label>
                                        <div className="relative">
                                            <Mail className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 size-3.5 -translate-y-1/2" />
                                            <Input
                                                id="email"
                                                type="email"
                                                value={staff.data.email}
                                                autoComplete="email"
                                                autoCapitalize="none"
                                                autoCorrect="off"
                                                spellCheck={false}
                                                placeholder="you@company.com.au"
                                                className="pl-8"
                                                onChange={(event) =>
                                                    staff.setData(
                                                        'email',
                                                        event.target.value,
                                                    )
                                                }
                                            />
                                        </div>
                                        {staff.errors.email ? (
                                            <p
                                                className="text-danger text-xs font-medium"
                                                role="alert"
                                            >
                                                {staff.errors.email}
                                            </p>
                                        ) : null}
                                    </div>

                                    <div className="grid gap-1.5">
                                        <Label htmlFor="staff-password">
                                            Password
                                        </Label>
                                        <div className="relative">
                                            <Lock className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 size-3.5 -translate-y-1/2" />
                                            <Input
                                                id="staff-password"
                                                type={
                                                    reveal ? 'text' : 'password'
                                                }
                                                value={staff.data.password}
                                                autoComplete="current-password"
                                                className="pr-9 pl-8"
                                                onChange={(event) =>
                                                    staff.setData(
                                                        'password',
                                                        event.target.value,
                                                    )
                                                }
                                            />
                                            <button
                                                type="button"
                                                onClick={() =>
                                                    setReveal(!reveal)
                                                }
                                                aria-label={
                                                    reveal
                                                        ? 'Hide the password'
                                                        : 'Show the password'
                                                }
                                                className="text-muted-foreground hover:text-foreground absolute top-1/2 right-2 -translate-y-1/2 rounded p-1"
                                            >
                                                {reveal ? (
                                                    <EyeOff className="size-3.5" />
                                                ) : (
                                                    <Eye className="size-3.5" />
                                                )}
                                            </button>
                                        </div>
                                        {staff.errors.password ? (
                                            <p
                                                className="text-danger text-xs font-medium"
                                                role="alert"
                                            >
                                                {staff.errors.password}
                                            </p>
                                        ) : null}
                                    </div>
                                </>
                            ) : (
                                <>
                                    <div className="grid gap-1.5">
                                        <Label htmlFor="username">
                                            Username
                                        </Label>
                                        <div className="relative">
                                            <UserRound className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 size-3.5 -translate-y-1/2" />
                                            <Input
                                                id="username"
                                                value={link.data.username}
                                                autoComplete="username"
                                                autoCapitalize="none"
                                                autoCorrect="off"
                                                spellCheck={false}
                                                placeholder="northside-crew"
                                                className="pl-8"
                                                onChange={(event) =>
                                                    link.setData(
                                                        'username',
                                                        event.target.value,
                                                    )
                                                }
                                            />
                                        </div>
                                        {link.errors.username ? (
                                            <p
                                                className="text-danger text-xs font-medium"
                                                role="alert"
                                            >
                                                {link.errors.username}
                                            </p>
                                        ) : null}
                                    </div>

                                    <div className="grid gap-1.5">
                                        <Label htmlFor="password">
                                            Password
                                        </Label>
                                        <div className="relative">
                                            <Lock className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 size-3.5 -translate-y-1/2" />
                                            <Input
                                                id="password"
                                                type={
                                                    reveal ? 'text' : 'password'
                                                }
                                                value={link.data.password}
                                                autoComplete="current-password"
                                                className="pr-9 pl-8"
                                                placeholder="xxxx-xxxx-xxxx"
                                                onChange={(event) =>
                                                    link.setData(
                                                        'password',
                                                        event.target.value,
                                                    )
                                                }
                                            />
                                            <button
                                                type="button"
                                                onClick={() =>
                                                    setReveal(!reveal)
                                                }
                                                aria-label={
                                                    reveal
                                                        ? 'Hide the password'
                                                        : 'Show the password'
                                                }
                                                className="text-muted-foreground hover:text-foreground absolute top-1/2 right-2 -translate-y-1/2 rounded p-1"
                                            >
                                                {reveal ? (
                                                    <EyeOff className="size-3.5" />
                                                ) : (
                                                    <Eye className="size-3.5" />
                                                )}
                                            </button>
                                        </div>
                                        {link.errors.password ? (
                                            <p
                                                className="text-danger text-xs font-medium"
                                                role="alert"
                                            >
                                                {link.errors.password}
                                            </p>
                                        ) : null}
                                    </div>
                                </>
                            )}

                            <Button
                                type="submit"
                                disabled={
                                    busy ||
                                    (mode === 'staff'
                                        ? staff.data.email.trim() === '' ||
                                          staff.data.password === ''
                                        : link.data.username.trim() === '' ||
                                          link.data.password === '')
                                }
                                className="mt-1 w-full"
                            >
                                {busy ? <Spinner /> : null}
                                Open the board
                            </Button>

                            <p className="text-muted-foreground text-[11px] leading-relaxed">
                                {mode === 'staff'
                                    ? 'The same email and password as the CRM. Nothing here can change a ticket.'
                                    : 'This is not the staff login. If these details are not working, ring the office — they can see whether the link is still switched on.'}
                            </p>
                        </form>
                    </div>
                </div>
            </div>
        </>
    );
}
