import { z } from 'zod';

// 1. Definimos el esquema de un item individual de la lista de productos
// Basado en los campos que usaste en ProductActivityList
const productItemSchema = z.object({
  description: z.string().optional().nullable(),
  dailyCount: z.coerce.string().or(z.number()).optional().nullable(),
  weeklyCount: z.coerce.string().or(z.number()).optional().nullable(),
  monthlyCount: z.coerce.string().or(z.number()).optional().nullable(),
});

const productionItemSchema = z.object({
  supplyType: z.string().optional().nullable(),
  quantity: z.coerce.string().or(z.number()).optional().nullable(),
  unit: z.string().min(1, { message: 'Unidad es requerida' }).nullable(),
});

const equipmentItemSchema = z.object({
  machine: z.string().nullable(),
  quantity: z.coerce.string().or(z.number()).optional().nullable(),
});

export const trainingSchema = z.object({
  //Datos de la visita
  id: z.number().optional(),
  coorFullName: z
    .string()
    .min(1, { message: 'Nombre del coordinador es requerido' }),
  coorPhone: z.string().refine((val) => /^(04|02)\d{9}$/.test(val), {
    message: 'El teléfono debe tener 11 dígitos y comenzar con 04 o 02',
  }),
  visitDate: z
    .string()
    .min(1, { message: 'Fecha y hora de visita es requerida' }),

  //Datos de la organización socioproductiva (OSP)
  ospType: z.string().min(1, { message: 'Tipo de OSP es requerido' }),
  ecoSector: z.string({ message: 'Sector Económico es requerido' }),
  productiveSector: z.string({ message: 'Sector Productivo es requerido' }),
  centralProductiveActivity: z.string({
    message: 'Actividad Central Productiva es requerido',
  }),
  mainProductiveActivity: z.string({
    message: 'Actividad Productiva Principal es requerida',
  }),
  productiveActivity: z.string({
    message: 'Actividad Productiva es requerida',
  }),
  productiveActivityOther: z.string().min(1, { message: 'Este campo es requerido' }).optional(),
  ospRif: z.string().optional().or(z.literal('')).nullable(),
  ospName: z.string().optional().or(z.literal('')).nullable(),
  companyConstitutionYear: z.coerce
    .number()
    .min(1900, { message: 'Año inválido' })
    .nullable(),
  currentStatus: z
    .string()
    .min(1, { message: 'Estatus actual es requerido' })
    .default('ACTIVA'),
  infrastructureMt2: z.string({ message: 'Infraestructura es requerida' }),
  hasTransport: z
    .preprocess(
      (val) => val === 'true' || val === true || val === 1 || val === '1',
      z.boolean(),
    )
    .optional()
    .nullable()
    .default(false),
  structureType: z.string({ message: 'Tipo de estructura es requerido' }),
  isOpenSpace: z
    .preprocess(
      (val) => val === 'true' || val === true || val === 1 || val === '1',
      z.boolean(),
    )
    .optional()
    .nullable()
    .default(false),
  paralysisReason: z.string().optional().nullable(),

  //Datos del Equipamiento
  equipmentList: z.array(equipmentItemSchema).optional().default([]),

  //Datos de Producción
  productionList: z.array(productionItemSchema).optional().default([]),

  // Datos de Actividad Productiva
  productList: z.array(productItemSchema).optional().default([]),

  // Distribución y Exportación
  internalDistributionZone: z
    .string()
    .min(1, { message: 'Zona de distribución es requerida' }),
  isExporting: z
    .preprocess(
      (val) => val === 'true' || val === true || val === 1 || val === '1',
      z.boolean(),
    )
    .optional()
    .default(false),
  externalCountry: z.string().optional().nullable(),
  externalCity: z.string().optional().nullable(),
  externalDescription: z.string().optional().nullable(),
  externalQuantity: z.coerce.string().or(z.number()).optional().nullable(),
  externalUnit: z.string().optional().nullable(),

  // Mano de obra
  womenCount: z.coerce
    .number()
    .min(0, { message: 'Cantidad de mujeres es requerida' }),
  menCount: z.coerce
    .number()
    .min(0, { message: 'Cantidad de hombres es requerida' }),

  //Detalles de la ubicación
  ospAddress: z
    .string()
    .min(1, { message: 'Dirección de la OSP es requerida' }),
  ospGoogleMapsLink: z.string().optional().or(z.literal('')).nullable(),
  communeName: z
    .string()
    .min(1, { message: 'Nombre de la comuna es requerida' }),
  siturCodeCommune: z
    .string()
    .min(1, { message: 'Código SITUR de la comuna es requerida' }),
  communeRif: z.string().min(1, { message: 'Rif de la comuna es requerida' }),
  communeSpokespersonName: z
    .string()
    .min(1, { message: 'Nombre del vocero de la comuna es requerido' }),
  communeSpokespersonPhone: z
    .string()
    .optional()
    .or(z.literal(''))
    .refine((val) => !val || /^(04|02)\d{9}$/.test(val), {
      message: 'El teléfono debe tener 11 dígitos y comenzar con 04 o 02',
    }),
  communeEmail: z
    .string()
    .email({ message: 'Correo electrónico de la Comuna inválido' })
    .optional()
    .or(z.literal(''))
    .nullable(),
  communalCouncil: z
    .string()
    .min(1, { message: 'Consejo Comunal es requerido' }),
  siturCodeCommunalCouncil: z
    .string()
    .min(1, { message: 'Código SITUR del Consejo Comunal es requerido' }),
  communalCouncilRif: z
    .string()
    .min(1, { message: 'Rif del Consejo Comunal es requerido' }),
  communalCouncilSpokespersonName: z
    .string()
    .min(1, { message: 'Nombre del vocero es requerido' }),
  communalCouncilSpokespersonPhone: z
    .string()
    .optional()
    .or(z.literal(''))
    .refine((val) => !val || /^(04|02)\d{9}$/.test(val), {
      message: 'El teléfono debe tener 11 dígitos y comenzar con 04 o 02',
    }),
  communalCouncilEmail: z
    .string()
    .email({ message: 'Correo electrónico del Consejo Comunal inválido' })
    .optional()
    .or(z.literal(''))
    .nullable(),

  //Datos del Responsable OSP
  ospResponsibleCedula: z
    .string()
    .min(1, { message: 'Cédula del responsable es requerida' }),
  ospResponsibleFullname: z
    .string()
    .min(1, { message: 'Nombre del responsable es requerido' }),
  ospResponsibleRif: z.string().optional().nullable(),
  civilState: z.string().optional().nullable(),
  ospResponsiblePhone: z
    .string()
    .min(1, { message: 'Teléfono del responsable es requerido' })
    .regex(/^(04|02)\d{9}$/, {
      message: 'El teléfono debe tener 11 dígitos y comenzar con 04 o 02',
    }),
  ospResponsibleEmail: z
    .string()
    .email({ message: 'Correo electrónico inválido' })
    .optional()
    .or(z.literal(''))
    .nullable(),

  familyBurden: z.coerce.number().optional(),
  numberOfChildren: z.coerce.number().optional(),

  //Datos adicionales
  generalObservations: z.string().optional().nullable(),

  //IMAGENES
  files: z.any().optional(),

  //no se envia la backend al crear ni editar el formulario
  state: z.number({ message: 'El estado es requerido' }).nullable(),
  municipality: z.number({ message: 'Municipio es requerido' }).nullable(),
  parish: z.number({ message: 'Parroquia es requerido' }).nullable(),
  coorState: z.number().optional().nullable(),
  coorMunicipality: z.number().optional().nullable(),
  coorParish: z.number().optional().nullable(),
  photo1: z.string().optional().nullable(),
  photo2: z.string().optional().nullable(),
  photo3: z.string().optional().nullable(),
  createdBy: z.number().optional().nullable(),
  updatedBy: z.number().optional().nullable(),
  created_at: z.string().optional().nullable(),
  updated_at: z.string().optional().nullable(),
});

