import { prisma } from "@/module/_global";
import { funGetUserById } from "@/module/auth";
import _, { ceil } from "lodash";
import { NextResponse } from "next/server";
import moment from "moment";

export async function GET(request: Request) {
   try {
      const { searchParams } = new URL(request.url)
      const idGroup = searchParams.get("group")
      const division = searchParams.get("division")
      const date = searchParams.get("date")
      const dateAkhir = searchParams.get("date-end")
      const kat = searchParams.get("cat")
      const user = searchParams.get("user")
      let grup

      const userMobile = await funGetUserById({ id: String(user) })

      if (userMobile.id == "null" || userMobile.id == undefined || userMobile.id == "") {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 200 });
      }


      if (idGroup == "null" || idGroup == undefined || idGroup == "" || idGroup == null || idGroup == "undefined") {
         grup = userMobile.idGroup
      } else {
         grup = idGroup
      }

      if (kat == "table-progress") {
         let kondisiProgress
         if (division == "undefined") {
            kondisiProgress = {
               isActive: true,
               Division: {
                  idGroup: String(grup)
               },
               DivisionProjectTask: {
                  some: {
                     dateStart: {
                        gte: moment(String(date)).startOf('day').toDate()
                     },
                     dateEnd: {
                        lte: moment(String(dateAkhir)).endOf('day').toDate()
                     }
                  }
               }
            }

         } else {
            kondisiProgress = {
               isActive: true,
               idDivision: String(division),
               DivisionProjectTask: {
                  some: {
                     dateStart: {
                        gte: moment(String(date)).startOf('day').toDate()
                     },
                     dateEnd: {
                        lte: moment(String(dateAkhir)).endOf('day').toDate()
                     }
                  }
               }
            }
         }


         const data = await prisma.divisionProject.findMany({
            where: kondisiProgress,
            select: {
               id: true,
               title: true,
               status: true,
               DivisionProjectTask: {
                  where: {
                     isActive: true
                  },
                  select: {
                     title: true,
                     status: true
                  }
               }
            }
         })

         const dataFix = data.map((v: any) => ({
            ..._.omit(v, ["DivisionProjectTask"]),
            progress: ceil((v.DivisionProjectTask.filter((i: any) => i.status == 1).length * 100) / v.DivisionProjectTask.length),
         }))

         return NextResponse.json({ success: true, message: "Berhasil mendapatkan data", data: dataFix }, { status: 200 });

      } else {
         // CHART PROGRESS
         let kondisiProgress
         if (division == "undefined") {
            kondisiProgress = {
               isActive: true,
               Division: {
                  idGroup: String(grup)
               },
               DivisionProjectTask: {
                  some: {
                     dateStart: {
                        gte: moment(String(date)).startOf('day').toDate()
                     },
                     dateEnd: {
                        lte: moment(String(dateAkhir)).endOf('day').toDate()
                     }
                  }
               }
            }
         } else {
            kondisiProgress = {
               isActive: true,
               idDivision: String(division),
               DivisionProjectTask: {
                  some: {
                     dateStart: {
                        gte: moment(String(date)).startOf('day').toDate()
                     },
                     dateEnd: {
                        lte: moment(String(dateAkhir)).endOf('day').toDate()
                     }
                  }
               }
            }
         }

         const data = await prisma.divisionProject.groupBy({
            where: kondisiProgress,
            by: ["status"],
            _count: true
         })

         const dataStatus = [{ name: 'Segera', status: 0, color: '#177AD5' }, { name: 'Dikerjakan', status: 1, color: '#fac858' }, { name: 'Selesai', status: 2, color: '#92cc76' }, { name: 'Dibatalkan', status: 3, color: '#ED6665' }]
         const hasilProgres: any[] = []
         let input
         for (let index = 0; index < dataStatus.length; index++) {
            const cek = data.some((i: any) => i.status == dataStatus[index].status)
            if (cek) {
               const find = ((Number(data.find((i: any) => i.status == dataStatus[index].status)?._count) * 100) / data.reduce((n, { _count }) => n + _count, 0)).toFixed(2)
               const fix = find != "100.00" ? find.substr(-2, 2) == "00" ? find.substr(0, 2) : find : "100"
               input = {
                  tooltipText: dataStatus[index].name,
                  value: Number(fix),
                  text:`${fix}%`,
                  color:dataStatus[index].color
               }
            } else {
               input = {
                  tooltipText: dataStatus[index].name,
                  value: 0,
                  text:`0%`,
                  color:dataStatus[index].color
               }
            }
            hasilProgres.push(input)
         }




         // CHART DOKUMEN
         let kondisi
         if (division == "undefined") {
            kondisi = {
               isActive: true,
               category: 'FILE',
               Division: {
                  idGroup: String(grup)
               },
               createdAt: {
                  gte: moment(String(date)).startOf('day').toDate(),
                  lte: moment(String(dateAkhir)).endOf('day').toDate()
               },
            }
         } else {
            kondisi = {
               isActive: true,
               category: 'FILE',
               idDivision: String(division),
               createdAt: {
                  gte: moment(String(date)).startOf('day').toDate(),
                  lte: moment(String(dateAkhir)).endOf('day').toDate()
               },
            }
         }

         const dataDokumen = await prisma.divisionDocumentFolderFile.findMany({
            where: kondisi,
         })

         const groupData = _.map(_.groupBy(dataDokumen, "extension"), (v: any) => ({
            file: v[0].extension,
            jumlah: v.length,
         }))

         const image = ['jpg', 'jpeg', 'png', 'heic']

         let hasilImage = {
            label: 'Gambar',
            value: 0
         }

         let hasilFile = {
            label: 'Dokumen',
            value: 0
         }

         groupData.map((v: any) => {
            if (image.some((i: any) => i == v.file)) {
               hasilImage = {
                  label: 'Gambar',
                  value: hasilImage.value + v.jumlah
               }
            } else {
               hasilFile = {
                  label: 'Dokumen',
                  value: hasilFile.value + v.jumlah
               }
            }
         })

         const hasilDokumen = [hasilImage, hasilFile]



         // CHART EVENT
         let kondisiEvent, kondisiSelesai, kondisiComingSoon
         if (division == "undefined") {
            // kondisiEvent = {
            //    isActive: true,
            //    Division: {
            //       idGroup: String(grup)
            //    },
            //    DivisionCalendarReminder: {
            //       some: {
            //          dateStart: {
            //             gte: new Date(String(date)),
            //             lte: new Date(String(dateAkhir))
            //          }
            //       }
            //    }
            // }

            kondisiSelesai = {
               isActive: true,
               Division: {
                  idGroup: String(grup)
               },
               DivisionCalendarReminder: {
                  some: {
                     dateStart: {
                        gte: moment(String(date)).startOf('day').toDate(),
                        lte: moment().toDate()
                     }
                  }
               }
            }

            kondisiComingSoon = {
               isActive: true,
               Division: {
                  idGroup: String(grup)
               },
               DivisionCalendarReminder: {
                  some: {
                     dateStart: {
                        gt: moment().toDate(),
                        lte: moment(String(dateAkhir)).endOf('day').toDate()
                     }
                  }
               }
            }
         } else {
            // kondisiEvent = {
            //    isActive: true,
            //    idDivision: String(division),
            //    DivisionCalendarReminder: {
            //       some: {
            //          dateStart: {
            //             gte: new Date(String(date)),
            //             lte: new Date(String(dateAkhir))
            //          }
            //       }
            //    }
            // }

            kondisiSelesai = {
               isActive: true,
               idDivision: String(division),
               DivisionCalendarReminder: {
                  some: {
                     dateStart: {
                        gte: moment(String(date)).startOf('day').toDate(),
                        lte: moment().toDate()
                     }
                  }
               }
            }

            kondisiComingSoon = {
               isActive: true,
               idDivision: String(division),
               DivisionCalendarReminder: {
                  some: {
                     dateStart: {
                        gt: moment().toDate(),
                        lte: moment(String(dateAkhir)).endOf('day').toDate()
                     }
                  }
               }
            }
         }

         const eventSelesai = await prisma.divisionCalendar.count({
            where: kondisiSelesai
         })

         const eventComingSoon = await prisma.divisionCalendar.count({
            where: kondisiComingSoon
         })

         const hasilEvent = [
            {
               label: 'Selesai',
               value: eventSelesai
            },
            {
               label: 'Akan Datang',
               value: eventComingSoon
            }
         ]

         // const dataEvent = await prisma.divisionCalendar.findMany({
         //    where: kondisiEvent,
         //    select: {
         //       id: true,
         //       idDivision: true,
         //       title: true,
         //       desc: true,
         //       status: true,
         //       timeStart: true,
         //       dateStart: true,
         //       timeEnd: true,
         //       dateEnd: true,
         //       createdAt: true,
         //       User: {
         //          select: {
         //             name: true
         //          }
         //       }
         //    },
         //    orderBy: {
         //       createdAt: 'desc'
         //    }
         // })

         // const hasilEvent = dataEvent.map((v: any) => ({
         //    ..._.omit(v, ["User"]),
         //    user_name: v.User.name,
         //    timeStart: moment.utc(v.timeStart).format('HH:mm'),
         //    timeEnd: moment.utc(v.timeEnd).format('HH:mm')
         // }))


         const allData = {
            progress: hasilProgres,
            dokumen: hasilDokumen,
            event: hasilEvent
         }

         return NextResponse.json({ success: true, message: "Berhasil mendapatkan data", data: allData }, { status: 200 });
      }


   }
   catch (error) {
      console.error(error);
      return NextResponse.json({ success: false, message: "Gagal mendapatkan data, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
   }
}