/**
 * EAMCO Office Frontend API Response Models
 *
 * This file contains TypeScript interfaces for all API responses
 * to replace 'any' types throughout the application.
 */

// Local type definitions for Axios (workaround for bundler moduleResolution issue)
export interface AxiosResponse<T = any, D = any> {
  data: T;
  status: number;
  statusText: string;
  headers: Record<string, string>;
  config: any;
  request?: any;
}

export interface AxiosError<T = unknown, D = any> extends Error {
  config?: any;
  code?: string;
  request?: any;
  response?: AxiosResponse<T, D>;
  isAxiosError: boolean;
}

import {
  DeliveryStatusType,
  PaymentStatusType,
  AutoStatusType,
  TransactionStatusType,
  CustomerAutomaticStatus
} from '../constants/status';

// Base interfaces
export interface BaseEntity {
  id: number;
}

export interface ApiResponse<T> {
  ok: boolean;
  data?: T;
  error?: string;
}

export interface PaginatedResponse<T> {
  data: T[];
  total: number;
  page: number;
  per_page: number;
}

// Customer interfaces
export interface Customer extends BaseEntity {
  user_id?: number;
  auth_net_profile_id?: string;
  account_number: string;
  customer_first_name: string;
  customer_last_name: string;
  customer_town: string;
  customer_state: number;
  customer_zip: string;
  customer_first_call?: string;
  customer_email?: string;
  customer_automatic: CustomerAutomaticStatus;
  customer_phone_number?: string;
  customer_home_type: number;
  customer_apt?: string;
  customer_address: string;
  company_id: number;
  customer_latitude?: string;
  customer_longitude?: string;
  correct_address: boolean;
}


export interface CustomerDescription extends BaseEntity {
  customer_id: number;
  account_number: string;
  company_id: number;
  fill_location?: number;
  description?: string;
}

export interface TankInspection extends BaseEntity {
  customer_id: number;
  last_tank_inspection?: string;
  tank_status: boolean;
  outside_or_inside: boolean;
  tank_size: number;
  tank_images?: number;
  tank_image_upload_dates?: string[];
}

export interface CustomerStats extends BaseEntity {
  customer_id: number;
  total_calls: number;
  service_calls_total: number;
  service_calls_total_spent: number;
  service_calls_total_profit: number;
  oil_deliveries: number;
  oil_total_gallons: number;
  oil_total_spent: number;
  oil_total_profit: number;
}

// Delivery interfaces
export interface Delivery extends BaseEntity {
  customer_id: number;
  customer_name: string;
  customer_address: string;
  customer_town: string;
  customer_state: string;
  customer_zip: string;
  gallons_ordered: number;
  customer_asked_for_fill: number;
  gallons_delivered: number;
  customer_filled: number;
  delivery_status: DeliveryStatusType;
  when_ordered?: string;
  when_delivered?: string;
  expected_delivery_date?: string;
  automatic: number;
  automatic_id?: number;
  oil_id?: number;
  supplier_price?: number;
  customer_price?: number;
  customer_temperature?: number;
  dispatcher_notes?: string;
  prime: number;
  same_day: number;
  emergency: number;
  pricing_tier_same_day?: number;
  pricing_tier_prime?: number;
  pricing_tier_emergency?: number;
  payment_type: number;
  payment_card_id?: number;
  cash_recieved?: number;
  driver_employee_id?: number;
  driver_first_name?: string;
  driver_last_name?: string;
  pre_charge_amount?: number;
  total_price: number;
  final_price: number;
  check_number?: string;
  promo_id?: number;
  promo_money_discount?: number;
}

export interface DeliveryNote extends BaseEntity {
  delivery_id: number;
  driver_comments?: string;
  time_added: string;
  driver_id: number;
  driver_name: string;
}

// Payment interfaces
export interface PaymentTransaction extends BaseEntity {
  customer_id: number;
  delivery_id?: number;
  service_id?: number;
  amount: number;
  payment_status: PaymentStatusType;
  transaction_id?: string;
  card_id?: number;
  transaction_type?: TransactionStatusType;
  created_at?: string;
  updated_at?: string;
}

