import { describe, expect, it } from 'vitest'
import { emptyBilingual } from '@/components/ui/BilingualInput'
import { getReservationWizardCopy } from './reservationWizard.copy'
import { createInitialDraft, reservationDraftReducer } from './reservationWizard.reducer'
import {
  validateCustomerStep,
  validateIdentityStep,
  validateLicenseStep,
  validatePaymentExtrasStep,
  validateRentalStep,
} from './reservationWizard.schemas'
import type { Customer } from './reservationWizard.types'

const copy = getReservationWizardCopy('en')

function validDraft() {
  return {
    ...createInitialDraft(),
    customer: {
      ...createInitialDraft().customer,
      mode: 'new' as const,
      firstName: { fr: 'Sara', ar: '' },
      lastName: { fr: 'Alaoui', ar: '' },
      email: 'sara@example.com',
      phone: '+212600000000',
    },
    identity: {
      dateOfBirth: '1990-01-01',
      nationality: 'Moroccan',
      fullAddress: '12 Main Street',
      identityDocumentNumber: 'AB123',
      internationalLicenseNumber: '',
    },
    license: {
      number: 'DL-123',
      country: 'MA',
      issuedAt: '2020-01-01',
      expiry: '2099-01-01',
      category: 'B',
      existingImageUrl: null,
      newImageFile: null,
    },
    rental: {
      vehicleId: 'vehicle_1',
      startDate: '2026-07-01T10:00',
      endDate: '2026-07-03T10:00',
      pickupLocation: '',
      returnLocation: '',
    },
    payment: {
      depositAmount: '0',
      paymentMode: 'CASH',
      notes: '',
    },
    additionalDrivers: [],
  }
}

describe('reservation wizard reducer', () => {
  it('hydrates existing customer identity and license data', () => {
    const customer: Customer = {
      id: 'customer_1',
      firstName: 'Sara',
      firstNameAr: 'سارة',
      lastName: 'Alaoui',
      lastNameAr: 'العلوي',
      email: 'sara@example.com',
      phone: '+212600000000',
      driverLicense: 'DL-1',
      dateOfBirth: '1990-01-01T00:00:00.000Z',
      nationality: 'Moroccan',
      address: { fullAddress: 'Rabat', identityDocumentNumber: 'AB123', internationalLicenseNumber: 'INT-1' },
      licenseIssuedAt: '2020-01-01T00:00:00.000Z',
      licenseExpiry: '2099-01-01T00:00:00.000Z',
      licenseCountry: 'MA',
      licenseCategory: 'B',
      licenseImageUrl: '/license.jpg',
    }

    const draft = reservationDraftReducer(createInitialDraft(), { type: 'selectExistingCustomer', customer })

    expect(draft.customer.selectedCustomerId).toBe('customer_1')
    expect(draft.customer.firstName).toEqual({ fr: 'Sara', ar: 'سارة' })
    expect(draft.identity.fullAddress).toBe('Rabat')
    expect(draft.license.number).toBe('DL-1')
    expect(draft.license.existingImageUrl).toBe('/license.jpg')
  })

  it('adds and removes additional drivers as an array', () => {
    const added = reservationDraftReducer(createInitialDraft(), { type: 'addAdditionalDriver' })
    expect(added.additionalDrivers).toHaveLength(1)

    const removed = reservationDraftReducer(added, { type: 'removeAdditionalDriver', id: added.additionalDrivers[0].id })
    expect(removed.additionalDrivers).toEqual([])
  })

  it('clears hydrated customer identity and license data when switching modes', () => {
    const customer: Customer = {
      id: 'customer_1',
      firstName: 'Sara',
      lastName: 'Alaoui',
      email: 'sara@example.com',
      driverLicense: 'DL-1',
      dateOfBirth: '1990-01-01T00:00:00.000Z',
      nationality: 'Moroccan',
      address: { fullAddress: 'Rabat', identityDocumentNumber: 'AB123' },
      licenseIssuedAt: '2020-01-01T00:00:00.000Z',
      licenseExpiry: '2099-01-01T00:00:00.000Z',
      licenseCountry: 'MA',
      licenseCategory: 'B',
    }

    const hydrated = reservationDraftReducer(createInitialDraft(), { type: 'selectExistingCustomer', customer })
    const switched = reservationDraftReducer(hydrated, { type: 'setCustomerMode', mode: 'new' })

    expect(switched.customer.mode).toBe('new')
    expect(switched.customer.selectedCustomerId).toBeNull()
    expect(switched.customer.email).toBe('')
    expect(switched.identity.fullAddress).toBe('')
    expect(switched.license.number).toBe('')
  })
})

describe('reservation wizard validation', () => {
  it('validates new customer required fields', () => {
    const draft = createInitialDraft()
    const errors = validateCustomerStep({ ...draft, customer: { ...draft.customer, mode: 'new', firstName: emptyBilingual() } }, copy)
    expect(errors['customer.firstName']).toBe(copy.validation.required)
    expect(errors['customer.email']).toBe(copy.validation.required)
  })

  it('validates date relationships in rental and license steps', () => {
    const draft = validDraft()
    expect(validateRentalStep({ ...draft, rental: { ...draft.rental, endDate: '2026-06-30T10:00' } }, copy)['rental.endDate']).toBe(copy.validation.endAfterStart)
    expect(validateLicenseStep({ ...draft, license: { ...draft.license, expiry: '2019-01-01' } }, copy)['license.expiry']).toBe(copy.validation.expiryFuture)
  })

  it('validates optional additional driver only when present', () => {
    const draft = {
      ...validDraft(),
      additionalDrivers: [{
        id: 'driver_1',
        firstName: emptyBilingual(),
        lastName: { fr: 'Driver', ar: '' },
        email: '',
        phone: '',
        driverLicense: '',
        licenseExpiry: '',
        licenseIssuedAt: '',
        dateOfBirth: '',
        nationality: emptyBilingual(),
      }],
    }

    const errors = validatePaymentExtrasStep(draft, copy)
    expect(errors['additionalDrivers.0.firstName']).toBe(copy.validation.required)
    expect(errors['additionalDrivers.0.driverLicense']).toBe(copy.validation.required)
  })

  it('accepts a complete valid draft', () => {
    expect(validateCustomerStep(validDraft(), copy)).toEqual({})
    expect(validateIdentityStep(validDraft(), copy)).toEqual({})
    expect(validateLicenseStep(validDraft(), copy)).toEqual({})
    expect(validateRentalStep(validDraft(), copy)).toEqual({})
    expect(validatePaymentExtrasStep(validDraft(), copy)).toEqual({})
  })
})
