import { Head, Link } from '@inertiajs/react';
import {
    ArrowRight,
    BatteryCharging,
    CalendarDays,
    ClipboardList,
    MapPin,
    Sun,
} from 'lucide-react';
import {
    TicketCard,
    ReportIssueButton,
    StatusPill,
} from '@/components/ticket/ticket-ui';
import { formatDate, formatNumber } from '@/lib/format';
import type {
    CustomerAccount,
    CustomerAccountSummary,
    CustomerJob,
    CustomerTicket,
} from '@/types';

type Props = {
    account: CustomerAccount;
    customer: CustomerAccountSummary | null;
    tickets: CustomerTicket[];
    jobs: CustomerJob[];
    counts: {
        open: number;
        waiting_on_you: number;
        urgent: number;
    };
};

export default function TicketDashboard({
    account,
    customer,
    tickets,
    jobs,
    counts,
}: Props) {
    const firstName = account.name.split(' ')[0];

    return (
        <>
            <Head title="Your solar support" />

            <div className="flex flex-col gap-6">
                <div className="flex flex-wrap items-end justify-between gap-4">
                    <div>
                        <p className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
                            {customer?.customer_number ?? 'Your account'}
                        </p>
                        <h1 className="mt-1 text-2xl font-semibold tracking-tight sm:text-3xl">
                            Hello, {firstName}.
                        </h1>
                        <p className="mt-1 text-sm text-muted-foreground">
                            {counts.open === 0
                                ? 'Nothing open right now. Report anything that changes.'
                                : `${counts.open} report${counts.open === 1 ? '' : 's'} being worked on.`}
                        </p>
                    </div>

                    <ReportIssueButton href="/ticket/tickets/new" />
                </div>

                <div className="grid gap-4 sm:grid-cols-3">
                    <SummaryTile
                        label="Open reports"
                        value={counts.open}
                        icon={ClipboardList}
                        tone="text-blue-600 dark:text-blue-300"
                    />
                    <SummaryTile
                        label="Waiting on you"
                        value={counts.waiting_on_you}
                        icon={ArrowRight}
                        tone="text-violet-600 dark:text-violet-300"
                        hint={
                            counts.waiting_on_you > 0
                                ? 'The support team has replied.'
                                : undefined
                        }
                    />
                    <SummaryTile
                        label="Urgent"
                        value={counts.urgent}
                        icon={Sun}
                        tone="text-red-600 dark:text-red-300"
                        hint={
                            counts.urgent > 0
                                ? 'Being triaged first.'
                                : undefined
                        }
                    />
                </div>

                <div className="grid gap-6 lg:grid-cols-[1.3fr_1fr]">
                    <TicketCard
                        title="Your reports"
                        description="Everything you have raised, newest first."
                        action={
                            tickets.length > 0 ? (
                                <Link
                                    href="/ticket/tickets"
                                    className="text-xs font-medium text-solar-ink underline underline-offset-4"
                                >
                                    View all
                                </Link>
                            ) : null
                        }
                    >
                        {tickets.length === 0 ? (
                            <EmptyReports />
                        ) : (
                            <ul className="divide-y divide-hairline">
                                {tickets.slice(0, 5).map((ticket) => (
                                    <li key={ticket.id}>
                                        <Link
                                            href={`/ticket/tickets/${ticket.id}`}
                                            className="-mx-2 flex flex-col gap-1 rounded-lg px-2 py-3 transition-colors hover:bg-muted/60"
                                        >
                                            <div className="flex flex-wrap items-center gap-2">
                                                <span className="font-mono text-xs 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">
                                                        Reply needed
                                                    </span>
                                                ) : null}
                                            </div>
                                            <p className="text-sm font-medium">
                                                {ticket.issue}
                                            </p>
                                            <p className="text-xs text-muted-foreground">
                                                Reported{' '}
                                                {formatDate(
                                                    ticket.reported_at,
                                                )}
                                                {ticket.job
                                                    ? ` · ${ticket.job.job_number}`
                                                    : ''}
                                            </p>
                                        </Link>
                                    </li>
                                ))}
                            </ul>
                        )}
                    </TicketCard>

                    <TicketCard
                        title="Your systems"
                        description="What we installed for you, and how to look after it."
                    >
                        {jobs.length === 0 ? (
                            <p className="text-sm text-muted-foreground">
                                We do not have an installation linked to your
                                account yet. If we installed your system, tell
                                us the address and we will connect it.
                            </p>
                        ) : (
                            <ul className="space-y-3">
                                {jobs.map((job) => (
                                    <li key={job.id}>
                                        <Link
                                            href={`/ticket/jobs/${job.id}`}
                                            className="block rounded-xl p-3 ring-1 ring-hairline transition-colors hover:bg-muted/50"
                                        >
                                            <div className="flex items-center justify-between gap-2">
                                                <span className="font-mono text-xs text-muted-foreground">
                                                    {job.job_number}
                                                </span>
                                                {job.system_size_kw ? (
                                                    <span className="inline-flex items-center gap-1 text-xs font-medium text-solar-ink">
                                                        <Sun className="size-3.5" />
                                                        {formatNumber(
                                                            job.system_size_kw,
                                                        )}{' '}
                                                        kW
                                                    </span>
                                                ) : null}
                                            </div>
                                            <p className="mt-1 text-sm font-medium">
                                                {job.title}
                                            </p>
                                            {job.address ? (
                                                <p className="mt-1 flex items-start gap-1 text-xs text-muted-foreground">
                                                    <MapPin className="mt-0.5 size-3 shrink-0" />
                                                    {job.address}
                                                </p>
                                            ) : null}
                                            <p className="mt-2 flex items-center gap-1 text-xs text-muted-foreground">
                                                <CalendarDays className="size-3" />
                                                {job.status_label}
                                                {job.install_date
                                                    ? ` · ${formatDate(job.install_date)}`
                                                    : ''}
                                            </p>
                                        </Link>
                                    </li>
                                ))}
                            </ul>
                        )}
                    </TicketCard>
                </div>

                <div className="rounded-2xl bg-muted/60 p-5 text-xs leading-relaxed text-muted-foreground">
                    <p className="mb-1 inline-flex items-center gap-1.5 font-medium text-foreground">
                        <BatteryCharging className="size-3.5" />
                        Looking after your system
                    </p>
                    <p>
                        Keep the panels clear of shade and debris, and check the
                        inverter display now and then. Generation on a cloudy day
                        is lower and normal — compare a full day against the same
                        month last year in your monitoring app before reporting a
                        fault. If production is zero, or the inverter is off or
                        showing an error, report it.
                    </p>
                </div>
            </div>
        </>
    );
}