export interface CreditCard extends BaseEntity {
  user_id: number;
  date_added?: string;
  card_number: string;
  last_four_digits: number;
  name_on_card: string;
  expiration_month: string;
  expiration_year: string;
  type_of_card: string;
  security_number?: string;
  accepted_or_declined?: number;
  main_card: boolean;
  zip_code?: string;
  auth_net_payment_profile_id?: string;
}

export interface AuthorizeTransaction extends BaseEntity {
  transaction_id: string;
  amount: number;
  status: TransactionStatusType;
  response_code?: string;
  auth_code?: string;
  created_at: string;
  auth_net_transaction_id?: string;
  customer_name?: string;
  preauthorize_amount: number | null;
  charge_amount: number | null;
  transaction_type?: number;
  delivery_id?: number;
  service_id?: number;
  auto_id?: number;
  customer_id?: number;
  rejection_reason?: string;
}

// Service interfaces
export interface ServiceCall extends BaseEntity {
  customer_id: number;
  customer_name?: string;
  customer_address?: string;
  customer_town?: string;
  customer_state?: string;
  customer_zip?: string;
  type_service_call: number;
  when_ordered?: string;
  scheduled_date: string;
  description: string;
  service_cost: string;
  payment_type?: number;
  payment_card_id?: number;
  payment_status?: number;
}

export interface ServicePart extends BaseEntity {
  service_call_id: number;
  part_name: string;
  part_number?: string;
  quantity: number;
  unit_cost: number;
  total_cost: number;
}

export interface ServicePlan extends BaseEntity {
  customer_id: number;
  customer_name: string;
  customer_address: string;
  customer_town: string;
  contract_plan: number;
  contract_years: number;
  contract_start_date: string;
}

// Employee interfaces
export interface Employee extends BaseEntity {
  employee_first_name: string;
  employee_last_name: string;
  employee_email?: string;
  employee_phone?: string;
  employee_role: string;
  is_active: boolean;
  hire_date?: string;
  admin_role: boolean;
  employee_type?: number;
  employee_town?: string;
  employee_phone_number?: string;
  user_id?: number;
}

export interface User {
  user_admin?: number;
  // Add other user properties as needed
}

// Auto delivery interfaces
export interface AutoDelivery extends BaseEntity {
  customer_id: number;
  customer_full_name: string;
  account_number: string;
  customer_town: string;
  customer_state: number;
  customer_zip: string;
  customer_address: string;
  last_fill?: string;
  last_updated?: string;
  estimated_gallons_left: number;
  estimated_gallons_left_prev_day: number;
  tank_height?: string;
  tank_size: number;
  house_factor: number;
  auto_status: AutoStatusType;
  days_since_last_fill: number;
  hot_water_summer: number;
  open_ticket_id?: number;
  confidence_score: number;
  k_factor_source: string;
  days_remaining: number;
  gallons_per_day: number;
}

// Promo interfaces
export interface Promo extends BaseEntity {
  promo_code: string;
  promo_name: string;
  discount_type: string;
  discount_value: number;
  is_active: boolean;
  start_date?: string;
  end_date?: string;
  usage_limit?: number;
  usage_count: number;
}

// Query/Lookup interfaces
export interface StateOption {
  value: number;
  text: string;
  abbreviation?: string;
}

export interface HomeTypeOption {
  value: number;
  text: string;
}

export interface PaymentTypeOption {
  id: number;
  name: string;
}

export interface OilPrice {
  id: number;
  supplier_name: string;
  price_per_gallon: number;
  effective_date: string;
}

// Search interfaces
export interface SearchResult {
  id: number;
  type: 'customer' | 'delivery' | 'service';
  title: string;
  subtitle?: string;
  data: any; // Keep as any for now since search results can be various types
}

// Stats interfaces
export interface DashboardStats {
  total_customers: number;
  active_deliveries: number;
  pending_payments: number;
  monthly_revenue: number;
  todays_deliveries: number;
}

export interface CompanyStats {
  total_revenue: number;
  total_profit: number;
  total_deliveries: number;
  total_service_calls: number;
  average_delivery_time: number;
}

