import * as Yup from 'yup';
import { buildFormData } from '../../api/helper/buildFormData';
import { objectToKeyValueArray } from '../../utils/ConvertObjToArr';

interface Param {
  key: string;
  value: string;
}
interface Category {
  id?: number | null;
  name: string | null;
}

interface Collection {
  name: string;
  collectionParam: {
    key: string;
  };
}

interface Attachment {
  id: number | null;
  // type: string;
  attachment: string;
}


interface FormUtilCommon {
  name: string;
  description: string;
  model: string;
  file?: string;
  category?: Category;
  params?: Param[];
  collections?: Collection[];
  attachments?: Attachment[]; // Add attachments here
}
interface ObjectToEdit extends FormUtilCommon {
  id?: number | null;
}

export interface InitialValues extends ObjectToEdit {

}

interface ValidateSchema extends FormUtilCommon {}

export const getInitialValues = (objectToEdit: ObjectToEdit | null = null): any => {
  
  const params = objectToEdit?.params ? objectToKeyValueArray(objectToEdit.params) : [{ key: '', value: '' }];
  const collections = objectToEdit?.collections || [];
  const attachments = objectToEdit?.attachments ? objectToEdit.attachments.map(attachment  =>  attachment.attachment  ?? []):[]

  return {
    id: objectToEdit?.id ?? null,
    category_id: objectToEdit?.category?.id ?? null,
    name: objectToEdit?.name ?? '',
    description: objectToEdit?.description ?? '',
    model: objectToEdit?.model ?? '',
    file: objectToEdit?.file ?? '',
    params: params,
    collections: collections,
    attachments: attachments, // Set the attachments here
  };
}

export const getValidationSchema = (editMode: boolean = false): Yup.Schema<ValidateSchema> => {
  return Yup.object().shape({
    name: Yup.string().required('required'),
    category_id: Yup.number().nullable().required('required'),
    description: Yup.string().required('required'),
    model: Yup.string().required('required'),
    file: Yup.string().required('required'),
    params: Yup.array().of(
      Yup.object().shape({
        key: Yup.string().required('Key is required'),
        value: Yup.string().required('Value is required'),
      })
    ).default([]),
  });
};

export const getDataToSend = (values: any): any => {
  const data = { ...values };
  if(data?.id){
    data["_method"] = "PUT"
  }
  
  // Ensure params is an array
  if (!Array.isArray(data.params)) {
    data.params = [];
  }
  
  // if (data.attachments && Array.isArray(data.attachments)) {
  //   data.attachments = data.attachments.map(({att}:any  ) => att.attachment);
  // }

  // const formData = new FormData();
  // buildFormData(formData, data);
  // return formData;
  if(typeof data['file'] == 'string') delete data['file']
  // Return the data object directly
  return data;
};