'use client';

import type { ManagementTableRow } from '@chego/ui';
import { clearSession, readSession } from '../lib/auth-session';

export const apiBase = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3001/api';

export async function fetchWithSession(path: string, init?: RequestInit) {
  const session = readSession();
  if (!session?.accessToken) {
    throw new Error('Sessao administrativa ausente.');
  }

  const headers = new Headers(init?.headers);
  headers.set('Authorization', `Bearer ${session.accessToken}`);
  if (!(init?.body instanceof FormData)) {
    headers.set('Content-Type', 'application/json');
  }

  const response = await fetch(`${apiBase}${path}`, {
    ...init,
    headers,
  });

  const payload = await response.json().catch(() => null);
  if (!response.ok) {
    const message = Array.isArray(payload?.message)
      ? payload.message.join(' ')
      : payload?.message;
    if (response.status === 401) {
      clearSession();
      throw new Error('Sua sessão administrativa expirou ou ficou inválida. Entre novamente.');
    }
    throw new Error(message ?? 'Falha na integracao com a API.');
  }

  return payload;
}

export function currency(value?: number | string | null) {
  const number = Number(value ?? 0);
  return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(number);
}

export function statusTone(status?: string | null) {
  switch (status) {
    case 'ACTIVE':
    case 'DELIVERED':
    case 'PAID':
      return 'emerald';
    case 'PENDING':
    case 'PREPARING':
    case 'DRIVER_ACCEPTED':
      return 'amber';
    case 'SUSPENDED':
    case 'REJECTED':
    case 'CANCELLED':
    case 'FAILED':
      return 'rose';
    default:
      return 'sky';
  }
}

export function humanStatus(status?: string | null) {
  return (status ?? 'UNKNOWN').replaceAll('_', ' ');
}

export type CrudActionState = 'idle' | 'create' | 'edit';

export type FormField = {
  key: string;
  label: string;
  type?: 'text' | 'email' | 'password' | 'select';
  required?: boolean;
  hideOnEdit?: boolean;
  options?: Array<{ label: string; value: string }>;
};

export type CrudPanelProps<TItem extends { id: string }> = {
  title: string;
  endpoint: string;
  fields: FormField[];
  emptyValues: Record<string, string>;
  toFormValues: (item: TItem) => Record<string, string>;
  toPayload: (values: Record<string, string>, mode: CrudActionState) => Record<string, unknown>;
  getColumns: () => Array<{ key: string; label: string; align?: 'left' | 'right' }>;
  getRows: (
    items: TItem[],
    onEdit: (item: TItem) => void,
    onDelete: (item: TItem) => void,
  ) => ManagementTableRow[];
  getPageLabel: (items: TItem[]) => string;
  getMetrics: (items: TItem[]) => Array<{ label: string; value: string; hint: string; tone: 'emerald' | 'amber' | 'rose' | 'sky' }>;
};
