"use client";

import { useActionState, useState } from "react";
import type { TransporterVehicleOption } from "@/lib/api/transporter";
import SafeImage from "@/components/ui/SafeImage";
import { assignVehicles } from "./actions";

/**
 * The selection UI, and only the selection UI, runs on the client.
 *
 * Toggling a card repaints its ring immediately, so that one bit of state has to
 * live here — but the list itself arrives as a prop from the server, so nothing
 * is fetched after hydration. The checkboxes are real form controls, which is
 * what lets the Server Action read the selection out of `FormData` rather than
 * out of a hand-assembled JSON body.
 */
export default function VehiclePicker({ items }: { items: TransporterVehicleOption[] }) {
  const [selected, setSelected] = useState<number[]>(() => items.filter((v) => v.is_selected).map((v) => v.id));
  const [msg, formAction, saving] = useActionState(assignVehicles, null);

  const toggle = (id: number) =>
    setSelected((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));

  return (
    <form action={formAction} className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold text-gray-900">My Vehicles</h1>
          <p className="text-sm text-gray-600">Pick the vehicle types you operate.</p>
        </div>
        <button
          type="submit"
          disabled={saving}
          className="rounded-lg bg-[#CC1414] px-5 py-2 text-sm font-medium text-white hover:bg-[#b21010] disabled:opacity-60"
        >
          {saving ? "Saving…" : "Save"}
        </button>
      </div>
      {msg && (
        <div className="rounded-lg bg-emerald-50 px-4 py-2 text-sm text-emerald-800 ring-1 ring-emerald-100">
          {msg}
        </div>
      )}
      {items.length === 0 ? (
        <div className="rounded-xl bg-white p-10 text-center text-sm text-gray-600 shadow-sm ring-1 ring-gray-100">
          No vehicles available.
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {items.map((v) => {
            const isSelected = selected.includes(v.id);
            return (
              <button
                key={v.id}
                type="button"
                onClick={() => toggle(v.id)}
                className={`flex items-center gap-3 rounded-xl bg-white p-4 text-left shadow-sm ring-1 transition ${
                  isSelected ? "ring-2 ring-[#CC1414]" : "ring-gray-100 hover:ring-gray-200"
                }`}
              >
                <div className="relative h-16 w-16 shrink-0 overflow-hidden rounded-lg bg-gray-100">
                  <SafeImage src={v.photo || "/logo.png"} alt={v.name} fill className="object-cover" sizes="64px" />
                </div>
                <div className="min-w-0 flex-1">
                  <div className="truncate text-sm font-semibold text-gray-900">{v.name}</div>
                  {v.type && <div className="text-xs text-gray-500">{v.type}</div>}
                  {v.capacity && <div className="text-xs text-gray-500">Capacity: {v.capacity}</div>}
                </div>
                <input
                  type="checkbox"
                  name="vehicle_ids"
                  value={v.id}
                  checked={isSelected}
                  onChange={() => toggle(v.id)}
                  className="h-4 w-4 accent-[#CC1414]"
                />
              </button>
            );
          })}
        </div>
      )}
    </form>
  );
}
