import type { Credential } from "$lib/optima-api/modules/credentials";
import type { CredentialType } from "$lib/optima-api/modules/credentialTypes";
import type { UnifiSite } from "$lib/optima-api/modules/unifi";
import type { PermissionMap } from "$lib/permissions";

export interface CompanyData {
  id: string;
  name: string;
  status?: string;
  type?: string;
  createdAt?: string;
  updatedAt?: string;
  identifier?: string;
  contactEmail?: string;
  contactPhone?: string;
  address?: string;
  city?: string;
  state?: string;
  zip?: string;
  country?: string;
  cw_Data?: {
    address?: {
      line1?: string;
      line2?: string | null;
      city?: string;
      state?: string;
      zip?: string;
      country?: string;
    };
    allAddresses?: Array<{
      id: number;
      uid: string;
      name: string;
      description?: string | null;
      defaultFlag: boolean;
      inactiveFlag: boolean;
      addressLine1?: string | null;
      addressLine2?: string | null;
      city?: string | null;
      state?: string | null;
      zip?: string | null;
      country?: string | null;
      phone?: string | null;
    }>;
    primaryContact?: {
      firstName?: string;
      lastName?: string;
      cwId?: number;
      inactive?: boolean;
      title?: string;
      phone?: string;
      email?: string;
    };
    allContacts?: Array<{
      firstName?: string;
      lastName?: string;
      cwId?: number;
      inactive?: boolean;
      title?: string;
      phone?: string;
      email?: string;
    }>;
    [key: string]: unknown;
  };
  [key: string]: unknown;
}

export interface ConfigurationData {
  id: string | number;
  name: string;
  active?: boolean;
  serialNumber?: string;
  status?: {
    id: number;
    name: string;
  };
  type?: {
    id: number;
    name: string;
    _info?: { type_href?: string };
  };
  notes?: string;
  questions?: Array<{
    id: number;
    question: string;
    answer?: string;
    fieldType: string;
  }> | null;
  info?: {
    lastUpdated?: string;
    updatedBy?: string;
    dateEntered?: string;
    enteredBy?: string;
  };
  key?: string;
  value?: string;
  description?: string;
  createdAt?: string;
  updatedAt?: string;
  [key: string]: unknown;
}

export interface PageData {
  company: CompanyData | null;
  configurations: ConfigurationData[];
  credentials: Credential[];
  credentialTypes: CredentialType[];
  unifiSites: UnifiSite[];
  accessToken: string | null;
  permissions: PermissionMap;
}

// Shared utility functions
export function companyInitials(name: string): string {
  return name
    .split(/\s+/)
    .slice(0, 2)
    .map((w) => w[0])
    .join("")
    .toUpperCase();
}

export function statusClass(status?: string): string {
  if (!status) return "neutral";
  const s = status.toLowerCase();
  if (s === "active") return "active";
  if (s === "inactive" || s === "disabled") return "inactive";
  if (s === "pending") return "pending";
  return "neutral";
}

export function configStatusClass(statusName?: string): string {
  if (!statusName) return "neutral";
  const s = statusName.toLowerCase();
  if (s === "active") return "active";
  if (s === "inactive" || s === "automate inactive") return "inactive";
  if (s === "reserved") return "reserved";
  if (s === "provisioning" || s === "pending approval") return "pending";
  return "neutral";
}

export function formatDate(dateStr?: string): string {
  if (!dateStr) return "";
  try {
    const dateOnly = dateStr.split("T")[0];
    const date = new Date(dateOnly + "T00:00:00");
    if (isNaN(date.getTime())) return "";
    return date.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  } catch {
    return "";
  }
}

export function formatPhone(phone?: string): string {
  if (!phone) return "";
  const digits = phone.replace(/\D/g, "");
  if (digits.length === 10) {
    return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
  }
  if (digits.length === 11 && digits.startsWith("1")) {
    return `+1 (${digits.slice(1, 4)}) ${digits.slice(4, 7)}-${digits.slice(7)}`;
  }
  return phone;
}

export function formatValueTypeLabel(vt: string): string {
  return vt
    .split("_")
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(" ");
}

export function formatAddress(c: CompanyData): string[] {
  const addr = c.cw_Data?.address;
  if (addr) {
    const lines: string[] = [];
    if (addr.line1) lines.push(addr.line1);
    if (addr.line2) lines.push(addr.line2);
    const cityStateZip = [addr.city, addr.state, addr.zip]
      .filter(Boolean)
      .join(", ");
    if (cityStateZip) lines.push(cityStateZip);
    if (addr.country) lines.push(addr.country);
    return lines;
  }
  const lines: string[] = [];
  if (c.address) lines.push(c.address);
  const cityStateZip = [c.city, c.state, c.zip].filter(Boolean).join(", ");
  if (cityStateZip) lines.push(cityStateZip);
  if (c.country) lines.push(c.country);
  return lines;
}

export function formatUptime(seconds: number): string {
  const days = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const mins = Math.floor((seconds % 3600) / 60);
  if (days > 0) return `${days}d ${hours}h`;
  if (hours > 0) return `${hours}h ${mins}m`;
  return `${mins}m`;
}