// Request interfaces
export interface CreateCustomerRequest {
  customer_last_name: string;
  customer_first_name: string;
  customer_town: string;
  customer_state: number;
  customer_zip: string;
  customer_email?: string;
  customer_home_type: number;
  customer_phone_number?: string;
  customer_address: string;
  customer_apt?: string;
  customer_description?: string;
}

export interface UpdateCustomerRequest {
  customer_last_name?: string;
  customer_first_name?: string;
  customer_town?: string;
  customer_state?: number;
  customer_zip?: string;
  customer_email?: string;
  customer_home_type?: number;
  customer_phone_number?: string;
  customer_address?: string;
  customer_apt?: string;
  customer_automatic?: CustomerAutomaticStatus;
}

export interface CreateDeliveryRequest {
  customer_id: number;
  gallons_ordered: number;
  expected_delivery_date?: string;
  payment_type: number;
  payment_card_id?: number;
  promo_id?: number;
  dispatcher_notes?: string;
}

export interface UpdateDeliveryRequest {
  gallons_delivered?: number;
  delivery_status?: DeliveryStatusType;
  payment_type?: number;
  total_price?: number;
  final_price?: number;
  driver_employee_id?: number;
  dispatcher_notes?: string;
}

export interface CreateCardRequest {
  customer_id: number;
  card_number: string;
  expiration_month: number | string;
  expiration_year: number | string;
  security_number: string;
  name_on_card: string;
  type_of_card?: string;
  main_card?: boolean;
}

export interface PaymentRequest {
  customer_id: number;
  amount: number;
  card_id?: number;
  delivery_id?: number;
  service_id?: number;
}

// Calendar/Event interfaces
export interface CalendarEvent {
  id: string;
  title: string;
  start: string;
  end?: string;
  backgroundColor?: string;
  extendedProps?: {
    customer_id: number;
    delivery_id?: number;
    service_id?: number;
    type: 'delivery' | 'service' | 'maintenance';
    status: string;
  };
}

// Form interfaces
export interface LoginForm {
  username: string;
  password: string;
}

export interface RegisterForm {
  username: string;
  email: string;
  password: string;
  confirm_password: string;
}

export interface ChangePasswordForm {
  current_password: string;
  new_password: string;
  confirm_password: string;
}

// ============================================
// Payment Request Interfaces (Authorize.net)
// ============================================

export interface TokenizeCardRequest {
  card_number: string;
  expiration_date: string; // YYYY-MM format
  cvv: string;
  main_card?: boolean;
}

export interface UpdateTokenizedCardRequest {
  card_number?: string;
  expiration_date?: string; // YYYY-MM format
  cvv?: string;
  main_card?: boolean;
}

export interface ChargeSavedCardRequest {
  card_id: number;
  charge_amount: string;
  delivery_id?: number;
  service_id?: number | null;
}

export interface PreauthorizeSavedCardRequest {
  card_id: number;
  preauthorize_amount: string;
  delivery_id?: number;
  auto_id?: number;
}

export interface ChargeDirectRequest {
  card_number: string;
  expiration_date: string;
  cvv: string;
  charge_amount: string;
  preauthorize_amount?: string;
  transaction_type: number;
  delivery_id?: number;
  service_id?: number | null;
  card_id?: number;
}

export interface CaptureRequest {
  charge_amount: number;
  auth_net_transaction_id: string;
}

// ============================================
// API Response Interfaces
// ============================================

export interface AuthorizeNetTransactionResponse {
  id: number;
  auth_net_transaction_id: string;
  preauthorize_amount: number | null;
  charge_amount: number | null;
  status: number; // 0 = approved, 1 = declined
  transaction_type: number; // 0 = charge, 1 = auth, 2 = capture
  created_at: string;
  rejection_reason?: string;
  customer_id?: number;
  delivery_id?: number;
  service_id?: number;
  auto_id?: number;
}

export interface DeliveryOrderResponse {
  ok: boolean;
  delivery: Delivery;
  error?: string;
}

export interface DeliveryTotalResponse {
  ok: boolean;
  priceprime: number;
  pricesameday: number;
  priceemergency: number;
  total_amount: number;
  discount: number;
  total_amount_after_discount: number;
}

