import { z } from 'zod';

import { damageEffectNameSchema } from '../../damage/Damage.schema';
import { powerUpNameSchema } from '../../powerUp/PowerUpAttributes.schema';
import { SCREEN_STATUS, SCREEN_VIEW } from './Screen.const';
import { KART_FINAL_STATE } from '../../kart/Kart.const';

export const screenStatusSchema = z.enum(SCREEN_STATUS);
export const screenViewSchema = z.enum(SCREEN_VIEW);
// KART_FINAL_STATE is { FINISHED: 'finished', ... } as const. z.nativeEnum works with it.
export const kartFinalStateSchema = z.enum(KART_FINAL_STATE);

export const screenModuleStatusSchema = z.object({
  latestView: screenViewSchema,
  screenStatus: screenStatusSchema,
});

export const screenCurrentTotalSchema = z.object({
  current: z.number().nullable(),
  total: z.number().nullable(),
});

export const screenGameTimeLeftSchema = z.object({
  minutes: z.number().nullable().optional(),
  seconds: z.number().nullable().optional(),
});

export const screenViewBaseConfigSchema = z.object({
  position: screenCurrentTotalSchema.optional(),
  coins: z.number().nullable().optional(),
  gameTimeLeft: screenGameTimeLeftSchema.optional(),
  powerUp: z
    .union([powerUpNameSchema, z.literal('Clear PowerUp')])
    .nullable()
    .optional(),
  powerUpAnimationTimeSeconds: z.number().nullable().optional(),
  damageEffect: z
    .union([damageEffectNameSchema, z.literal('Yellow Flag'), z.literal('Red Flag')])
    .nullable()
    .optional(),
  damageAnimationTimeSeconds: z
    .union([z.literal('Infinite'), z.number()])
    .nullable()
    .optional(),
});

export const screenRaceViewConfigSchema = screenViewBaseConfigSchema.extend({
  laps: screenCurrentTotalSchema.optional(),
});

export const screenBattleViewConfigSchema = screenViewBaseConfigSchema.extend({
  lives: screenCurrentTotalSchema.optional(),
});

export const countDownNextViewRaceSchema = z.object({
  nextView: z.literal('Race'),
  config: screenRaceViewConfigSchema,
});
export const countDownNextViewBattleSchema = z.object({
  nextView: z.literal('Battle'),
  config: screenBattleViewConfigSchema,
});

export const screenCountdownParamsSchema = z.union([countDownNextViewRaceSchema, countDownNextViewBattleSchema]);

export const updateRaceViewInputSchema = z.object({ view: z.literal('Race'), config: screenRaceViewConfigSchema });
export const updateBattleViewInputSchema = z.object({
  view: z.literal('Battle'),
  config: screenBattleViewConfigSchema,
});

export const screenUpdateGameViewInputSchema = z.union([updateRaceViewInputSchema, updateBattleViewInputSchema]);

export const screenFinishViewInputSchema = z.object({
  kartNumber: z.number().optional(),
  kartPosition: screenCurrentTotalSchema,
  coins: z.number(),
  finalState: kartFinalStateSchema.optional(),
});

export const screenHomeViewInputSchema = z.object({
  kartNumber: z.number().nullable().optional(),
});
