import { Form, Head, Link } from '@inertiajs/react';
import {
    ArrowLeft,
    CheckCircle2,
    Circle,
    Download,
    Paperclip,
    Send,
    Sun,
} from 'lucide-react';
import InputError from '@/components/input-error';
import { TicketCard, StatusPill } from '@/components/ticket/ticket-ui';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { formatDate, formatDateTime } from '@/lib/format';
import { cn } from '@/lib/utils';
import type { CustomerTicketDetail } from '@/types';

type Props = {
    ticket: CustomerTicketDetail;
    canReply: boolean;
};

export default function TicketShow({ ticket, canReply }: Props) {
    return (
        <>
            <Head title={`Report ${ticket.display_number}`} />

            <div className="mx-auto flex w-full max-w-3xl flex-col gap-5">
                <div>
                    <Link
                        href="/ticket/tickets"
                        className="inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground"
                    >
                        <ArrowLeft className="size-3.5" />
                        All reports
                    </Link>

                    <div className="mt-3 flex flex-wrap items-center gap-2">
                        <span className="font-mono text-sm text-muted-foreground">
                            {ticket.display_number}
                        </span>
                        <StatusPill status={ticket.status} />
                        {ticket.needs_your_reply ? (
                            <span className="rounded-full bg-violet-500/10 px-2 py-0.5 text-[11px] font-medium text-violet-700 dark:text-violet-300">
                                Your reply is needed
                            </span>
                        ) : null}
                    </div>

                    <h1 className="mt-1 text-2xl font-semibold tracking-tight">
                        {ticket.issue}
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">
                        {ticket.status.description}
                    </p>
                </div>

                {ticket.needs_your_reply ? (
                    <div className="rounded-xl border border-violet-500/25 bg-violet-500/[0.06] px-4 py-3 text-sm text-violet-800 dark:text-violet-300">
                        The support team has asked you something. Reply at the
                        bottom of this page so the report keeps moving.
                    </div>
                ) : null}

                <TicketCard title="Progress">
                    <ol className="grid gap-3 sm:grid-cols-5">
                        {ticket.progress.map((step, index) => (
                            <li
                                key={step.key}
                                className="flex gap-2 sm:flex-col sm:gap-1.5"
                            >
                                <span
                                    className={cn(
                                        'mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full',
                                        step.state === 'done' &&
                                            'bg-emerald-500/15 text-emerald-600 dark:text-emerald-300',
                                        step.state === 'current' &&
                                            'bg-solar-soft text-solar-ink ring-1 ring-solar/40',
                                        step.state === 'todo' &&
                                            'bg-muted text-muted-foreground',
                                    )}
                                >
                                    {step.state === 'done' ? (
                                        <CheckCircle2 className="size-3.5" />
                                    ) : (
                                        <Circle className="size-2.5 fill-current" />
                                    )}
                                </span>
                                <div>
                                    <p
                                        className={cn(
                                            'text-xs font-medium',
                                            step.state === 'todo' &&
                                                'text-muted-foreground',
                                        )}
                                    >
                                        {index + 1}. {step.label}
                                    </p>
                                    <p className="mt-0.5 text-[11px] leading-relaxed text-muted-foreground">
                                        {step.description}
                                    </p>
                                </div>
                            </li>
                        ))}
                    </ol>
                </TicketCard>

                <TicketCard title="What you told us">
                    <div
                        className="hypertext text-sm leading-relaxed"
                        // Sanitized on the server by App\Support\Html before it
                        // reaches this page; the column also holds imported and
                        // customer-sent text, which Html escapes.
                        dangerouslySetInnerHTML={{
                            __html: ticket.description_html,
                        }}
                    />

                    {ticket.attachments.length > 0 ? (
                        <div className="mt-4 border-t border-hairline pt-4">
                            <p className="mb-2 inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                                <Paperclip className="size-3.5" />
                                Your photos and files
                            </p>
                            <ul className="grid gap-2 sm:grid-cols-2">
                                {ticket.attachments.map((attachment) => (
                                    <li key={attachment.id}>
                                        <a
                                            href={attachment.url}
                                            className="flex items-center justify-between gap-2 rounded-lg px-3 py-2 text-xs ring-1 ring-hairline hover:bg-muted/60"
                                        >
                                            <span className="truncate">
                                                {attachment.name}
                                            </span>
                                            <span className="flex items-center gap-2 text-muted-foreground">
                                                {attachment.human_size}
                                                <Download className="size-3.5" />
                                            </span>
                                        </a>
                                    </li>
                                ))}
                            </ul>
                        </div>
                    ) : null}
                </TicketCard>

                {ticket.job ? (
                    <TicketCard title="The system this is about">
                        <Link
                            href={`/ticket/jobs/${ticket.job.id}`}
                            className="flex flex-wrap items-center justify-between gap-3 rounded-xl px-3 py-3 ring-1 ring-hairline hover:bg-muted/60"
                        >
                            <div>
                                <p className="font-mono text-xs text-muted-foreground">
                                    {ticket.job.job_number}
                                </p>
                                <p className="mt-0.5 text-sm font-medium">
                                    {ticket.job.title}
                                </p>
                                {ticket.job.address ? (
                                    <p className="mt-0.5 text-xs text-muted-foreground">
                                        {ticket.job.address}
                                    </p>
                                ) : null}
                            </div>
                            <span className="inline-flex items-center gap-1.5 text-xs font-medium text-solar-ink">
                                <Sun className="size-3.5" />
                                {ticket.job.system_size_kw
                                    ? `${ticket.job.system_size_kw} kW`
                                    : 'View system'}
                            </span>
                        </Link>
                    </TicketCard>
                ) : null}

                {ticket.resolution_html ? (
                    <TicketCard title="How it was resolved">
                        <div
                            className="hypertext text-sm leading-relaxed"
                            dangerouslySetInnerHTML={{
                                __html: ticket.resolution_html,
                            }}
                        />
                        {ticket.dates.resolved_at ? (
                            <p className="mt-2 text-xs text-muted-foreground">
                                Resolved{' '}
                                {formatDateTime(ticket.dates.resolved_at)}
                            </p>
                        ) : null}
                    </TicketCard>
                ) : null}

                <TicketCard
                    title="Conversation"
                    description="Only what we have sent to each other. Anything our team writes internally stays in the office."
                >
                    {ticket.messages.length === 0 ? (
                        <p className="text-sm text-muted-foreground">
                            No replies yet. We will answer here, and the status
                            above changes when we do.
                        </p>
                    ) : (
                        <ul className="space-y-4">
                            {ticket.messages.map((message) => (
                                <li
                                    key={message.id}
                                    className={cn(
                                        'rounded-xl p-3.5',
                                        message.from_customer
                                            ? 'bg-muted/60'
                                            : 'bg-solar-soft/60 ring-1 ring-solar/20',
                                    )}
                                >
                                    <div className="flex flex-wrap items-center justify-between gap-2">
                                        <p className="text-xs font-medium">
                                            {message.from_customer
                                                ? 'You'
                                                : message.author}
                                        </p>
                                        <p className="text-[11px] text-muted-foreground">
                                            {formatDateTime(message.posted_at)}
                                        </p>
                                    </div>
                                    <div
                                        className="hypertext mt-1.5 text-sm leading-relaxed"
                                        dangerouslySetInnerHTML={{
                                            __html: message.body_html,
                                        }}
                                    />
                                </li>
                            ))}
                        </ul>
                    )}

                    {canReply ? (
                        <Form
                            action={`/ticket/tickets/${ticket.id}/reply`}
                            method="post"
                            className="mt-5 border-t border-hairline pt-4"
                        >
                            {({ processing, errors }) => (
                                <>
                                    <label
                                        htmlFor="body"
                                        className="text-sm font-medium"
                                    >
                                        Add a reply
                                    </label>
                                    <textarea
                                        id="body"
                                        name="body"
                                        required
                                        maxLength={5000}
                                        className="border-input mt-2 min-h-24 w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]"
                                        placeholder="Anything else we should know — including a time that suits for a visit."
                                    />
                                    <InputError
                                        message={errors.body}
                                        className="mt-1.5"
                                    />
                                    <div className="mt-3 flex items-center justify-between gap-3">
                                        <p className="text-[11px] text-muted-foreground">
                                            Replies go to the support desk, not
                                            to an emergency service.
                                        </p>
                                        <Button
                                            type="submit"
                                            disabled={processing}
                                        >
                                            {processing ? (
                                                <Spinner />
                                            ) : (
                                                <Send />
                                            )}
                                            Send reply
                                        </Button>
                                    </div>
                                </>
                            )}
                        </Form>
                    ) : (
                        <p className="mt-4 border-t border-hairline pt-4 text-xs text-muted-foreground">
                            This report is closed. If the issue has come back,{' '}
                            <Link
                                href={`/ticket/tickets/new${ticket.job ? `?job=${ticket.job.id}` : ''}`}
                                className="font-medium text-foreground underline underline-offset-4"
                            >
                                log a new report
                            </Link>{' '}
                            so it is triaged again.
                        </p>
                    )}
                </TicketCard>

                <p className="px-1 text-xs text-muted-foreground">
                    Reported {formatDate(ticket.dates.reported_at)}
                    {ticket.dates.acknowledged_at
                        ? ` · acknowledged ${formatDate(ticket.dates.acknowledged_at)}`
                        : ''}
                </p>
            </div>
        </>
    );
}
