import axios from 'axios'

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1'

export const api = axios.create({
  baseURL: API_URL,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
})

api.interceptors.request.use((config) => {
  if (typeof window !== 'undefined') {
    const token = localStorage.getItem('access_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
  }
  return config
})

api.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (
      typeof window !== 'undefined' &&
      error.response?.status === 401 &&
      !error.config?.url?.includes('/auth/login')
    ) {
      localStorage.removeItem('access_token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  },
)

export interface ApiResponse<T> {
  success?: boolean
  message?: string
  data: T
}

export interface PaginatedMeta {
  current_page: number
  last_page: number
  per_page: number
  total: number
  from: number | null
  to: number | null
}

export interface PaginatedResponse<T> {
  success?: boolean
  data: T[]
  meta: PaginatedMeta
}

export interface User {
  id: number
  name: string
  email: string
  phone?: string
  status: string
  roles: string[]
  permissions?: string[]
  last_login_at?: string
  created_at?: string
  updated_at?: string
}

export interface Partner {
  id: number
  client_code: string
  name: string
  legal_name?: string
  vat_number?: string
  registration_number?: string
  duns_number?: string
  lei_code?: string
  partner_type: string
  industry?: string
  status: string
  contact_person?: string
  phone?: string
  mobile?: string
  email?: string
  website?: string
  street?: string
  city?: string
  state_region?: string
  postal_code?: string
  country?: string
  payment_terms: string
  payment_terms_custom?: string
  opening_balance?: number
  credit_limit?: number
  default_discount?: number
  tax_category?: string
  risk_level: string
  bank_name?: string
  account_iban?: string
  swift_bic?: string
  created_at: string
  updated_at?: string
}

export interface Employee {
  id: number
  employee_code: string
  full_name: string
  surname?: string
  fathers_name?: string
  ssn_sin?: string
  passport_number?: string
  date_of_birth?: string
  gender?: string
  role: string
  department?: string
  phone?: string
  email?: string
  status: string
  employment_type: string
  joining_date?: string
  hourly_rate?: number
  daily_rate?: number
  monthly_base_salary?: number
  bank_name?: string
  account_number?: string
  iban?: string
  swift?: string
  user_id?: number
  created_at: string
  updated_at?: string
}

export interface CompanySettings {
  id: number
  company_name: string
  has_logo?: boolean
  logo_url?: string | null
  default_currency: string
  default_language: string
  timezone: string
  tax_id?: string
  iban?: string
  address?: string
  phone?: string
  email?: string
  website?: string
}

export interface AuditLog {
  id: number
  action: string
  auditable_type?: string
  auditable_id?: number
  user?: { id: number; name: string; email: string }
  created_at: string
}

export interface Project {
  id: number
  project_code: string
  name: string
  category?: string
  summary?: string
  partner_id?: number
  partner?: { id: number; name: string } | null
  manager_id?: number
  status: string
  start_date?: string
  deadline?: string
  no_deadline?: boolean
  budget?: number
  actual_spend?: number
  budget_variance?: number
  progress?: number
  progress_manual?: number | null
  progress_auto?: number
  budget_projection?: number
  time_projection?: string | null
  sites_count?: number
  site_count?: number
  active_sites?: number
  avg_site_progress?: number
  assignments_count?: number
  attendances_count?: number
  sites?: Array<{ id: number; site_code: string; name: string; status: string; progress: number }>
  created_at: string
  updated_at?: string
}

export interface SiteLocation {
  id: number
  site_id: number
  parent_id?: number | null
  location_type: string
  code?: string
  name: string
  description?: string
  children?: SiteLocation[]
}

export interface Site {
  id: number
  project_id: number
  project?: { id: number; name: string; project_code: string } | null
  site_code: string
  name: string
  address?: string
  city?: string
  status: string
  site_manager_id?: number
  site_manager?: { id: number; full_name: string } | null
  start_date?: string
  planned_end_date?: string
  actual_end_date?: string
  progress: number
  notes?: string
  qr_code?: string
  locations?: SiteLocation[]
  locations_count?: number
  assignments_count?: number
  attendances_count?: number
  counts?: {
    assignments: number
    attendances: number
    locations: number
  }
  created_at: string
  updated_at?: string
}

export interface SiteShelf {
  site_id: number
  site_name: string
  site_code: string
  folders: Array<{ name: string; count: number }>
}

export interface Assignment {
  id: number
  site_id: number
  site?: {
    id: number
    name: string
    site_code: string
    project?: { id: number; name: string } | null
  } | null
  assignment_date: string
  employee_id?: number
  employee?: { id: number; full_name: string; employee_code: string } | null
  vehicle_registration?: string
  vehicle_description?: string
  worker_locked?: boolean
  vehicle_locked?: boolean
  is_day_off?: boolean
  status: string
  notes?: string
  created_at: string
  updated_at?: string
}

export interface Attendance {
  id: number
  site_id: number
  site?: { id: number; name: string; site_code: string } | null
  assignment_id?: number
  employee_id: number
  employee?: {
    id: number
    full_name: string
    employee_code: string
    hourly_rate?: number | null
    daily_rate?: number | null
  } | null
  attendance_date: string
  status: string
  check_in_at?: string
  check_out_at?: string
  hours_worked?: number
  notes?: string
  manual_entry?: boolean
  created_at: string
  updated_at?: string
}

export interface AttendanceMonthlyRow {
  employee_id: number
  employee_code: string
  employee_name: string
  site_id: number | null
  site_name: string | null
  total_hours: number
  days_present: number
  days_off_paid: number
  days_off_unpaid: number
  days_absent: number
  hourly_rate: number | null
  daily_rate: number | null
  estimated_pay: number
}

export interface ContractBoqItem {
  id: number
  contract_id: number
  item_code?: string
  description: string
  unit?: string
  quantity: number
  client_unit_price: number
  subcontractor_unit_price?: number
  sort_order?: number
}

export interface ContractMilestone {
  id: number
  contract_id: number
  title: string
  due_date?: string
  amount?: number
  status: string
  sort_order?: number
}

export interface Contract {
  id: number
  project_id: number
  project?: { id: number; name: string; project_code: string } | null
  site_id?: number
  site?: { id: number; name: string; site_code: string } | null
  partner_id?: number
  partner?: { id: number; name: string } | null
  subcontractor_id?: number
  subcontractor?: { id: number; name: string } | null
  parent_contract_id?: number
  contract_type: string
  version: number
  contract_number: string
  title: string
  status: string
  start_date?: string
  end_date?: string
  no_end_date?: boolean
  total_value?: number
  currency: string
  retention_percent: number
  boq_items?: ContractBoqItem[]
  milestones?: ContractMilestone[]
  created_at: string
  updated_at?: string
}

export interface MeasurementRow {
  id: number
  mb_item_group_id: number
  work_description?: string
  unit?: string
  quantity?: number
  length?: number
  width?: number
  height?: number
  multiplier: number
  production: number
  subtotal: number
  performed_by: string
  subcontractor_id?: number
}

export interface MbItemGroup {
  id: number
  measurement_book_id: number
  boq_item_id: number
  boq_item?: {
    id: number
    item_code?: string
    description: string
    unit?: string
  } | null
  site_location_id?: number
  item_type: string
  custom_formula?: unknown
  rows?: MeasurementRow[]
}

export interface MeasurementBook {
  id: number
  contract_id: number
  contract?: { id: number; contract_number: string; title: string } | null
  project_id: number
  project?: { id: number; name: string; project_code: string } | null
  site_id: number
  site?: { id: number; name: string; site_code: string } | null
  mb_number: string
  period_start?: string
  period_end?: string
  status: string
  submitted_at?: string
  verified_at?: string
  approved_at?: string
  rejection_reason?: string
  item_groups?: MbItemGroup[]
  created_at: string
  updated_at?: string
}

export interface IpcLine {
  id: number
  ipc_id: number
  boq_item_id: number
  boq_item?: {
    id: number
    item_code?: string
    description: string
    unit?: string
    quantity?: number
  } | null
  previous_qty: number
  current_qty: number
  cumulative_qty: number
  unit_price: number
  amount: number
  realization_pct: number
}

export interface Ipc {
  id: number
  contract_id: number
  contract?: {
    id: number
    contract_number: string
    title: string
    project_id?: number
    retention_percent?: number
  } | null
  site_id?: number
  site?: { id: number; name: string; site_code: string } | null
  ipc_number: string
  ipc_type: string
  period_start?: string
  period_end?: string
  status: string
  retention_amount: number
  deductions: number
  net_payable: number
  submitted_at?: string
  approved_at?: string
  lines?: IpcLine[]
  created_at: string
  updated_at?: string
}

export interface OfferLine {
  id: number
  offer_id: number
  description: string
  quantity: number
  unit_price: number
  line_total: number
  sort_order?: number
}

export interface Offer {
  id: number
  offer_number: string
  partner_id: number
  partner?: { id: number; name: string } | null
  project_id?: number
  project?: { id: number; name: string; project_code: string } | null
  title: string
  status: string
  valid_until?: string
  currency: string
  subtotal: number
  tax_amount: number
  total: number
  notes?: string
  lines?: OfferLine[]
  created_at: string
  updated_at?: string
}

export interface OrderLine {
  id: number
  order_id: number
  description: string
  quantity: number
  unit_price: number
  line_total: number
}

export interface Order {
  id: number
  order_number: string
  order_type: string
  status: string
  partner_id?: number
  partner?: { id: number; name: string } | null
  project_id?: number
  project?: { id: number; name: string; project_code: string } | null
  site_id?: number
  site?: { id: number; name: string; site_code: string } | null
  offer_id?: number
  title: string
  delivery_date?: string
  currency: string
  total: number
  notes?: string
  lines?: OrderLine[]
  created_at: string
  updated_at?: string
}

export interface DailyActivityLog {
  id: number
  project_id: number
  project?: { id: number; name: string; project_code: string } | null
  site_id: number
  site?: { id: number; name: string; site_code: string } | null
  activity_date: string
  category: string
  description?: string
  quantity?: number
  unit_cost?: number
  total_cost: number
  employee_id?: number
  employee?: { id: number; full_name: string } | null
  created_at: string
}

export interface InspectionTemplate {
  id: number
  name: string
  description?: string
  items: Array<{ key: string; label: string }>
  active: boolean
  created_at: string
}

export interface InspectionItem {
  id: number
  inspection_id: number
  item_key: string
  label: string
  result?: string | null
  photo_path?: string
  notes?: string
}

export interface CorrectiveAction {
  id: number
  issue_id: number
  description: string
  due_date?: string
  completed_at?: string
  created_at: string
}

export interface Issue {
  id: number
  issue_number: string
  inspection_id?: number
  project_id?: number
  project?: { id: number; name: string; project_code: string } | null
  site_id?: number
  site?: { id: number; name: string; site_code: string } | null
  title: string
  description?: string
  status: string
  severity?: string
  actions?: CorrectiveAction[]
  created_at: string
  updated_at?: string
}

export interface Inspection {
  id: number
  inspection_number: string
  template_id?: number
  template?: { id: number; name: string } | null
  project_id: number
  project?: { id: number; name: string; project_code: string } | null
  site_id: number
  site?: { id: number; name: string; site_code: string } | null
  status: string
  inspected_at?: string
  submitted_at?: string
  approved_at?: string
  items?: InspectionItem[]
  issues?: Issue[]
  created_at: string
  updated_at?: string
}

export interface TaxRule {
  id: number
  name: string
  kind: 'vat' | 'withholding' | 'corporate' | 'payroll' | string
  rate: number
  country?: string
  is_default: boolean
  active: boolean
  effective_from?: string
  effective_to?: string
  created_at: string
  updated_at?: string
}

export interface TaxParameter {
  id: number
  name: string
  value: number
  unit?: string
  description?: string
  created_at: string
  updated_at?: string
}

export interface Warehouse {
  id: number
  name: string
  code: string
  type: 'static' | 'project' | string
  project_id?: number
  site_id?: number
  allow_negative: boolean
  project?: { id: number; name: string; project_code: string } | null
  site?: { id: number; name: string; site_code: string } | null
  created_at: string
  updated_at?: string
}

export interface InventoryItem {
  id: number
  sku: string
  name: string
  unit: string
  min_stock?: number | null
  description?: string
  created_at: string
  updated_at?: string
}

export interface StockLevel {
  id: number
  warehouse_id: number
  item_id: number
  quantity: number
  warehouse?: { id: number; name: string; code: string; type?: string } | null
  item?: { id: number; sku: string; name: string; unit: string } | null
}

export interface StockMovement {
  id: number
  warehouse_id: number
  to_warehouse_id?: number | null
  item_id: number
  movement_type: string
  quantity: number
  unit_cost?: number | null
  reference_type?: string | null
  reference_id?: number | null
  notes?: string | null
  created_by?: number | null
  created_at: string
  warehouse?: { id: number; name: string; code: string } | null
  to_warehouse?: { id: number; name: string; code: string } | null
  item?: { id: number; sku: string; name: string; unit: string } | null
}

export interface InvoiceLine {
  id: number
  invoice_id: number
  description: string
  quantity: number
  unit_price: number
  tax_rate: number
  line_total: number
  agreed_unit_price?: number | null
  inventory_item_id?: number | null
  warehouse_id?: number | null
  price_alert?: boolean
  alert_flags?: string[]
}

export interface Payment {
  id: number
  invoice_id: number
  amount: number
  paid_at: string
  method: string
  reference?: string
  notes?: string
  created_at: string
}

export interface Invoice {
  id: number
  invoice_number: string
  invoice_type: string
  status: string
  partner_id: number
  partner?: { id: number; name: string; client_code?: string } | null
  project_id?: number
  project?: { id: number; name: string; project_code?: string } | null
  site_id?: number
  site?: { id: number; name: string; site_code?: string } | null
  ipc_id?: number
  ipc?: { id: number; ipc_number: string; status: string } | null
  issue_date?: string
  due_date?: string
  currency: string
  subtotal: number
  tax_amount: number
  total: number
  amount_paid: number
  balance?: number
  notes?: string
  has_price_alerts?: boolean
  lines?: InvoiceLine[]
  payments?: Payment[]
  created_at: string
  updated_at?: string
}

export interface FinanceDashboard {
  outstanding_ar: number
  outstanding_ap: number
  counts: { sales_open: number; purchase_open: number }
}

export interface LedgerEntry {
  date: string
  type: 'invoice' | 'payment'
  reference: string
  description: string
  debit: number
  credit: number
  balance?: number
  invoice_id?: number
  invoice_type?: string
}

export interface PartnerLedger {
  partner: {
    id: number
    name: string
    client_code: string
    opening_balance: number
  }
  entries: LedgerEntry[]
  closing_balance: number
}

export interface Asset {
  id: number
  asset_code: string
  name: string
  category?: string
  status: string
  purchase_date?: string
  purchase_value?: number
  useful_life_months?: number
  salvage_value?: number
  book_value?: number
  depreciation_method?: string
  partner_id?: number
  partner?: { id: number; name: string } | null
  project_id?: number
  project?: { id: number; name: string } | null
  insurance_expiry?: string
  road_tax_expiry?: string
  inspection_expiry?: string
  notes?: string
  maintenance?: Array<{
    id: number
    service_date: string
    description: string
    cost?: number
    next_due_date?: string
  }>
  depreciation?: Array<{
    id: number
    period_ym: string
    amount: number
    book_value_after: number
  }>
  created_at: string
  updated_at?: string
}

export interface PayrollLine {
  id: number
  payroll_run_id: number
  employee_id: number
  employee?: {
    id: number
    full_name: string
    employee_code: string
    iban?: string
  } | null
  days_worked: number
  hours_worked: number
  gross: number
  tax: number
  social_contrib: number
  net: number
  notes?: string
}

export interface PayrollRun {
  id: number
  period_ym: string
  status: string
  total_gross: number
  total_deductions: number
  total_net: number
  lines?: PayrollLine[]
  created_at: string
  updated_at?: string
}

export interface DocumentRecord {
  id: number
  project_id?: number | null
  project?: { id: number; name: string } | null
  folder_path: string
  title: string
  file_name: string
  mime_type?: string | null
  size_bytes?: number | null
  storage_path: string
  version: number
  lock_status: 'unlocked' | 'locked' | string
  locked_by?: number | null
  uploaded_by?: number | null
  created_at: string
  updated_at?: string
}

export interface NotificationItem {
  id: number
  user_id: number
  title: string
  body?: string | null
  entity_type?: string | null
  entity_id?: number | null
  read_at?: string | null
  created_at: string
}

export interface NotificationPreference {
  id: number
  user_id: number
  event_key: string
  in_app: boolean
  email: boolean
}

export interface NoteItem {
  id: number
  entity_type: string
  entity_id: number
  body: string
  created_by?: number | null
  created_by_user?: { id: number; name: string } | null
  created_at: string
  updated_at?: string
}
