import { AngehoerigeSection } from "@/components/employees/AngehoerigeSection";
import { fmtAge, fmtDate } from "@/lib/format";
import type { Database } from "@/lib/supabase/types";

type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"];
type Location = Database["public"]["Tables"]["locations"]["Row"];
type Dependent = Database["public"]["Tables"]["employee_dependents"]["Row"];

function formatAddress(employee: EmployeeRow): string {
  const cityLine = [employee.postal_code, employee.city].filter(Boolean).join(" ");
  return [employee.address, cityLine].filter(Boolean).join(", ") || "–";
}

export function StammdatenTab({ employee, location, dependents }: { employee: EmployeeRow; location?: Location; dependents: Dependent[] }) {
  // Defensive against a DB that hasn't received the title_prefix/title_suffix
  // migration yet — select("*") simply omits unknown columns, so these can
  // be undefined rather than the empty array the column default implies.
  const titles = [...(employee.title_prefix ?? []), ...(employee.title_suffix ?? [])];
  const rows: [string, string][] = [
    ["Titel", titles.length > 0 ? titles.join(", ") : "–"],
    ["Geburtsdatum", `${fmtDate(employee.birth_date)} (${fmtAge(employee.birth_date)} Jahre)`],
    ["SV-Nummer", employee.sv_nummer ?? "–"],
    ["Staatsbürgerschaft", employee.nationality],
    ["E-Mail", employee.email],
    ["Telefon", employee.phone ?? "–"],
    ["Standort", location ? `${location.name} (${location.country})` : "–"],
    ["Adresse", formatAddress(employee)],
    ["Land", employee.address_country ?? "–"],
    ["Geschlecht", employee.gender === "m" ? "männlich" : "weiblich"],
  ];
  return (
    <div className="flex flex-col gap-6">
      <dl className="grid grid-cols-1 gap-x-8 gap-y-4 sm:grid-cols-2 lg:grid-cols-3">
        {rows.map(([label, value]) => (
          <div key={label}>
            <dt className="text-xs font-semibold uppercase tracking-wide text-ink-muted">{label}</dt>
            <dd className="mt-1 text-sm text-ink">{value}</dd>
          </div>
        ))}
      </dl>
      <AngehoerigeSection employeeId={employee.id} dependents={dependents} />
    </div>
  );
}
