"use client"

import { useLayoutEffect, useState, type CSSProperties } from "react"

export type ContactsTableColumn =
  | "checkbox"
  | "name"
  | "email"
  | "phone"
  | "job"
  | "labels"

const COLUMN_WIDTHS: Record<ContactsTableColumn, string> = {
  checkbox: "40px",
  name: "minmax(0, 2fr)",
  email: "minmax(0, 2fr)",
  phone: "minmax(0, 1.5fr)",
  job: "minmax(0, 1.5fr)",
  labels: "minmax(0, 1fr)",
}

const COLUMN_LABELS: Record<Exclude<ContactsTableColumn, "checkbox">, string> = {
  name: "Nom",
  email: "E-mail",
  phone: "Numéro de téléphone",
  job: "Fonction et entreprise",
  labels: "Libellés",
}

function columnsForWidth(width: number): ContactsTableColumn[] {
  const cols: ContactsTableColumn[] = ["checkbox", "name"]
  if (width >= 640) cols.push("email")
  if (width >= 768) cols.push("phone")
  if (width >= 1024) cols.push("job", "labels")
  return cols
}

export function useContactsTableColumns() {
  const [visibleColumns, setVisibleColumns] = useState<ContactsTableColumn[]>(() =>
    typeof window === "undefined"
      ? ["checkbox", "name", "email", "phone", "job", "labels"]
      : columnsForWidth(window.innerWidth)
  )

  useLayoutEffect(() => {
    const update = () => setVisibleColumns(columnsForWidth(window.innerWidth))
    update()

    const mqlSm = window.matchMedia("(min-width: 640px)")
    const mqlMd = window.matchMedia("(min-width: 768px)")
    const mqlLg = window.matchMedia("(min-width: 1024px)")

    mqlSm.addEventListener("change", update)
    mqlMd.addEventListener("change", update)
    mqlLg.addEventListener("change", update)
    return () => {
      mqlSm.removeEventListener("change", update)
      mqlMd.removeEventListener("change", update)
      mqlLg.removeEventListener("change", update)
    }
  }, [])

  return { visibleColumns, columnLabels: COLUMN_LABELS }
}

export function contactsTableGridStyle(columns: ContactsTableColumn[]): CSSProperties {
  return {
    gridTemplateColumns: columns.map((c) => COLUMN_WIDTHS[c]).join(" "),
  }
}

export function isContactsColumnVisible(
  columns: ContactsTableColumn[],
  column: ContactsTableColumn
): boolean {
  return columns.includes(column)
}
