import * as Yup from 'yup';
import { Expense } from '@/types/api/expense';
import { formatDate } from '@/lib/helper';
import { S3_PUBLIC_BASE_URL } from '@/config/constant';

type ExpenseRealizationFormSchemaType = {
  category?: {
    value: 'BOP' | 'NON-BOP';
    label: 'BOP' | 'NON-BOP';
  };
  location?: {
    value: number;
    label: string;
  };
  realization_date?: string;
  kandangs?: { id?: number; name?: string }[];
  supplier?: {
    value: number;
    label: string;
  };
  existing_documents?: { name: string; url: string }[];
  documents?: File[];
  realizations: {
    kandang_id?: number;
    cost_items: {
      nonstock?: {
        value: number;
        label: string;
      };
      quantity?: number;
      price?: number;
      notes?: string;
    }[];
  }[];
};

export const ExpenseRealizationFormSchema: Yup.ObjectSchema<ExpenseRealizationFormSchemaType> =
  Yup.object({
    category: Yup.object({
      value: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
      label: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
    }).required('Kategori wajib diisi!'),

    location: Yup.object({
      value: Yup.number().min(1).required(),
      label: Yup.string().required(),
    }).required('Lokasi wajib diisi!'),

    realization_date: Yup.string().required('Tanggal transaksi wajib diisi!'),
    kandangs: Yup.array()
      .of(
        Yup.object({
          id: Yup.number().optional(),
          name: Yup.string().optional(),
        })
      )
      .optional(),

    supplier: Yup.object({
      value: Yup.number().min(1).required(),
      label: Yup.string().required(),
    }).required('Vendor wajib diisi!'),

    existing_documents: Yup.array().of(
      Yup.object({
        name: Yup.string().required(),
        url: Yup.string().required(),
      })
    ),

    documents: Yup.array().of(Yup.mixed<File>().required()).optional(),

    realizations: Yup.array()
      .of(
        Yup.object({
          kandang_id: Yup.number()
            .optional()
            .test('valid-kandang-id', 'Wajib memilih kandang!', (value) => {
              if (value === undefined || value === null || value === 0) {
                return true;
              }
              return value >= 1;
            }),
          cost_items: Yup.array()
            .of(
              Yup.object({
                nonstock: Yup.object({
                  value: Yup.number().min(1).required(),
                  label: Yup.string().required(),
                }).required('Nonstock wajib diisi!'),
                quantity: Yup.number().required('Total kuantitas wajib diisi!'),
                price: Yup.number().required('Harga satuan wajib diisi!'),
                notes: Yup.string(),
              })
            )
            .min(1, 'Harus memiliki setidaknya 1 biaya!')
            .required('Biaya wajib diisi!'),
        })
      )
      .min(1, 'Biaya wajib diisi!')
      .required('Biaya wajib diisi!'),
  });

export const UpdateExpenseRealizationFormSchema = ExpenseRealizationFormSchema;

export const UploadRealizationDocumentsFormSchema = Yup.object({
  realization_documents: Yup.array()
    .of(Yup.mixed<File>().required())
    .required(),
});

export type ExpenseRealizationFormValues = Yup.InferType<
  typeof ExpenseRealizationFormSchema
>;

export type UploadRealizationDocumentsFormValues = Yup.InferType<
  typeof UploadRealizationDocumentsFormSchema
>;

export const getExpenseRealizationFormInitialValues = (
  initialValues?: Expense
): ExpenseRealizationFormValues => {
  return {
    category: initialValues?.category
      ? {
          value: initialValues.category,
          label: initialValues.category,
        }
      : undefined,
    location: initialValues?.location
      ? {
          value: initialValues.location.id,
          label: initialValues.location.name,
        }
      : undefined,
    realization_date: initialValues?.realization_date
      ? formatDate(initialValues?.realization_date, 'YYYY-MM-DD')
      : undefined,
    kandangs: initialValues?.kandangs.map((kandang) => ({
      id: kandang.id,
      name: kandang.name,
    })),
    supplier: initialValues?.supplier
      ? {
          value: initialValues.supplier.id,
          label: initialValues.supplier.name,
        }
      : undefined,
    existing_documents: initialValues?.realization_docs?.map((doc) => {
      const path = doc.path.startsWith('/') ? doc.path.slice(1) : doc.path;
      return {
        name: doc.path,
        url: `${S3_PUBLIC_BASE_URL}/${path}`,
      };
    }),
    documents: [],
    realizations: initialValues?.kandangs
      ? initialValues.kandangs.map((kandangExpense) => {
          const costItemsInitialValue = kandangExpense.realisasi
            ? kandangExpense.realisasi.map((realisasiItem, realisasiIdx) => {
                return {
                  nonstock: {
                    value: kandangExpense.pengajuans?.[realisasiIdx]
                      .id as number,
                    label: realisasiItem.nonstock.name,
                  },
                  quantity: realisasiItem.qty,
                  price: realisasiItem.price,
                  notes: realisasiItem.notes,
                };
              })
            : kandangExpense.pengajuans
              ? kandangExpense.pengajuans.map((expenseItem) => ({
                  nonstock: {
                    value: expenseItem.id,
                    label: expenseItem.nonstock.name,
                  },
                  quantity: expenseItem.qty,
                  price: expenseItem.price,
                  notes: expenseItem.notes,
                }))
              : [];

          return {
            kandang_id: kandangExpense.id,
            cost_items: costItemsInitialValue,
          };
        })
      : [],
  };
};
