"use client";

import { z } from "zod";
import { useQuery } from "@tanstack/react-query";
import { useAuth } from "@/components/auth";
import { CrudPage } from "@/components/crud-page";
import { apiGet, Customer, Location, Paginated } from "@/lib/api";

const schema = z.object({
  customer_id: z.string().min(1),
  name: z.string().min(2),
  street: z.string().optional().nullable(),
  postal_code: z.string().optional().nullable(),
  city: z.string().optional().nullable(),
  room: z.string().optional().nullable()
});

export default function LocationsPage() {
  const { token } = useAuth();
  const customers = useQuery({
    queryKey: ["customers-options", token],
    queryFn: () => apiGet<Paginated<Customer>>("/customers?page=1&page_size=100", token ?? ""),
    enabled: Boolean(token)
  });
  const customerOptions = (customers.data?.items ?? []).map((item) => ({ label: item.name, value: item.id }));
  return (
    <CrudPage<Location>
      title="Standorte"
      subtitle="Standorte und Raeume mit Zuordnung zum Kunden."
      endpoint="/locations"
      columns={[
        { key: "name", label: "Name" },
        { key: "city", label: "Ort" },
        { key: "room", label: "Raum" },
        { key: "customer_id", label: "Kunden-ID" }
      ]}
      fields={[
        { name: "customer_id", label: "Kunde", type: "select", options: customerOptions },
        { name: "name", label: "Name" },
        { name: "street", label: "Adresse" },
        { name: "postal_code", label: "PLZ" },
        { name: "city", label: "Ort" },
        { name: "room", label: "Raum" }
      ]}
      schema={schema}
      emptyValues={{ customer_id: "", name: "", street: "", postal_code: "", city: "", room: "" }}
    />
  );
}