function SummaryTile({
    label,
    value,
    icon: Icon,
    tone,
    hint,
}: {
    label: string;
    value: number;
    icon: React.ComponentType<{ className?: string }>;
    tone: string;
    hint?: string;
}) {
    return (
        <div className="rounded-2xl bg-card p-4 ring-1 ring-hairline">
            <div className="flex items-center justify-between">
                <p className="text-xs font-medium text-muted-foreground">
                    {label}
                </p>
                <Icon className={`size-4 ${tone}`} />
            </div>
            <p className="mt-2 text-2xl font-semibold crm-num">{value}</p>
            {hint ? (
                <p className="mt-1 text-[11px] text-muted-foreground">{hint}</p>
            ) : null}
        </div>
    );
}

function EmptyReports() {
    return (
        <div className="rounded-xl border border-dashed border-hairline px-4 py-8 text-center">
            <ClipboardList className="mx-auto size-6 text-muted-foreground" />
            <p className="mt-2 text-sm font-medium">No reports yet</p>
            <p className="mx-auto mt-1 max-w-sm text-xs text-muted-foreground">
                When something is not right — no generation, a fault code, a
                bill that does not add up — report it here and it goes straight
                to the support desk.
            </p>
            <div className="mt-4">
                <ReportIssueButton
                    href="/ticket/tickets/new"
                    label="Report the first issue"
                />
            </div>
        </div>
    );
}
