import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import HomeView from '@/views/HomeView.vue'
import LoginView from '@/views/LoginView.vue'
import NotFoundView from '@/views/NotFoundView.vue'
import WelcomePage from '@/components/Pages/Welcome.vue'
import EmptyPage from '@/components/Pages/EmptyPage.vue'
import qs from 'qs'
import {
  DaftarGangguanDKPL,
  DaftarGangguanMLD1K,
  DaftarGangguanResponseTime,
  DaftarGangguanRecoveryTime,
  DaftarGangguanSTIDP,
  DaftarGangguanBM,
  DaftarGangguanDMAPKT,
  RekapGangguanALL,
  RekapGangguanJenisGangguan,
  RekapGangguanJenisGangguanSE,
  RekapGangguanPerPosko,
  RekapGangguanPerRegu,
  RekapGangguanPerTanggal,
  RekapGangguanBerdasarMedia,
  RekapGangguanAlihPosko,
  RekapGangguanDMAPKT,
  RekapGangguanRatingPerPosko,
  RekapGangguanRatingPerRegu,
  RekapGangguanKTI,
  RekapGangguanCTTM
} from '@/components/Pages/Gangguan'
import {
  DaftarKeluhanDKUL,
  DaftarKeluhanPLD1K,
  DaftarKeluhanResponseTime,
  DaftarKeluhanRecoveryTime,
  DaftarKeluhanSTIDP,
  DaftarKeluhanBerdasarMedia,
  DaftarKeluhanSelesaiCC,
  RekapKeluhanALL,
  RekapKeluhanPerFungsiBidang,
  RekapKeluhanPerJenisKeluhan,
  RekapKeluhanPerKelompokKeluhan,
  RekapKeluhanPerTanggal,
  RekapKeluhanPerUnit,
  RekapKeluhanBerdasarMedia,
  RekapKeluhanRatingPerUnit
} from '@/components/Pages/Keluhan'
import {
  MonalisaGRDispatchingTimeGangguan,
  MonalisaLBKADDalamPelaporan,
  MonalisaLKPenurunanJumlahKomplain,
  MonalisaLKAgingComplaint,
  MonalisaLKEnergyNotSales,
  MonalisaLKKDADPelaporan,
  MonalisaGRRecoveryTimeGangguan,
  MonalisaGRResponseTimeGangguan,
  MonalisaGRJumlahDDRPTRCTGangguan,
  MonalisaGRGangguanPerJenisGangguan,
  MonalisaGRLaporUlang,
  MonalisaGRENSGangguan,
  MonalisaGRGangguanBelumSelesai,
  MonalisaGRJumlahKaliGangguan,
  MonalisaLBEnergyNotSales,
  MonalisaLBAgingComplaint,
  MonalisaLBPenurunanJumlahKomplain,
  MonalisaKRKeluhanBelumSelesai,
  MonalisaKRLaporUlangKeluhan,
  MonalisaKRGangguanPerJenisKeluhan,
  MonalisaKRJumlahDDRPTRCTKeluhan,
  MonalisaKRResponseTimeKeluhan,
  MonalisaKRRecoveryTimeKeluhan,
  MonalisaKRJumlahKaliKeluhan
} from '@/components/Pages/Monalisa'
import { LaporanCICO } from '@/components/Pages/Cico'
import { Anomali_LAPPGU, Anomali_LAPPKU, Anomali_LAPPGP } from '@/components/Pages/Anomali'
import { LaporanCttKwhPeriksa } from '@/components/Pages/Ctt'
import { MaterialDGMYG, MaterialRPM } from '@/components/Pages/Material'
import { TransaksiTable1 } from '@/components/Pages/Transaksi'
import { PencarianDataTable1 } from '@/components/Pages/PencarianData'