export interface OilPricingResponse {
  price_from_supplier: number;
  price_for_customer: number;
  price_for_employee: number;
  price_same_day: number;
  price_prime: number;
  price_emergency: number;
  date: string;
}

export interface WhoAmIResponse {
  ok: boolean;
  user: {
    user_id: number;
    user_admin?: number;
  };
}

export interface AuthorizeCheckResponse {
  profile_exists: boolean;
  has_payment_methods: boolean;
  missing_components: string[];
  valid_for_charging: boolean;
}

export interface CreateAuthorizeAccountResponse {
  success: boolean;
  profile_id?: string;
  message?: string;
  error_detail?: string;
  is_duplicate?: boolean;
}

export interface PromoResponse {
  id: number;
  name_of_promotion: string;
  description: string;
  money_off_delivery: number;
  text_on_ticket: string;
}

export interface CardsOnFileResponse {
  cards: number;
}

export interface PaymentCardResponse {
  userCard: CreditCard;
}

export interface UpdateStatusResponse {
  update: boolean;
}

// ============================================
// Component Local State Interfaces
// ============================================

export interface DeliveryFormData {
  id: number;
  customer_id: number;
  customer_name: string;
  customer_address: string;
  customer_town: string;
  customer_state: number;
  customer_zip: string;
  gallons_ordered: number;
  customer_asked_for_fill: number;
  gallons_delivered: number;
  customer_filled: number;
  delivery_status: number;
  when_ordered: string;
  when_delivered: string;
  expected_delivery_date: string;
  automatic: number;
  automatic_id?: number;
  oil_id: number;
  supplier_price: number;
  customer_price: number;
  customer_temperature: number;
  dispatcher_notes: string;
  prime: number;
  promo_id: number | null;
  emergency: number;
  same_day: number;
  pricing_tier_same_day?: number;
  pricing_tier_prime?: number;
  pricing_tier_emergency?: number;
  payment_type: number;
  payment_card_id: number;
  driver_employee_id: number;
  driver_first_name: string;
  driver_last_name: string;
  pre_charge_amount: number;
  total_price: number;
  final_price?: number;
  service_id?: number | null;
}

export interface CustomerFormData {
  id: number;
  user_id?: number;
  customer_first_name: string;
  customer_last_name: string;
  customer_town: string;
  customer_address: string;
  customer_state: number;
  customer_zip: string;
  customer_apt: string;
  customer_home_type: number;
  customer_phone_number: string;
  account_number: string;
  auth_net_profile_id?: string | null;
  customer_email?: string;
}

export interface CreditCardFormData {
  id: number;
  name_on_card: string;
  main_card: boolean;
  card_number: string;
  expiration_month: string;
  type_of_card: string;
  last_four_digits: string | number;
  expiration_year: string;
  security_number: string;
  date_added?: string;
  user_id?: number | string;
  accepted_or_declined?: number | string;
  auth_net_payment_profile_id?: string;
  zip_code?: string;
}

export interface PricingData {
  price_from_supplier: number;
  price_for_customer: number;
  price_for_employee: number;
  price_same_day: number;
  price_prime: number;
  price_emergency: number;
  date: string;
}

export interface PromoData {
  name_of_promotion: string;
  description: string;
  money_off_delivery: number;
  text_on_ticket: string;
}

export interface AutoTicketData {
  id: number;
  customer_id: number | string;
  account_number: string;
  customer_town: string;
  customer_state: number | string;
  customer_address: string;
  customer_zip: string;
  customer_full_name: string;
  oil_prices_id: number | string;
  fill_date: string;
  gallons_delivered: string;
  price_per_gallon: string;
  total_amount_customer: string;
  payment_type: number | string;
  payment_card_id: number | string;
  payment_status: number;
  open_ticket_id: number | null;
}

export interface AutoDeliveryData {
  id: number;
  customer_id: number;
  account_number: string;
  customer_town: string;
  customer_state: number;
  customer_address: string;
  customer_zip: string;
  customer_full_name: string;
  last_fill: string;
  days_since_last_fill: number;
  last_updated: string;
  estimated_gallons_left: number;
  estimated_gallons_left_prev_day: number;
  tank_height: string;
  tank_size: string | number;
  house_factor: number;
  auto_status: number;
  open_ticket_id: number | null;
  confidence_score: number;
  k_factor_source: string;
  days_remaining: number;
  gallons_per_day: number;
}

