import * as SecureStore from 'expo-secure-store';
import type {
  Bid,
  Category,
  ChatMessage,
  Job,
  JobDetail,
  MeResponse,
  User,
} from './types';

const TOKEN_KEY = 'jaforlife_mobile_token';
const DEFAULT_API_URL = 'http://10.0.2.2/job_connect/public/api.php';
const API_BASE_URL = (process.env.EXPO_PUBLIC_API_URL || DEFAULT_API_URL).replace(/\/+$/, '');

export class ApiError extends Error {
  constructor(
    message: string,
    public readonly status: number,
  ) {
    super(message);
    this.name = 'ApiError';
  }
}

interface RequestOptions {
  token?: string;
  method?: 'GET' | 'POST';
  body?: unknown;
  query?: Record<string, string | number | undefined>;
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
  const search = new URLSearchParams({ path });
  Object.entries(options.query || {}).forEach(([key, value]) => {
    if (value !== undefined && String(value) !== '') {
      search.set(key, String(value));
    }
  });

  const headers: Record<string, string> = { Accept: 'application/json' };
  if (options.body !== undefined) {
    headers['Content-Type'] = 'application/json';
  }
  if (options.token) {
    headers.Authorization = `Bearer ${options.token}`;
  }

  let response: Response;
  try {
    response = await fetch(`${API_BASE_URL}?${search.toString()}`, {
      method: options.method || 'GET',
      headers,
      body: options.body === undefined ? undefined : JSON.stringify(options.body),
    });
  } catch {
    throw new Error(
      `Could not connect to the JaforLife API at ${API_BASE_URL}. Check the server address and that your phone or emulator can reach it.`,
    );
  }

  const raw = await response.text();
  let payload: unknown;
  try {
    payload = raw ? JSON.parse(raw) : {};
  } catch {
    throw new Error('The server returned an invalid response. Check the PHP server logs.');
  }

  if (!response.ok) {
    const message = isRecord(payload) && typeof payload.error === 'string'
      ? payload.error
      : `Request failed (${response.status}).`;
    throw new ApiError(message, response.status);
  }

  return payload as T;
}

export async function saveToken(token: string): Promise<void> {
  await SecureStore.setItemAsync(TOKEN_KEY, token);
}

export async function readToken(): Promise<string | null> {
  return SecureStore.getItemAsync(TOKEN_KEY);
}

export async function clearToken(): Promise<void> {
  await SecureStore.deleteItemAsync(TOKEN_KEY);
}

export interface CodeRequest {
  purpose: 'login' | 'register' | 'link';
  phone: string;
  name?: string;
  email?: string;
  role?: 'customer' | 'contractor';
  city?: string;
  parish?: string;
  business_name?: string;
  password?: string;
}

export async function requestCode(body: CodeRequest): Promise<{ challenge_id: number; message: string }> {
  return request('auth/request-code', { method: 'POST', body });
}

export async function verifyCode(
  challengeId: number,
  code: string,
): Promise<{ token: string; expires_at: string; user: User }> {
  return request('auth/verify-code', {
    method: 'POST',
    body: { challenge_id: challengeId, code },
  });
}

export async function signOut(token: string): Promise<void> {
  await request('auth/logout', { method: 'POST', token, body: {} });
}

export async function getMe(token: string): Promise<MeResponse> {
  return request('me', { token });
}

export async function getCategories(): Promise<Category[]> {
  const result = await request<{ categories: Category[] }>('categories');
  return result.categories;
}

export async function getJobs(
  token?: string,
  query: { category?: string; q?: string } = {},
): Promise<Job[]> {
  const result = await request<{ jobs: Job[] }>('jobs', { token, query });
  return result.jobs;
}

export async function getCustomerJobs(token: string): Promise<Job[]> {
  const result = await request<{ jobs: Job[] }>('me/jobs', { token });
  return result.jobs;
}

export async function getContractorBids(token: string): Promise<Bid[]> {
  const result = await request<{ bids: Bid[] }>('me/bids', { token });
  return result.bids;
}

export async function getJob(token: string | undefined, jobId: string | number): Promise<JobDetail> {
  return request(`jobs/${jobId}`, { token });
}

export async function createJob(
  token: string,
  body: {
    title: string;
    description: string;
    location: string;
    parish: string;
    category_id: number;
    budget_min: string;
    budget_max: string;
    preferred_date: string;
  },
): Promise<{ job_id: number; message: string }> {
  return request('jobs', { method: 'POST', token, body });
}

export async function placeBid(
  token: string,
  jobId: string | number,
  body: { amount: string; message: string },
): Promise<{ credits: number; message: string }> {
  return request(`jobs/${jobId}/bids`, { method: 'POST', token, body });
}

export async function acceptBid(
  token: string,
  jobId: string | number,
  bidId: string | number,
): Promise<{ message: string }> {
  return request(`jobs/${jobId}/bids/${bidId}/accept`, { method: 'POST', token, body: {} });
}

export async function getMessages(
  token: string,
  jobId: string | number,
  afterId = 0,
): Promise<{ messages: ChatMessage[]; job_status: string }> {
  return request(`jobs/${jobId}/messages`, { token, query: { after_id: afterId } });
}

export async function sendMessage(
  token: string,
  jobId: string | number,
  body: string,
): Promise<{ message_id: number; message: string }> {
  return request(`jobs/${jobId}/messages`, {
    method: 'POST',
    token,
    body: { body },
  });
}