export const routes: RouteRecordRaw[] = [
  {
    path: '/home',
    name: 'Home',
    component: HomeView,
    children: [
      {
        path: '',
        name: 'Home Page',
        component: WelcomePage
      },
      {
        path: 'gangguan',
        name: 'Gangguan',
        children: [
          {
            path: 'daftar',
            name: 'Daftar',
            children: [
              {
                path: '1',
                name: 'Daftar Gangguan Dialihkan Ke Posko Lain',
                component: DaftarGangguanDKPL
              },
              {
                path: '2',
                name: 'Daftar Gangguan Melapor Lebih Dari 1 Kali',
                component: DaftarGangguanMLD1K
              },
              {
                path: '3',
                name: 'Daftar Gangguan Response Time',
                component: DaftarGangguanResponseTime
              },
              {
                path: '4',
                name: 'Daftar Gangguan Recovery Time',
                component: DaftarGangguanRecoveryTime
              },
              {
                path: '5',
                name: 'Daftar Gangguan Selesai Tanpa ID Pelanggan',
                component: DaftarGangguanSTIDP
              },
              {
                path: '6',
                name: 'Daftar Gangguan Berdasarkan Media',
                component: DaftarGangguanBM
              },
              {
                path: '7',
                name: 'Daftar Gangguan Diselesaikan Mobile APKT',
                component: DaftarGangguanDMAPKT
              },
              {
                path: ':pathMatch(.*)*',
                component: EmptyPage
              }
            ]
          },
          {
            path: 'rekapitulasi',
            name: 'Rekapitulasi',
            children: [
              {
                path: '1',
                name: 'Rekapitulasi Gangguan All',
                component: RekapGangguanALL
              },
              {
                path: '2',
                name: 'Rekapitulasi Gangguan/Jenis Gangguan',
                component: RekapGangguanJenisGangguan
              },
              {
                path: '3',
                name: 'Rekapitulasi Gangguan/Jenis Gangguan SE 004',
                component: RekapGangguanJenisGangguanSE
              },
              {
                path: '4',
                name: 'Rekapitulasi Gangguan Per Posko',
                component: RekapGangguanPerPosko
              },
              {
                path: '5',
                name: 'Rekapitulasi Gangguan Per Regu',
                component: RekapGangguanPerRegu
              },
              {
                path: '6',
                name: 'Rekapitulasi Gangguan Per Tanggal',
                component: RekapGangguanPerTanggal
              },
              {
                path: '7',
                name: 'Rekapitulasi Gangguan Berdasarkan Media',
                component: RekapGangguanBerdasarMedia
              },
              {
                path: '8',
                name: 'Rekapitulasi Gangguan Alih  Posko',
                component: RekapGangguanAlihPosko
              },
              {
                path: '9',
                name: 'Rekapitulasi Gangguan Diselesaikan Mobile APKT',
                component: RekapGangguanDMAPKT
              },
              {
                path: '10',
                name: 'Rekapitulasi Rating Per Posko',
                component: RekapGangguanRatingPerPosko
              },
              {
                path: '11',
                name: 'Rekapitulasi Rating Per Regu',
                component: RekapGangguanRatingPerRegu
              },
              {
                path: '12',
                name: 'Rekapitulasi Koreksi Transaksi Individual',
                component: RekapGangguanKTI
              },
              {
                path: '13',
                name: 'Rekapitulasi Cleansing Transaksi TM',
                component: RekapGangguanCTTM
              },
              {
                path: ':pathMatch(.*)*',
                component: EmptyPage
              }
            ]
          },
          {
            path: ':pathMatch(.*)*',
            component: EmptyPage
          }
        ]
      },
      {
        path: 'keluhan',
        name: 'Keluhan',
        children: [
          {
            path: 'daftar',
            name: 'Daftar',
            children: [
              {
                path: '1',
                name: 'Daftar Keluhan Dialihkan Ke Unit Lain',
                component: DaftarKeluhanDKUL
              },
              {
                path: '2',
                name: 'Daftar Keluhan Pelanggan Lebih Dari 1 Kali',
                component: DaftarKeluhanPLD1K
              },
              {
                path: '3',
                name: 'Daftar Keluhan Response Time',
                component: DaftarKeluhanResponseTime
              },
              {
                path: '4',
                name: 'Daftar Keluhan Recovery Time',
                component: DaftarKeluhanRecoveryTime
              },
              {
                path: '5',
                name: 'Daftar Keluhan Selesai Tanpa ID Pelanggan',
                component: DaftarKeluhanSTIDP
              },
              {
                path: '6',
                name: 'Daftar Keluhan Berdasarkan Media',
                component: DaftarKeluhanBerdasarMedia
              },
              {
                path: '7',
                name: 'Daftar Keluhan Selesai di Contact Center',
                component: DaftarKeluhanSelesaiCC
              },
              {
                path: ':pathMatch(.*)*',
                component: EmptyPage
              }
            ]
          },
          {
            path: 'rekapitulasi',
            name: 'Rekapitulasi',
            children: [
              {
                path: '1',
                name: 'Rekapitulasi Keluhan All',
                component: RekapKeluhanALL
              },
              {
                path: '2',
                name: 'Rekapitulasi Keluhan Per Fungsi Bidang',
                component: RekapKeluhanPerFungsiBidang
              },
              {
                path: '3',
                name: 'Rekapitulasi Keluhan Per Jenis Keluhan',
                component: RekapKeluhanPerJenisKeluhan
              },
              {
                path: '4',
                name: 'Rekapitulasi Keluhan Per Kelompok Keluhan',
                component: RekapKeluhanPerKelompokKeluhan
              },
              {
                path: '5',
                name: 'Rekapitulasi Keluhan Per Tanggal',
                component: RekapKeluhanPerTanggal
              },
              {
                path: '6',
                name: 'Rekapitulasi Keluhan Per Unit',
                component: RekapKeluhanPerUnit
              },
              {
                path: '7',
                name: 'Rekapitulasi Keluhan Berdasarkan Media',
                component: RekapKeluhanBerdasarMedia
              },
              {
                path: '8',
                name: 'Rekapitulasi Rating Per Unit',
                component: RekapKeluhanRatingPerUnit
              },
              {
                path: ':pathMatch(.*)*',
                component: EmptyPage
              }
            ]
          },
          {
            path: ':pathMatch(.*)*',
            component: EmptyPage
          }
        ]
      },
      {
        path: 'monalisa',
        name: 'Monalisa',
        children: [
          {
            path: 'gangguan',
            name: 'Gangguan',
            children: [
              {
                path: 'rekapitulasi',
                name: 'Rekapitulasi',
                children: [
                  {
                    path: '1',
                    name: 'Jumlah Kali Gangguan',
                    component: MonalisaGRJumlahKaliGangguan
                  },
                  {
                    path: '2',
                    name: 'Dispacthing Time (DT) Gangguan',
                    component: MonalisaGRDispatchingTimeGangguan
                  },
                  {
                    path: '3',
                    name: 'Recovery Time (RCT) Gangguan',
                    component: MonalisaGRRecoveryTimeGangguan
                  },
                  {
                    path: '4',
                    name: 'Response Time (RPT) Gangguan',
                    component: MonalisaGRResponseTimeGangguan
                  },
                  {
                    path: '5',
                    name: 'Jumlah dan Durasi RPT RCT Gangguan',
                    component: MonalisaGRJumlahDDRPTRCTGangguan
                  },
                  {
                    path: '6',
                    name: 'Rekapitulasi Gangguan Per Jenis Gangguan',
                    component: MonalisaGRGangguanPerJenisGangguan
                  },
                  {
                    path: '7',
                    name: 'Rekapitulasi Lapor Ulang Gangguan',
                    component: MonalisaGRLaporUlang
                  },
                  {
                    path: '8',
                    name: 'Rekapitulasi ENS Gangguan',
                    component: MonalisaGRENSGangguan
                  },
                  {
                    path: '9',
                    name: 'Rekapitulasi Gangguan Belum Selesai',
                    component: MonalisaGRGangguanBelumSelesai
                  },
                  {
                    path: ':pathMatch(.*)*',
                    component: EmptyPage
                  }
                ]
              },
              {
                path: ':pathMatch(.*)*',
                component: EmptyPage
              }
            ]
          },
          {
            path: 'keluhan',
            name: 'Keluhan',
            children: [
              {
                path: 'rekapitulasi',
                name: 'Rekapitulasi',
                children: [
                  {
                    path: '1',
                    name: 'Jumlah Kali Keluhan',
                    component: MonalisaKRJumlahKaliKeluhan
                  },
                  {
                    path: '2',
                    name: 'Recovery Time (RCT) Keluhan',
                    component: MonalisaKRRecoveryTimeKeluhan
                  },
                  {
                    path: '3',
                    name: 'Response Time (RPT) Keluhan',
                    component: MonalisaKRResponseTimeKeluhan
                  },
                  {
                    path: '4',
                    name: 'Jumlah dan Durasi RPT RCT Keluhan',
                    component: MonalisaKRJumlahDDRPTRCTKeluhan
                  },
                  {
                    path: '5',
                    name: '(Monalisa) Rekapitulasi Keluhan Per Jenis Keluhan',
                    component: MonalisaKRGangguanPerJenisKeluhan
                  },
                  {
                    path: '6',
                    name: 'Rekapitulasi Lapor Ulang Keluhan',
                    component: MonalisaKRLaporUlangKeluhan
                  },
                  {
                    path: '7',
                    name: 'Rekapitulasi Keluhan Belum Selesai',
                    component: MonalisaKRKeluhanBelumSelesai
                  },
                  {
                    path: ':pathMatch(.*)*',
                    component: EmptyPage
                  }
                ]
              },
              {
                path: ':pathMatch(.*)*',
                component: EmptyPage
              }
            ]
          },
          {
            path: 'laporan-kpi',
            name: 'Laporan KPI',
            children: [
              {
                path: 'bulanan',
                name: 'Bulanan',
                children: [
                  {
                    path: '1',
                    name: '(Monalisa) Penurunan Jumlah Komplain',
                    component: MonalisaLBPenurunanJumlahKomplain
                  },
                  {
                    path: '2',
                    name: '(Monalisa) Aging Complaint',
                    component: MonalisaLBAgingComplaint
                  },
                  {
                    path: '3',
                    name: '(Monalisa) Energy Not Sales (ENS)',
                    component: MonalisaLBEnergyNotSales
                  },
                  {
                    path: '4',
                    name: '(Monalisa) Kepatuhan dan Akurasi Dalam Pelaporan',
                    component: MonalisaLBKADDalamPelaporan
                  },
                  {
                    path: ':pathMatch(.*)*',
                    component: EmptyPage
                  }
                ]
              },
              {
                path: 'kumulatif',
                name: 'Kumulatif',
                children: [
                  {
                    path: '1',
                    name: 'Penurunan Jumlah Komplain',
                    component: MonalisaLKPenurunanJumlahKomplain
                  },
                  {
                    path: '2',
                    name: 'Aging Complaint',
                    component: MonalisaLKAgingComplaint
                  },
                  {
                    path: '3',
                    name: 'Energy Not Sales (ENS)',
                    component: MonalisaLKEnergyNotSales
                  },
                  {
                    path: '4',
                    name: 'Kepatuhan dan Akurasi Dalam Pelaporan',
                    component: MonalisaLKKDADPelaporan
                  },
                  {
                    path: ':pathMatch(.*)*',
                    component: EmptyPage
                  }
                ]
              },
              {
                path: ':pathMatch(.*)*',
                component: EmptyPage
              }
            ]
          },
          {
            path: ':pathMatch(.*)*',
            component: EmptyPage
          }
        ]
      },
      {
        path: 'check-in-out',
        name: 'Check In Dan Check Out',
        children: [
          {
            path: 'laporan',
            name: 'Laporan Check In /Check Out (CICO)',
            children: [
              {
                path: '1',
                name: 'Laporan Check In /Check Out (CICO)',
                component: LaporanCICO
              },
              {
                path: ':pathMatch(.*)*',
                component: EmptyPage
              }
            ]
          },
          {
            path: ':pathMatch(.*)*',
            component: EmptyPage
          }
        ]
      },
      {
        path: 'anomali-pengaduan',
        name: 'Anomali Penanganan Pengaduan',
        children: [
          {
            path: 'gangguan',
            name: 'Gangguan',
            children: [
              {
                path: '1',
                name: 'Laporan Anomali Penanganan Pengaduan Gangguan Unit',
                component: Anomali_LAPPGU
              },
              {
                path: '2',
                name: 'Laporan Anomali Penanganan Pengaduan Gangguan Petugas',
                component: Anomali_LAPPGP
              },
              {
                path: ':pathMatch(.*)*',
                component: EmptyPage
              }
            ]
          },
          {
            path: 'keluhan',
            name: 'Keluhan',
            children: [
              {
                path: '1',
                name: 'Laporan Anomali Penanganan Pengaduan Keluhan Unit',
                component: Anomali_LAPPKU
              },
              {
                path: ':pathMatch(.*)*',
                component: EmptyPage
              }
            ]
          },
          {
            path: ':pathMatch(.*)*',
            component: EmptyPage
          }
        ]
      },
      {
        path: 'ctt-kwh-periksa',
        name: 'CTT & KWH Periksa',
        children: [
          {
            path: '1',
            name: 'Laporan CTT & KWH Periksa',
            component: LaporanCttKwhPeriksa
          },
          {
            path: ':pathMatch(.*)*',
            component: EmptyPage
          }
        ]
      },
      {
        path: 'material',
        name: 'Material',
        children: [
          {
            path: 'daftar',
            name: 'Daftar',
            children: [
              {
                path: '1',
                name: 'Daftar Gangguan Dan Material Yang Dipakai',
                component: MaterialDGMYG
              },
              {
                path: ':pathMatch(.*)*',
                component: EmptyPage
              }
            ]
          },
          {
            path: 'rekapitulasi',
            name: 'Rekapitulasi',
            children: [
              {
                path: '1',
                name: 'Rekapitulasi Pemakaian Material',
                component: MaterialRPM
              },
              {
                path: ':pathMatch(.*)*',
                component: EmptyPage
              }
            ]
          },
          {
            path: ':pathMatch(.*)*',
            component: EmptyPage
          }
        ]
      },
      {
        path: 'transaksi',
        name: 'Transaksi',
        children: [
          {
            path: '1',
            name: 'Transaksi APKT',
            component: TransaksiTable1
          },
          {
            path: ':pathMatch(.*)*',
            component: EmptyPage
          }
        ]
      },
      {
        path: 'pencarian-data',
        name: 'Pencarian Data',
        children: [
          {
            path: '1',
            name: 'Pencarian Report Number',
            component: PencarianDataTable1
          },
          {
            path: ':pathMatch(.*)*',
            component: EmptyPage
          }
        ]
      },
      {
        path: ':pathMatch(.*)*',
        component: EmptyPage
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginView
  },
  {
    path: '/404',
    name: 'Not Found',
    component: NotFoundView
  },
  {
    path: '/',
    redirect: {
      name: 'Home'
    }
  }
]

export const mergeChildrenRoutes = (routes: RouteRecordRaw[]): RouteRecordRaw[] => {
  const mergedRoutes: RouteRecordRaw[] = []

  for (const route of routes) {
    if (route.children && route.children.length > 0) {
      // Buat salinan route tanpa children
      const topLevelRoute: RouteRecordRaw = { ...route, children: [] }

      // Salin setiap route children ke children route paling atas
      for (const childRoute of route.children) {
        const fullPath = `${route.path}/${childRoute.path}`.replace(/\/+/g, '/')
        const mergedChildRoute: RouteRecordRaw = { ...childRoute, path: fullPath }
        topLevelRoute.children?.push(mergedChildRoute)
      }

      mergedRoutes.push(topLevelRoute)
    } else {
      // Jika route tidak memiliki children, tambahkan as is
      mergedRoutes.push(route)
    }
  }

  return mergedRoutes
}

export const extractLeafRoutes = (routes: RouteRecordRaw[], parentPath = ''): RouteRecordRaw[] => {
  const leafRoutes: RouteRecordRaw[] = []

  for (const route of routes) {
    const fullPath = `${parentPath}/${route.path}`.replace(/\/+/g, '/')

    if (route.children && route.children.length > 0) {
      leafRoutes.push(...extractLeafRoutes(route.children, fullPath))
    } else {
      const leafRoute = { ...route, path: fullPath }
      leafRoutes.push(leafRoute)
    }
  }

  return leafRoutes
}

export const fixRoute = (route: RouteRecordRaw[]): RouteRecordRaw[] => {
  var newRoute: RouteRecordRaw[] = []

  const getRoute = (route: RouteRecordRaw[], parent: string = '') => {
    route.forEach((r) => {
      if (r.children) {
        if (r.component) {
          const fullPath = `${parent.replace('/', '')}/${r.path.replace('/', '')}`
          newRoute.push({
            path: fullPath,
            name: r.name,
            component: r.component
          } as RouteRecordRaw)
        }
        getRoute(r.children, `${parent}/${r.path}`)
      } else {
        const fullPath = `${parent.replace('/', '')}/${r.path.replace('/', '')}`
        if (
          newRoute.find(
            (nr) => nr.path !== '/' && nr.path === '/home' && fullPath.includes(nr.path)
          )
        ) {
          const index = newRoute.findIndex((nr) => nr.path !== '/' && fullPath.includes(nr.path))
          newRoute[index] = {
            ...newRoute[index],
            children: [
              ...(newRoute[index].children ?? []),
              {
                path:
                  fullPath === '/home/'
                    ? ''
                    : fullPath.includes('/home/')
                      ? fullPath.replace('/home/', '')
                      : fullPath,
                name: r.name,
                component: r.component
              } as RouteRecordRaw
            ]
          }
        } else {
          newRoute.push({
            path: fullPath,
            name: r.name,
            component: r.component
          } as RouteRecordRaw)
        }
      }
    })
  }
  getRoute(route)

  // remove duplicate route path and sort by path length
  const uniqueRoute = newRoute
    .filter((nr, index, self) => self.findIndex((n) => n.path === nr.path) === index)
    .sort((a, b) => b.path.length - a.path.length)
  // console.log('route', newRoute);

  // return uniqueRoute
  return newRoute
}

const router = createRouter({
  history: createWebHistory(),
  linkActiveClass: 'active',
  stringifyQuery: qs.stringify,
  routes: fixRoute(routes),
  strict: true
})

router.beforeEach((to, from, next) => {
  // redirect to login page if not logged in and trying to access a restricted page
  const auth = useAuthStore()

  // if to is not found, redirect to 404
  if (to.matched.length === 0) {
    if (to.path === '/') {
      if (auth.isLoggedIn) {
        next('/home')
      } else {
        next('/login')
      }
    } else {
      next('/404')
    }
  } else {
    // if to is not login and user is not logged in, redirect to login
    if (auth.isLoggedIn) {
      // if to is login and user is logged in, redirect to home
      if (to.path === '/login') {
        next('/home')
      } else {
        next()
      }
    } else {
      // if to is 404, redirect to 404
      if (to.path !== '/404' && to.path !== '/login') {
        next('/login')
      } else {
        next()
      }
    }
  }
})

export default router