export interface CustomerDescriptionData {
  customer_id: number;
  account_number: string;
  company_id: number;
  fill_location: number;
  description: string;
}

// ============================================
// Axios Response Type Helper
// ============================================
export interface AxiosApiResponse<T> {
  data: T;
  status: number;
  statusText: string;
}

// ============================================
// API Response Wrapper Types
// ============================================
// Backend returns: { ok: true, <key>: <data> }
// These types match the actual API response structure

export interface CustomersResponse {
  ok: boolean;
  customers: Customer[];
}

export interface CustomerResponse {
  ok: boolean;
  customer: Customer;
  error?: string;
}

export interface CardsResponse {
  ok: boolean;
  cards: CreditCard[];
}

export interface CardResponse {
  ok: boolean;
  card: CreditCard;
  error?: string;
}

export interface DeliveriesResponse {
  ok: boolean;
  deliveries: Delivery[];
}

export interface DeliveryResponse {
  ok: boolean;
  delivery: Delivery;
  error?: string;
}

export interface TransactionsResponse {
  ok: boolean;
  transactions: PaymentTransaction[] | AuthorizeTransaction[];
}

export interface PromosResponse {
  ok: boolean;
  promos: Promo[];
}

export interface DriversResponse {
  ok: boolean;
  drivers: Employee[];
}

// Driver type alias for clarity
export type Driver = Employee;

// Utility types (legacy - use specific response types above for new code)
export type CustomerListResponse = CustomersResponse;
export type DeliveryListResponse = DeliveriesResponse;
export type TransactionListResponse = TransactionsResponse;
export type CardListResponse = CardsResponse;
export type ServiceListResponse = PaginatedResponse<ServiceCall>;
export type EmployeeListResponse = PaginatedResponse<Employee>;

export interface ServicesResponse {
  ok: boolean;
  services: ServiceCall[];
}

export interface ServiceResponse {
  ok: boolean;
  service: ServiceCall;
}

export interface CalendarEventsResponse {
  ok: boolean;
  events: CalendarEvent[];
}

// Theme interfaces
export interface ThemeOption {
  name: string;
  label: string;
  preview: string;  // Primary color for preview swatch
}

// Delivery Map interfaces
export interface DeliveryMapItem {
  id: number;
  street: string;
  town: string;
  state: string;
  zipcode: string | number;
  customerName: string;
  notes: string;
  latitude: string | null;
  longitude: string | null;
  gallonsOrdered: number;
  isFill: boolean;
  deliveryStatus: number;
  customerId: number;
}

export interface DeliveriesMapResponse {
  ok: boolean;
  deliveries: DeliveryMapItem[];
}

// Delivery History interfaces
export interface DeliveryHistoryItem {
  id: number;
  customerId: number;
  customerName: string;
  town: string;
  address: string;
  gallonsDelivered: number;
  prime: boolean;
  emergency: boolean;
  sameDay: boolean;
  deliveryStatus: number;
}

export interface DeliveryHistoryResponse {
  ok: boolean;
  deliveries: DeliveryHistoryItem[];
  totalGallons: number;
  totalDeliveries: number;
  primeCount: number;
  emergencyCount: number;
  sameDayCount: number;
}

// Admin Settings interfaces
export interface QuickCallEntry {
  name: string;
  phone: string;
}

export interface AdminSettings {
  id: number;
  updated_at: string | null;
  logo_base64: string | null;
  logo_mime_type: string | null;
  company_name: string;
  link_facebook: string | null;
  link_google: string | null;
  link_website: string | null;
  link_google_review: string | null;
  quick_calls: string | null;
  show_automatics: boolean;
  show_stats: boolean;
  show_service: boolean;
  show_ticker: boolean;
  default_theme: string;
}

export interface AdminSettingsResponse {
  ok: boolean;
  settings: AdminSettings;
}