import { Form, Head, Link, usePage } from '@inertiajs/react';
import {
    Bug,
    CircleHelp,
    HandCoins,
    PiggyBank,
    Send,
    ShieldAlert,
    ShieldCheck,
    TrendingUp,
    UserRound,
    Wallet,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { useState } from 'react';
import SupportTicketController from '@/actions/App/Http/Controllers/SupportTicketController';
import InputError from '@/components/input-error';
import MemberPage from '@/components/member/member-page';
import { RequiredMark } from '@/components/required-mark';
import { Spinner } from '@/components/ui/spinner';
import { formatDateTime, formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import { create, index } from '@/routes/support';
import type { SelectOption } from '@/types';

type RecentTransaction = {
    reference: string;
    description: string;
    amount: number;
    direction: 'credit' | 'debit';
    createdAt: string | null;
};

const MIN_MESSAGE = 10;
const MAX_MESSAGE = 5000;

const categoryIcons: Record<string, LucideIcon> = {
    account: UserRound,
    payments: Wallet,
    savings: PiggyBank,
    financing: HandCoins,
    investments: TrendingUp,
    verification: ShieldCheck,
    technical: Bug,
    other: CircleHelp,
};

const priorityHints: Record<string, string> = {
    low: 'A question or suggestion, no rush.',
    normal: 'Something is not working as expected.',
    high: 'Money is involved, e.g. a missing deposit or transfer.',
    urgent: 'You suspect fraud or someone else used your account.',
};

const inputClasses =
    'w-full rounded-landing border border-surface-200 bg-white px-3.5 text-[15px] text-ink outline-none placeholder:text-ink-300 focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15 aria-invalid:border-red-500';

const cardClasses =
    'rounded-landing-lg border border-surface-200 bg-white shadow-landing-sm';

export default function SupportCreate({
    categories,
    priorities,
    recentTransactions,
}: {
    categories: SelectOption[];
    priorities: SelectOption[];
    recentTransactions: RecentTransaction[];
}) {
    // A help topic on the Support page can choose the category for the member.
    const requestedCategory = new URLSearchParams(
        usePage().url.split('?')[1] ?? '',
    ).get('category');
    const [category, setCategory] = useState(
        categories.some((option) => option.value === requestedCategory)
            ? (requestedCategory as string)
            : '',
    );
    const [priority, setPriority] = useState('normal');
    const [message, setMessage] = useState('');
    const [linkedReference, setLinkedReference] = useState('');

    const linkTransaction = (reference: string) => {
        setLinkedReference(reference);

        if (reference !== '' && !message.includes(reference)) {
            setMessage((current) =>
                `${current.trimEnd()}${current.trim() ? '\n\n' : ''}Transaction reference: ${reference}`.slice(
                    0,
                    MAX_MESSAGE,
                ),
            );
        }
    };

    const length = message.trim().length;

    return (
        <>
            <Head title="New support ticket" />

            <MemberPage
                title="New support ticket"
                description="Tell us what you need and our team will reply on the ticket."
            >
                <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,20rem)] lg:items-start">
                    <Form
                        {...SupportTicketController.store.form()}
                        className={cn(cardClasses, 'grid gap-5 p-4 sm:p-6')}
                    >
                        {({ processing, errors }) => (
                            <>
                                <div className="grid gap-2">
                                    <label
                                        htmlFor="subject"
                                        className="text-sm font-semibold text-ink-700"
                                    >
                                        Subject
                                        <RequiredMark />
                                    </label>
                                    <input
                                        id="subject"
                                        name="subject"
                                        required
                                        minLength={5}
                                        maxLength={150}
                                        autoFocus
                                        placeholder="e.g. My transfer has not arrived"
                                        aria-invalid={
                                            errors.subject ? true : undefined
                                        }
                                        className={cn(inputClasses, 'h-11')}
                                    />
                                    <InputError message={errors.subject} />
                                </div>

                                <fieldset className="grid gap-2">
                                    <legend className="mb-2 text-sm font-semibold text-ink-700">
                                        Category
                                        <RequiredMark />
                                    </legend>
                                    <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
                                        {categories.map((option) => {
                                            const Icon =
                                                categoryIcons[option.value] ??
                                                CircleHelp;
                                            const isSelected =
                                                category === option.value;

                                            return (
                                                <label
                                                    key={option.value}
                                                    className={cn(
                                                        'flex cursor-pointer items-center gap-2 rounded-landing border px-2.5 py-2 text-xs font-semibold transition-colors has-focus-visible:ring-2 has-focus-visible:ring-highlight',
                                                        isSelected
                                                            ? 'border-brand bg-brand-faint/40 text-ink ring-2 ring-brand/15'
                                                            : 'border-surface-200 text-ink-700 hover:border-brand/40',
                                                    )}
                                                >
                                                    <input
                                                        type="radio"
                                                        name="category"
                                                        value={option.value}
                                                        required
                                                        checked={isSelected}
                                                        onChange={() =>
                                                            setCategory(
                                                                option.value,
                                                            )
                                                        }
                                                        className="sr-only"
                                                    />
                                                    <Icon className="size-4 shrink-0 text-brand" />
                                                    <span className="min-w-0 leading-tight">
                                                        {option.label}
                                                    </span>
                                                </label>
                                            );
                                        })}
                                    </div>
                                    <InputError message={errors.category} />
                                </fieldset>

                                <fieldset className="grid gap-2">
                                    <legend className="mb-2 text-sm font-semibold text-ink-700">
                                        Priority
                                    </legend>
                                    <div className="grid grid-cols-4 gap-1 rounded-full bg-surface-100 p-1">
                                        {priorities.map((option) => (
                                            <label
                                                key={option.value}
                                                className={cn(
                                                    'cursor-pointer rounded-full px-2 py-1.5 text-center text-xs font-semibold transition-colors has-focus-visible:ring-2 has-focus-visible:ring-highlight sm:text-sm',
                                                    priority === option.value
                                                        ? option.value ===
                                                          'urgent'
                                                            ? 'bg-red-600 text-white'
                                                            : 'bg-white text-ink shadow-landing-sm'
                                                        : 'text-ink-500 hover:text-ink',
                                                )}
                                            >
                                                <input
                                                    type="radio"
                                                    name="priority"
                                                    value={option.value}
                                                    checked={
                                                        priority ===
                                                        option.value
                                                    }
                                                    onChange={() =>
                                                        setPriority(
                                                            option.value,
                                                        )
                                                    }
                                                    className="sr-only"
                                                />
                                                {option.label}
                                            </label>
                                        ))}
                                    </div>
                                    <p className="text-xs text-ink-500">
                                        {priorityHints[priority]}
                                    </p>
                                    <InputError message={errors.priority} />
                                </fieldset>

                                {recentTransactions.length > 0 && (
                                    <div className="grid gap-2">
                                        <label
                                            htmlFor="related_transaction"
                                            className="text-sm font-semibold text-ink-700"
                                        >
                                            Related transaction{' '}
                                            <span className="font-normal text-ink-400">
                                                (optional)
                                            </span>
                                        </label>
                                        <select
                                            id="related_transaction"
                                            value={linkedReference}
                                            onChange={(event) =>
                                                linkTransaction(
                                                    event.target.value,
                                                )
                                            }
                                            className={cn(inputClasses, 'h-11')}
                                        >
                                            <option value="">
                                                None — not about a transaction
                                            </option>
                                            {recentTransactions.map(
                                                (transaction) => (
                                                    <option
                                                        key={
                                                            transaction.reference
                                                        }
                                                        value={
                                                            transaction.reference
                                                        }
                                                    >
                                                        {transaction.direction ===
                                                        'credit'
                                                            ? '+'
                                                            : '−'}
                                                        {formatNaira(
                                                            transaction.amount,
                                                        )}{' '}
                                                        ·{' '}
                                                        {
                                                            transaction.description
                                                        }{' '}
                                                        ·{' '}
                                                        {formatDateTime(
                                                            transaction.createdAt,
                                                        )}
                                                    </option>
                                                ),
                                            )}
                                        </select>
                                        <p className="text-xs text-ink-400">
                                            Its reference is added to your
                                            message so we can find it quickly.
                                        </p>
                                    </div>
                                )}

                                <div className="grid gap-2">
                                    <label
                                        htmlFor="message"
                                        className="text-sm font-semibold text-ink-700"
                                    >
                                        Message
                                        <RequiredMark />
                                    </label>
                                    <textarea
                                        id="message"
                                        name="message"
                                        required
                                        rows={7}
                                        maxLength={MAX_MESSAGE}
                                        value={message}
                                        onChange={(event) =>
                                            setMessage(event.target.value)
                                        }
                                        placeholder="What happened, when, and any amounts or error messages you saw."
                                        aria-invalid={
                                            errors.message ? true : undefined
                                        }
                                        className={cn(inputClasses, 'py-2.5')}
                                    />
                                    <div className="flex justify-between gap-3 text-xs">
                                        <span
                                            className={
                                                length > 0 &&
                                                length < MIN_MESSAGE
                                                    ? 'text-amber-700'
                                                    : 'text-ink-400'
                                            }
                                        >
                                            {length < MIN_MESSAGE
                                                ? `At least ${MIN_MESSAGE} characters.`
                                                : 'More detail helps us solve it faster.'}
                                        </span>
                                        <span className="text-ink-400 tabular-nums">
                                            {message.length}/{MAX_MESSAGE}
                                        </span>
                                    </div>
                                    <InputError message={errors.message} />
                                </div>

                                <div className="flex flex-col-reverse gap-2 sm:flex-row sm:items-center">
                                    <Link
                                        href={index()}
                                        className="inline-flex h-11 items-center justify-center rounded-full px-5 text-sm font-semibold text-ink-500 hover:text-brand"
                                    >
                                        Cancel
                                    </Link>
                                    <button
                                        type="submit"
                                        disabled={processing}
                                        className="inline-flex h-11 flex-1 items-center justify-center gap-2 rounded-full bg-brand px-5 text-[15px] font-semibold text-white transition-colors hover:bg-brand-hover focus-visible:ring-2 focus-visible:ring-highlight focus-visible:ring-offset-2 focus-visible:outline-none disabled:opacity-60"
                                    >
                                        {processing ? (
                                            <Spinner />
                                        ) : (
                                            <Send className="size-4" />
                                        )}
                                        Submit ticket
                                    </button>
                                </div>
                            </>
                        )}
                    </Form>

                    <aside className="flex flex-col gap-4">
                        <section className="rounded-landing-lg border border-highlight/30 bg-highlight-faint p-4">
                            <h2 className="font-display text-base font-semibold text-ink">
                                Before you send
                            </h2>
                            <ul className="mt-2 grid list-disc gap-1.5 pl-4 text-sm text-ink-700">
                                <li>
                                    Check the{' '}
                                    <Link
                                        href={index()}
                                        className="font-semibold text-brand hover:underline"
                                    >
                                        common questions
                                    </Link>{' '}
                                    — the answer may already be there.
                                </li>
                                <li>
                                    Link the transaction, or add its reference,
                                    if money is involved.
                                </li>
                                <li>Include dates and amounts.</li>
                                <li>
                                    One problem per ticket keeps things moving.
                                </li>
                            </ul>
                        </section>

                        <section className={cn(cardClasses, 'p-4')}>
                            <h2 className="font-display text-base font-semibold text-ink">
                                Choosing a priority
                            </h2>
                            <dl className="mt-3 grid gap-2.5 text-sm">
                                {priorities.map((option) => (
                                    <div key={option.value}>
                                        <dt className="font-semibold text-ink">
                                            {option.label}
                                        </dt>
                                        <dd className="text-xs text-ink-400">
                                            {priorityHints[option.value]}
                                        </dd>
                                    </div>
                                ))}
                            </dl>
                        </section>

                        <p className="flex items-start gap-2 rounded-landing border border-amber-200 bg-amber-50 px-3.5 py-3 text-xs text-amber-900">
                            <ShieldAlert className="mt-0.5 size-4 shrink-0" />
                            Never include your password or transaction PIN. Our
                            team will never ask for them.
                        </p>
                    </aside>
                </div>
            </MemberPage>
        </>
    );
}

SupportCreate.layout = {
    breadcrumbs: [
        { title: 'Support', href: index() },
        { title: 'New ticket', href: create() },
    ],
};
