export interface VesselData {
  imo: string;
  vesselName: string;
  type: string;
  length: number;
  width: number;
  estimatedEnginePower: number;
}

export interface CarbonCalculation {
  yearlyEmissions: number;
  offsetCost: number;
  recommendedProjects: Array<{
    id: string;
    name: string;
    description: string;
    costPerTon: number;
  }>;
}

export interface CarbonEstimate {
  fuelConsumption: number; // liters per year
  co2Emissions: number; // tons per year
}

export interface TripEstimate {
  distance: number; // nautical miles
  duration: number; // hours
  fuelConsumption: number; // liters
  co2Emissions: number; // tons
}

export interface Currency {
  code: string;
  symbol: string;
  rate: number; // Exchange rate relative to USD
}

export type CurrencyCode = 'USD' | 'EUR' | 'GBP' | 'CHF';

export interface Portfolio {
  id: number;
  name: string;
  description: string;
  projects: OffsetProject[];
  pricePerTon: number;
  currency: CurrencyCode;
}

export type CertificationStatus =
  | 'standard 2020'
  | 'standard 2023'
  | 'nonstandard'
  | 'in progress';

export interface OffsetProject {
  id: string;
  name: string;
  description: string;
  shortDescription: string;
  imageUrl: string;
  pricePerTon: number;
  percentage?: number;  // Project's contribution to portfolio
  certificationStatus?: CertificationStatus;  // Wren certification standard
  location: string;
  type: string;
  verificationStandard: string;
  impactMetrics: {
    co2Reduced: number;
    treesPlanted?: number;
    livelihoodsImproved?: number;
  };
}

export type OffsetOrderSource =
  | 'subscription'
  | 'flight'
  | 'gift'
  | 'custom-duration'
  | 'one-off'
  | 'referral-bonus'
  | 'annual-incentive'
  | 'public-api'
  | 'special-offer';

export interface OffsetOrder {
  id: string;
  amountCharged: number; // Amount in cents (amount_paid_by_customer from API)
  currency: CurrencyCode;
  tons: number;
  portfolio: Portfolio;
  status: 'pending' | 'completed' | 'failed';
  createdAt: string;
  dryRun: boolean;
  source?: OffsetOrderSource;  // Source of the payment
  note?: string;  // Optional note attached to the order
}

export type CalculatorType = 'trip' | 'annual' | 'mobile';

// Stripe Checkout Types
export interface CheckoutSession {
  sessionId: string;
  url: string;
  orderId: string;
}

export interface StoredOrder {
  id: string;
  stripeSessionId: string;
  stripePaymentIntent: string | null;
  wrenOrderId: string | null;
  customerEmail: string | null;
  tons: number;
  portfolioId: number;
  baseAmount: number; // in cents
  processingFee: number; // in cents
  totalAmount: number; // in cents
  currency: CurrencyCode;
  status: 'pending' | 'paid' | 'fulfilled' | 'failed';
  createdAt: string;
  updatedAt: string;
}

export interface OrderDetailsResponse {
  order: {
    id: string;
    tons: number;
    portfolioId: number;
    baseAmount: number;
    processingFee: number;
    totalAmount: number;
    currency: string;
    status: string;
    wrenOrderId: string | null;
    stripeSessionId: string;
    createdAt: string;
    portfolio?: Portfolio; // Portfolio data with projects for pie chart
  };
  session: {
    paymentStatus: string;
    customerEmail?: string;
  };
}

// NocoDB Order Record (Admin Portal)
export interface OrderRecord {
  // NocoDB metadata
  Id: number;
  CreatedAt: string;
  UpdatedAt: string;

  // Order identification
  orderId: string;
  status: 'pending' | 'paid' | 'fulfilled' | 'cancelled';
  source?: string; // 'web', 'mobile-app', 'manual', 'api'

  // Payment information
  stripeSessionId?: string; // Stripe Checkout Session ID
  stripePaymentIntent?: string; // Stripe Payment Intent ID (for refunds)
  baseAmount: string; // Pre-fee amount in cents (from Stripe metadata)
  processingFee: string; // Stripe processing fee in cents (from Stripe metadata)
  totalAmount: string; // Total charged amount in cents (baseAmount + processingFee)
  currency: string; // 'USD', 'EUR', 'GBP', 'CHF'
  amountUSD?: string; // Amount converted to USD for reporting
  paymentMethod?: string; // Payment method type (e.g., "card", "bank_transfer")

  // Carbon offset details
  co2Tons: string; // Tons of CO2 offset (from Stripe metadata.tons)
  portfolioId: string; // Wren portfolio ID (from Stripe metadata)
  portfolioName?: string; // Human-readable portfolio name
  wrenOrderId?: string; // Wren API order ID (populated after fulfillment)
  certificateUrl?: string; // URL to offset certificate
  fulfilledAt?: string; // Timestamp when order was fulfilled with Wren

  // Customer information
  customerName: string; // From Stripe customer_details.name (business_name or individual_name)
  customerEmail: string; // From Stripe customer_details.email
  customerPhone?: string; // From Stripe customer_details.phone (if phone collection enabled)
  businessName?: string; // From Stripe customer_details.business_name (B2B purchases)
  stripeCustomerId?: string; // From Stripe customer (reusable customer ID)
  taxIdType?: string; // From Stripe customer_details.tax_ids[0].type (e.g., "eu_vat", "us_ein")
  taxIdValue?: string; // From Stripe customer_details.tax_ids[0].value
  billingCity?: string; // From Stripe address.city
  billingCountry?: string; // From Stripe address.country
  billingLine1?: string; // From Stripe address.line1
  billingLine2?: string; // From Stripe address.line2
  billingPostalCode?: string; // From Stripe address.postal_code
  billingState?: string; // From Stripe address.state

  // Vessel information (optional - for yacht calculations)
  vesselName?: string; // Name of vessel
  imoNumber?: string; // IMO vessel identification number
  vesselType?: string; // Type of vessel (e.g., "Motor Yacht")
  vesselLength?: string; // Vessel length in meters

  // Trip details (optional - for trip-based calculations)
  departurePort?: string; // Departure port name
  arrivalPort?: string; // Arrival port name
  distance?: string; // Distance in nautical miles
  avgSpeed?: string; // Average speed in knots
  duration?: string; // Trip duration in hours
  enginePower?: string; // Engine power in horsepower

  // Admin notes
  notes?: string; // Internal admin notes
}

// QR Code System Types
export interface QRCalculatorData {
  // Calculator mode
  calculationType: 'fuel' | 'distance' | 'custom';

  // Distance-based inputs
  distance?: number;  // nautical miles
  speed?: number;     // knots
  fuelRate?: number;  // liters/hour

  // Fuel-based inputs
  fuelAmount?: number;  // liters or gallons
  fuelUnit?: 'liters' | 'gallons';

  // Custom amount
  customAmount?: number;  // tons of CO2

  // Vessel information (optional, for context)
  vessel?: {
    imo?: string;
    name?: string;
    type?: string;
    enginePower?: number;
  };

  // Metadata
  timestamp?: string;  // ISO timestamp for tracking
  source?: string;     // e.g., "marina-api", "broker-portal"
}

export interface QRGenerationResponse {
  qrCodeDataURL: string;  // PNG as data URL
  qrCodeSVG: string;      // SVG markup
  url: string;            // The full URL with encoded data
  expiresAt: string;      // ISO timestamp
}

export interface QRValidationResult {
  valid: boolean;
  error?: string;
  data?: QRCalculatorData;
}
