"use client";

import { useParams } from "next/navigation";
import Link from "next/link";
import { useMemo } from "react";
import useSWR from "swr";
import { Car, Wrench, FileText, Clock, Printer, ArrowLeft } from "lucide-react";
import { HistoryData } from "@/types";
import { formatDate } from "@/lib/format";
import Loading from "@/components/Loading";

const fetcher = (url: string) => fetch(url).then((r) => r.json());

export default function CarHistoryPrintPage() {
  const { id } = useParams();
  const { data: history } = useSWR<HistoryData>(`/api/cars/${id}/history`, fetcher);

  const grouped = useMemo(() => {
    if (!history) return [];
    const map = new Map<string, HistoryData["tasks"]>();
    for (const task of history.tasks) {
      const key = task.title.trim();
      if (!map.has(key)) map.set(key, []);
      map.get(key)!.push(task);
    }
    return Array.from(map.entries())
      .map(([title, tasks]) => ({ title, tasks, count: tasks.length }))
      .sort((a, b) => a.title.localeCompare(b.title));
  }, [history]);

  if (!history) return <Loading />;

  return (
    <div className="min-h-screen bg-white">
      <div className="max-w-5xl mx-auto px-8 py-8">
        <div className="flex items-center justify-between mb-8 no-print">
          <Link
            href={`/cars/${history.car.id}/history`}
            className="inline-flex items-center gap-1 text-sm text-steel-600 hover:text-brand-600"
          >
            <ArrowLeft className="w-4 h-4" /> Back to history
          </Link>
          <button
            onClick={() => window.print()}
            className="px-4 py-2 bg-brand-600 text-white rounded-md text-sm inline-flex items-center gap-2 hover:bg-brand-700"
          >
            <Printer className="w-4 h-4" /> Print
          </button>
        </div>

        <header className="border-b pb-6 mb-6">
          <div className="flex items-center gap-3 mb-2">
            <Car className="w-8 h-8 text-brand-600" />
            <h1 className="text-2xl font-bold">{history.car.regNumber} — Service history</h1>
          </div>
          <div className="grid sm:grid-cols-2 md:grid-cols-4 gap-4 text-sm text-steel-700">
            <Info label="Make" value={history.car.make} />
            <Info label="Model" value={history.car.model} />
            <Info label="Colour" value={history.car.color} />
            <Info label="Year" value={history.car.year ? String(history.car.year) : undefined} />
            <Info label="Owner" value={history.car.ownerName} />
            <Info label="Phone" value={history.car.ownerPhone} />
            <Info label="Email" value={history.car.ownerEmail} />
            <Info label="Mileage" value={history.car.mileage != null ? history.car.mileage.toLocaleString() : undefined} />
          </div>
        </header>

        <section>
          <h2 className="text-lg font-bold mb-4 flex items-center gap-2">
            <Wrench className="w-5 h-5 text-steel-600" /> Service tasks
          </h2>

          {history.tasks.length === 0 ? (
            <p className="text-steel-500">No service history yet.</p>
          ) : (
            <div className="space-y-6">
              {grouped.map((group) => (
                <div key={group.title}>
                  <h3 className="font-bold text-steel-900 mb-2 border-b pb-1">
                    {group.title}{" "}
                    <span className="text-sm font-normal text-steel-500">({group.count})</span>
                  </h3>
                  <ul className="space-y-2">
                    {group.tasks.map((task) => (
                      <li key={task.id} className="text-sm text-steel-700 flex flex-wrap items-center gap-2">
                        <span className="inline-flex items-center gap-1 text-steel-500">
                          <Clock className="w-3 h-3" />
                          {formatDate(task.finishedAt || task.createdAt)}
                        </span>
                        <span>Order #{task.orderId}</span>
                        {task.orderMileage != null && <span>— {task.orderMileage.toLocaleString()} mi</span>}
                        {task.notes && <span>— {task.notes}</span>}
                      </li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>
          )}
        </section>

        <footer className="mt-12 pt-6 border-t text-xs text-steel-400 print-only">
          Printed from Andris Car Service on {new Date().toLocaleDateString("en-IE")}.
        </footer>
      </div>
    </div>
  );
}

function Info({ label, value }: { label: string; value?: string | null }) {
  return (
    <div>
      <div className="text-xs text-steel-500 uppercase">{label}</div>
      <div className="font-medium">{value || "—"}</div>
    </div>
  );
}
