import { Head, Link } from '@inertiajs/react';
import {
    ArrowRight,
    ChevronDown,
    CircleCheck,
    Clock,
    HelpCircle,
    Inbox,
    LifeBuoy,
    MessageSquareWarning,
    MessagesSquare,
    Plus,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import type { ReactNode } from 'react';
import MemberPage from '@/components/member/member-page';
import Pagination from '@/components/member/pagination';
import StatusBadge from '@/components/member/status-badge';
import { ticketStatusTone } from '@/components/member/ticket-thread';
import { formatDateTime } from '@/lib/format';
import { cn } from '@/lib/utils';
import { complaints } from '@/routes';
import { calculator } from '@/routes/financing';
import { show as kycShow } from '@/routes/kyc';
import { create as newSavingsPlan } from '@/routes/savings';
import { create, index, show } from '@/routes/support';
import { edit as editPin } from '@/routes/transaction-pin';
import { create as newTransfer } from '@/routes/transfers';
import type { Paginated, TicketItem } from '@/types';

type Status = TicketItem['status'];

type Counts = Record<'all' | Status, number>;

type HelpTopic = {
    question: string;
    answer: ReactNode;
    category: string;
    link?: { label: string; href: ReturnType<typeof kycShow> };
};

const helpTopics: HelpTopic[] = [
    {
        question: 'How do I add money to my wallet?',
        answer: 'Funding by bank transfer is being connected and will be available soon. Until then, open a ticket and our team will help you fund your wallet.',
        category: 'payments',
    },
    {
        question: 'How does identity verification work?',
        answer: 'Upload three documents on the Verification page: a government-issued ID, a proof of address and a passport photograph. Our team reviews each one and notifies you. Once all three are approved, savings, financing and transfers unlock.',
        category: 'verification',
        link: { label: 'Go to verification', href: kycShow() },
    },
    {
        question: 'How do I apply for financing?',
        answer: 'Verify your identity and set a transaction PIN, then use the calculator to pick an amount and term. The application asks for the purpose, a guarantor and a recent bank statement. Most decisions come within 3 working days, on clear, fair terms.',
        category: 'financing',
        link: { label: 'Open the calculator', href: calculator() },
    },
    {
        question: 'How do I send money to another member?',
        answer: 'Open Transfer, enter their 10-digit account number and check the name we show you. Then enter the amount and confirm with your PIN. Transfers are instant and free: ₦50 to ₦1,000,000 each, up to ₦2,000,000 a day.',
        category: 'payments',
        link: { label: 'Make a transfer', href: newTransfer() },
    },
    {
        question: 'How does auto-save work?',
        answer: 'When you create a savings plan, tick "Save automatically". We move your contribution from your wallet on each due date. If your wallet is short, nothing is taken and we notify you.',
        category: 'savings',
        link: { label: 'Start a savings plan', href: newSavingsPlan() },
    },
    {
        question: 'My PIN is locked or I forgot it',
        answer: 'After 5 wrong attempts, PIN use pauses for 15 minutes, then you can try again. You can change your PIN in Settings with your current PIN. If you have forgotten it, open a ticket and we will help you reset it safely.',
        category: 'account',
        link: { label: 'PIN settings', href: editPin() },
    },
];

const filters: { key: 'all' | Status; label: string }[] = [
    { key: 'all', label: 'All' },
    { key: 'awaiting_member', label: 'Awaiting you' },
    { key: 'open', label: 'Open' },
    { key: 'resolved', label: 'Resolved' },
];

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

function StatTile({
    icon: Icon,
    label,
    value,
    tone,
}: {
    icon: LucideIcon;
    label: string;
    value: number;
    tone: string;
}) {
    return (
        <div className={cn(cardClasses, 'flex items-center gap-3 p-3.5')}>
            <span
                className={cn(
                    'flex size-10 shrink-0 items-center justify-center rounded-landing',
                    tone,
                )}
            >
                <Icon className="size-5" />
            </span>
            <div className="min-w-0">
                <p className="font-display text-xl font-semibold text-ink tabular-nums">
                    {value}
                </p>
                <p className="truncate text-xs text-ink-400">{label}</p>
            </div>
        </div>
    );
}

export default function SupportIndex({
    tickets,
    status,
    counts,
}: {
    tickets: Paginated<TicketItem>;
    status: Status | null;
    counts: Counts;
}) {
    const active = status ?? 'all';

    return (
        <>
            <Head title="Support" />

            <MemberPage
                title="Support"
                description="Find quick answers or ask our team. We reply here and notify you."
                actions={
                    <Link
                        href={create()}
                        className="inline-flex items-center gap-1.5 rounded-full bg-brand px-3.5 py-1.5 text-sm font-semibold text-white hover:bg-brand-hover"
                    >
                        <Plus className="size-4" />
                        New ticket
                    </Link>
                }
            >
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
                    <StatTile
                        icon={MessagesSquare}
                        label="Awaiting your reply"
                        value={counts.awaiting_member}
                        tone="bg-amber-50 text-amber-700"
                    />
                    <StatTile
                        icon={Clock}
                        label="Open with our team"
                        value={counts.open}
                        tone="bg-brand-faint text-brand"
                    />
                    <StatTile
                        icon={CircleCheck}
                        label="Resolved"
                        value={counts.resolved}
                        tone="bg-highlight-faint text-highlight-dark"
                    />
                </div>

                <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,22rem)] lg:items-start">
                    <section className="flex min-w-0 flex-col gap-3">
                        <nav
                            aria-label="Filter tickets"
                            className="flex w-full gap-1 overflow-x-auto rounded-full bg-surface-100 p-1 sm:w-fit"
                        >
                            {filters.map((filter) => (
                                <Link
                                    key={filter.key}
                                    href={index({
                                        query:
                                            filter.key === 'all'
                                                ? {}
                                                : { status: filter.key },
                                    })}
                                    preserveScroll
                                    aria-current={
                                        active === filter.key
                                            ? 'page'
                                            : undefined
                                    }
                                    className={cn(
                                        'shrink-0 rounded-full px-3 py-1.5 text-sm font-semibold whitespace-nowrap transition-colors focus-visible:ring-2 focus-visible:ring-highlight focus-visible:outline-none',
                                        active === filter.key
                                            ? 'bg-white text-ink shadow-landing-sm'
                                            : 'text-ink-500 hover:text-ink',
                                    )}
                                >
                                    {filter.label}{' '}
                                    <span className="text-ink-400">
                                        {counts[filter.key]}
                                    </span>
                                </Link>
                            ))}
                        </nav>

                        {tickets.data.length === 0 ? (
                            <div
                                className={cn(
                                    cardClasses,
                                    'flex flex-col items-center px-5 py-10 text-center',
                                )}
                            >
                                <span className="flex size-12 items-center justify-center rounded-full bg-surface-50">
                                    {counts.all === 0 ? (
                                        <LifeBuoy className="size-6 text-ink-300" />
                                    ) : (
                                        <Inbox className="size-6 text-ink-300" />
                                    )}
                                </span>
                                <p className="mt-3 font-semibold text-ink">
                                    {counts.all === 0
                                        ? 'No tickets yet'
                                        : 'Nothing here'}
                                </p>
                                <p className="mt-1 max-w-sm text-sm text-ink-400">
                                    {counts.all === 0
                                        ? 'Check the common questions first. If you still need help, open a ticket and our team will reply here.'
                                        : 'No tickets with this status.'}
                                </p>
                                {counts.all === 0 && (
                                    <Link
                                        href={create()}
                                        className="mt-4 inline-flex items-center gap-1.5 rounded-full bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-brand-hover"
                                    >
                                        <Plus className="size-4" />
                                        Open your first ticket
                                    </Link>
                                )}
                            </div>
                        ) : (
                            <ul
                                className={cn(
                                    cardClasses,
                                    'divide-y divide-surface-100 overflow-hidden',
                                )}
                            >
                                {tickets.data.map((ticket) => (
                                    <li key={ticket.id}>
                                        <Link
                                            href={show(ticket.id)}
                                            className={cn(
                                                'flex items-center gap-3 px-4 py-3.5 transition-colors hover:bg-surface-50',
                                                ticket.status ===
                                                    'awaiting_member' &&
                                                    'bg-amber-50/40',
                                            )}
                                        >
                                            <div className="min-w-0 flex-1">
                                                <div className="flex items-center gap-2">
                                                    <p className="truncate text-sm font-semibold text-ink">
                                                        {ticket.subject}
                                                    </p>
                                                    {(ticket.priority ===
                                                        'high' ||
                                                        ticket.priority ===
                                                            'urgent') && (
                                                        <span className="shrink-0 rounded-full bg-red-50 px-1.5 text-[10px] leading-4 font-semibold text-red-700">
                                                            {
                                                                ticket.priorityLabel
                                                            }
                                                        </span>
                                                    )}
                                                </div>
                                                <p className="mt-0.5 truncate text-xs text-ink-400">
                                                    <span className="font-mono">
                                                        {ticket.reference}
                                                    </span>{' '}
                                                    · {ticket.categoryLabel} ·{' '}
                                                    {formatDateTime(
                                                        ticket.lastActivityAt,
                                                    )}
                                                </p>
                                            </div>
                                            <StatusBadge
                                                tone={
                                                    ticketStatusTone[
                                                        ticket.status
                                                    ]
                                                }
                                            >
                                                {ticket.statusLabel}
                                            </StatusBadge>
                                        </Link>
                                    </li>
                                ))}
                            </ul>
                        )}

                        <Pagination page={tickets} />
                    </section>

                    <aside className="flex flex-col gap-4">
                        <section className={cn(cardClasses, 'p-4')}>
                            <h2 className="flex items-center gap-2 font-display text-base font-semibold text-ink">
                                <HelpCircle className="size-4 text-brand" />
                                Common questions
                            </h2>
                            <div className="mt-3 divide-y divide-surface-100">
                                {helpTopics.map((topic) => (
                                    <details
                                        key={topic.question}
                                        className="group py-2.5"
                                    >
                                        <summary className="flex cursor-pointer list-none items-center justify-between gap-3 text-sm font-semibold text-ink-700 hover:text-ink [&::-webkit-details-marker]:hidden">
                                            {topic.question}
                                            <ChevronDown className="size-4 shrink-0 text-ink-400 transition-transform group-open:rotate-180" />
                                        </summary>
                                        <p className="mt-2 text-sm leading-relaxed text-ink-500">
                                            {topic.answer}
                                        </p>
                                        <div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs font-semibold">
                                            {topic.link && (
                                                <Link
                                                    href={topic.link.href}
                                                    className="inline-flex items-center gap-1 text-brand hover:text-highlight-dark"
                                                >
                                                    {topic.link.label}
                                                    <ArrowRight className="size-3" />
                                                </Link>
                                            )}
                                            <Link
                                                href={create({
                                                    query: {
                                                        category:
                                                            topic.category,
                                                    },
                                                })}
                                                className="text-ink-500 hover:text-brand"
                                            >
                                                Still stuck? Ask us
                                            </Link>
                                        </div>
                                    </details>
                                ))}
                            </div>
                        </section>

                        <section className="rounded-landing-lg border border-highlight/30 bg-highlight-faint p-4">
                            <h2 className="font-display text-base font-semibold text-ink">
                                How we help
                            </h2>
                            <ul className="mt-2 grid gap-1.5 text-sm text-ink-700">
                                <li>We reply on your ticket and notify you.</li>
                                <li>
                                    Choose High or Urgent priority if money is
                                    involved.
                                </li>
                                <li>
                                    We will never ask for your password or PIN.
                                </li>
                            </ul>
                        </section>

                        <a
                            href={complaints.url()}
                            className={cn(
                                cardClasses,
                                'flex items-start gap-3 p-4 transition-colors hover:border-brand/40',
                            )}
                        >
                            <MessageSquareWarning className="mt-0.5 size-5 shrink-0 text-amber-700" />
                            <span>
                                <span className="block text-sm font-semibold text-ink">
                                    Not happy with our service?
                                </span>
                                <span className="mt-0.5 block text-xs leading-relaxed text-ink-400">
                                    Submit a formal complaint. It goes straight
                                    to our complaints team.
                                </span>
                            </span>
                        </a>
                    </aside>
                </div>
            </MemberPage>
        </>
    );
}

SupportIndex.layout = {
    breadcrumbs: [{ title: 'Support', href: index() }],
};
