import * as Yup from 'yup';
import { Uniformity } from '@/types/api/production/uniformity';

type UniformityFormSchemaType = {
  date: string;
  location?: {
    value: number;
    label: string;
  } | null;
  location_id: number;
  project_flock?: {
    value: number;
    label: string;
  } | null;
  project_flock_id: number;
  project_flock_kandang_id: number | null;
  kandang?: {
    value: number;
    label: string;
  } | null;
  kandang_id: number;
  document: File | undefined;
};

const FileSchema = Yup.mixed<File>()
  .test('documentSize', 'Ukuran file maksimal 5 MB', (value): boolean => {
    if (!value) return true;
    if (value instanceof File) return value.size <= 5 * 1024 * 1024;
    return false;
  })
  .test('documentType', 'Format file harus Excel', (value): boolean => {
    if (!value) return true;
    if (value instanceof File) {
      const allowedTypes = [
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'text/csv',
      ];
      return allowedTypes.includes(value.type);
    }
    return false;
  });

export const UniformityFormSchema: Yup.ObjectSchema<UniformityFormSchemaType> =
  Yup.object({
    date: Yup.string().required('Tanggal wajib diisi!'),
    location: Yup.object({
      value: Yup.number().min(1).required(),
      label: Yup.string().required(),
    }).nullable(),
    location_id: Yup.number()
      .min(1, 'Location wajib diisi!')
      .required('Location wajib diisi!')
      .typeError('Location wajib diisi!'),
    project_flock: Yup.object({
      value: Yup.number().min(1).required(),
      label: Yup.string().required(),
    }).nullable(),
    project_flock_id: Yup.number()
      .min(1, 'Project flock wajib diisi!')
      .required('Project flock wajib diisi!')
      .typeError('Project flock wajib diisi!'),
    project_flock_kandang_id: Yup.number().optional().nullable().default(null),
    kandang: Yup.object({
      value: Yup.number().min(1).required(),
      label: Yup.string().required(),
    }).nullable(),
    kandang_id: Yup.number()
      .min(1, 'Kandang wajib diisi!')
      .required('Kandang wajib diisi!')
      .typeError('Kandang wajib diisi!'),
    document: FileSchema.required('File wajib diisi!'),
  });

export type UniformityFormValues = Yup.InferType<typeof UniformityFormSchema>;

export type UniformityFormData = {
  date: string;
  project_flock_kandang_id: number;
  document: File | null;
  document_name: string;
};

export const getUniformityFormInitialValues = (
  initialValues?: Partial<Uniformity>
): UniformityFormValues => {
  return {
    date: '',
    location: null,
    location_id: 0,
    project_flock: null,
    project_flock_id: 0,
    project_flock_kandang_id: initialValues?.project_flock_kandang_id ?? null,
    kandang: null,
    kandang_id: 0,
    document: undefined,
  };
};
