"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, Contact, Customer, Paginated } from "@/lib/api";

const schema = z.object({
  customer_id: z.string().min(1),
  full_name: z.string().min(2),
  function: z.string().optional().nullable(),
  email: z.union([z.string().email(), z.literal(""), z.null()]).optional(),
  phone: z.string().optional().nullable()
});

export default function ContactsPage() {
  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<Contact>
      title="Ansprechpartner"
      subtitle="Kontaktpersonen, Funktionen und Kommunikationsdaten."
      endpoint="/contacts"
      columns={[
        { key: "full_name", label: "Name" },
        { key: "function", label: "Funktion" },
        { key: "email", label: "Mail" },
        { key: "phone", label: "Telefon" }
      ]}
      fields={[
        { name: "customer_id", label: "Kunde", type: "select", options: customerOptions },
        { name: "full_name", label: "Name" },
        { name: "function", label: "Funktion" },
        { name: "email", label: "Mail", type: "email" },
        { name: "phone", label: "Telefon" }
      ]}
      schema={schema}
      emptyValues={{ customer_id: "", full_name: "", function: "", email: "", phone: "" }}
    />
  );
}