export type TrainingSchema = z.infer<typeof trainingSchema>;

export const getTrainingSchema = z.object({
  //Datos de la visita
  id: z.number().optional(),
  coorFullName: z.string(),
  coorPhone: z.string(),
  visitDate: z.string(),
  //Datos de la organización socioproductiva (OSP)
  ospType: z.string(),
  ecoSector: z.string(),
  productiveSector: z.string(),
  centralProductiveActivity: z.string(),
  mainProductiveActivity: z.string(),
  productiveActivity: z.string(),
  productiveActivityOther: z.string(),
  ospRif: z.string().optional().or(z.literal('')).nullable(),
  ospName: z.string().optional().or(z.literal('')).nullable(),
  companyConstitutionYear: z.coerce.number(),
  currentStatus: z.string(),
  infrastructureMt2: z.string(),
  hasTransport: z
    .preprocess(
      (val) => val === 'true' || val === true || val === 1 || val === '1',
      z.boolean(),
    )
    .optional()
    .nullable()
    .default(false),
  structureType: z.string(),
  isOpenSpace: z
    .preprocess(
      (val) => val === 'true' || val === true || val === 1 || val === '1',
      z.boolean(),
    )
    .optional()
    .nullable()
    .default(false),
  paralysisReason: z.string().optional().nullable(),
  //Datos del Equipamiento
  equipmentList: z.array(equipmentItemSchema).optional().default([]),
  //Datos de Producción
  productionList: z.array(productionItemSchema).optional().default([]),
  // Datos de Actividad Productiva
  productList: z.array(productItemSchema).optional().default([]),
  // Distribución y Exportación
  internalDistributionZone: z.string(),
  isExporting: z
    .preprocess(
      (val) => val === 'true' || val === true || val === 1 || val === '1',
      z.boolean(),
    )
    .optional()
    .default(false),
  externalCountry: z.string().optional().nullable(),
  externalCity: z.string().optional().nullable(),
  externalDescription: z.string().optional().nullable(),
  externalQuantity: z.coerce.string().or(z.number()).optional().nullable(),
  externalUnit: z.string().optional().nullable(),
  // Mano de obra
  womenCount: z.coerce.number(),
  menCount: z.coerce.number(),
  //Detalles de la ubicación
  ospAddress: z.string(),
  ospGoogleMapsLink: z.string().optional().or(z.literal('')).nullable(),
  communeName: z.string(),
  siturCodeCommune: z.string(),
  communeRif: z.string().or(z.literal('')).nullable(),
  communeSpokespersonName: z.string().or(z.literal('')).nullable(),
  communeSpokespersonPhone: z.string(),
  communeEmail: z.string().optional().or(z.literal('')).nullable(),
  communalCouncil: z.string(),
  siturCodeCommunalCouncil: z.string(),
  communalCouncilRif: z.string().optional(),
  communalCouncilSpokespersonName: z.string(),
  communalCouncilSpokespersonPhone: z.string(),
  communalCouncilEmail: z.string(),
  //Datos del Responsable OSP
  ospResponsibleCedula: z.string(),
  ospResponsibleFullname: z.string(),
  ospResponsibleRif: z.string().optional().nullable(),
  civilState: z.string().optional().nullable(),
  ospResponsiblePhone: z.string(),
  ospResponsibleEmail: z.string(),
  familyBurden: z.coerce.number().optional(),
  numberOfChildren: z.coerce.number().optional(),
  //Datos adicionales
  generalObservations: z.string().optional().nullable(),
  //no se envia la backend al crear ni editar el formulario
  state: z.number().nullable(),
  municipality: z.number().nullable(),
  parish: z.number().nullable(),
  coorState: z.number().optional().nullable(),
  coorMunicipality: z.number().optional().nullable(),
  coorParish: z.number().optional().nullable(),
  photo1: z.string().optional().nullable(),
  photo2: z.string().optional().nullable(),
  photo3: z.string().optional().nullable(),
  createdBy: z.number().optional().nullable(),
  updatedBy: z.number().optional().nullable(),
  created_at: z.string().optional().nullable(),
  updated_at: z.string().optional().nullable(),
});

export const trainingApiResponseSchema = z.object({
  message: z.string(),
  data: z.array(getTrainingSchema),
  meta: z.object({
    page: z.number(),
    limit: z.number(),
    totalCount: z.number(),
    totalPages: z.number(),
    hasNextPage: z.boolean(),
    hasPreviousPage: z.boolean(),
    nextPage: z.number().nullable(),
    previousPage: z.number().nullable(),
  }),
});

export const TrainingMutate = z.object({
  message: z.string(),
  data: trainingSchema,
});
