export default function useFeedback() {
  class MFeedback implements TFeedback {
    _id?: string;
    description?: string;
    subject?: string;
    service?: string;
    provider?: string | null;
    location: string;
    status?: string;
    createdBy?: any;
    createdByName?: string;
    createdByEmail?: string;
    attachments?: TAttachment[];
    workOrders?: object[];
    workOrder?: Record<string, any>;
    organization: string;
    site: string;
    createdAt?: string | Date;
    updatedAt?: string | Date;
    app: string;
    assignee?: string;
    assigneeName?: string;
    assigneeInfo?: Record<string, any>;
    statusUpdates?: any[];
    attachedIR?: Array<Record<string, any>>;

    constructor(feedback: Partial<TFeedback> = {}) {
      this._id = feedback._id || "";
      this.description = feedback.description || "";
      this.subject = feedback.subject || "";
      this.service = feedback.service || "";
      this.status = feedback.status || "";
      this.createdBy = feedback.createdBy || {};
      this.provider = feedback.provider || null;
      this.location = feedback.location || "";
      this.attachments = feedback.attachments || [];
      this.workOrders = feedback.workOrders || [];
      this.workOrder = feedback.workOrder ?? {};
      this.organization = feedback.organization || "";
      this.site = feedback.site || "";
      this.createdAt = "";
      this.updatedAt = "";
      this.app = feedback.app || "";
      this.assignee = feedback.assignee || "";
      this.assigneeName = feedback.assigneeName || "";
      this.assigneeInfo = feedback.assigneeInfo ?? {};
      this.statusUpdates = feedback.statusUpdates ?? [];
      this.attachedIR = feedback.attachedIR ?? [];
    }
  }

  const feedback = useState("feedback", () => new MFeedback());
  const feedbacks = useState("feedbacks", (): TFeedback[] => []);
  const page = useState("page", () => 1);
  const pages = useState("pages", () => 0);
  const pageRange = useState("pageRange", () => "-- - -- of --");

  function setFeedback(data?: TFeedback) {
    feedback.value = data || new MFeedback();
  }

  const { currentUser } = useLocalAuth();

  async function getFeedbacks({
    page = 1,
    limit = 10,
    search = "",
    site = "",
    dateFrom = "",
    dateTo = "",
    date,
    status = "",
    provider = "",
    service = "",
    userId = "",
  }: {
    page?: number;
    limit?: number;
    search?: string;
    site?: string;
    dateFrom?: any;
    dateTo?: any;
    date?: any;
    status?: string;
    provider?: string | any;
    service?: string;
    userId?: string;
  } = {}) {
    try {
      return useNuxtApp().$api<Record<string, any>>("/api/feedbacks2", {
        method: "GET",
        query: {
          page,
          limit,
          search,
          site,
          dateFrom,
          dateTo,
          date,
          status,
          provider,
          service,
          ...(currentUser.value?.type != "site" && {
            userId,
          }),
        },
      });
    } catch (err) {
      console.error("Error fetching feedbacks:", err);
    }
  }

  function getFeedbackById(id: string) {
    return useNuxtApp().$api<TFeedback>(`/api/feedbacks2/${id}`, {
      method: "GET",
    });
  }

  function createFeedback(payload: TFeedback) {
    return useNuxtApp().$api<Record<string, any>>("/api/feedbacks2", {
      method: "POST",
      body: payload,
    });
  }

  function updateFeedback(id: string, payload: TFeedbackUpdate) {
    return useNuxtApp().$api<Record<string, any>>(`/api/feedbacks2/${id}`, {
      method: "PUT",
      body: payload,
    });
  }

  // function deleteFeedback(id: string) {
  //   return useNuxtApp().$api<Record<string, any>>(
  //     `/api/feedbacks/deleted/feedback/${id}`,
  //     {
  //       method: "PUT",
  //       // query: { id },
  //     }
  //   );
  // }

  function updateFeedbackServiceProvider(id: string, serviceProvider: string) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/feedbacks2/${id}/service-provider`,
      {
        method: "PATCH",
        body: {
          serviceProvider,
        },
      }
    );
  }

  function updateStatusComplete(id: string, payload: TFeedbackStatusComplete) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/feedbacks2/${id}/status/complete`,
      {
        method: "PUT",
        body: payload,
      }
    );
  }

  function addFeedBackWorkOrder(payload: any) {
    return useNuxtApp().$api<Record<string, any>>(
      "/api/feedbacks2/create-work-order",
      {
        method: "POST",
        body: payload,
      }
    );
  }

  function updateStatusFeedback(payload: any) {
    return useNuxtApp().$api<Record<string, any>>(
      "/api/feedbacks2/status-update",
      {
        method: "POST",
        body: payload,
      }
    );
  }

  function deleteFeedback(id: string) {
    return useNuxtApp().$api<Record<string, any>>(`/api/feedbacks/${id}`, {
      method: "DELETE",
    });
  }

  return {
    feedbacks,
    setFeedback,
    feedback,
    page,
    pages,
    pageRange,
    getFeedbacks,
    getFeedbackById,
    createFeedback,
    updateFeedback,
    deleteFeedback,
    updateFeedbackServiceProvider,
    updateStatusComplete,
    addFeedBackWorkOrder,
    updateStatusFeedback,
  };
}
