"use client";
import { globalRole, LayoutNavbarNew, TEMA } from "@/module/_global";
import { funGetAllGroup, IDataGroup } from "@/module/group";
import { useHookstate } from "@hookstate/core";
import { Badge, Box, Select, Skeleton, Stack, Table } from "@mantine/core";
import { DateInput } from "@mantine/dates";
import { useShallowEffect } from "@mantine/hooks";
import _ from "lodash";
import moment from "moment";
import { useParams } from "next/navigation";
import router from "next/router";
import { useState } from "react";
import toast from "react-hot-toast";
import { funGetReportDivision } from "../lib/api_division";
import EchartBarReportCalender from "./echart_bar_calender";
import EchartBarReport from "./echart_bar_report";
import EchartPaiReport from "./echart_pai_report";

export default function CreateReport() {
  const [value, setValue] = useState<Date | null>(null);
  const [valueAkhir, setValueAkhir] = useState<Date | null>(null);
  const [dataGroup, setDataGroup] = useState<IDataGroup[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadingTable, setLoadingTable] = useState(false);
  const [tampil, setTampil] = useState(false);
  const [isGroup, setIsGroup] = useState("");
  const param = useParams<{ id: string }>()
  const tema = useHookstate(TEMA)
  const roleLogin = useHookstate(globalRole)
  const [reportTable, setReportTable] = useState<any[]>([])
  const [report, setReport] = useState({
    progress: [],
    dokumen: [],
    event: [],
  })
  const [touched, setTouched] = useState({
    grup: false,
    start_date: false,
    end_date: false
  })

  async function loadData() {
    const loadGroup = await funGetAllGroup('?active=true')
    if (loadGroup.success) {
      setDataGroup(loadGroup.data);
    } else {
      toast.error(loadGroup.message);
    }
  }

  async function onReport(group: string, awal: any, akhir: any) {
    try {
      setReport({
        progress: [],
        dokumen: [],
        event: [],
      })
      setTampil(true)
      setLoading(true)
      const res = await funGetReportDivision(`?group=${group}&division=${param.id}&date=${moment(awal).format("YYYY-MM-DD")}&date-end=${moment(akhir).format("YYYY-MM-DD")}`)
      if (res.success) {
        setReport(res.data)
      } else {
        toast.error(res.message)
      }
    } catch (error) {
      console.error(error)
      toast.error("Gagal mendapatkan data, coba lagi nanti");
    } finally {
      setLoading(false)
    }
  }

  async function onReportTable(group: string, awal: any, akhir: any) {
    try {
      setLoadingTable(true)
      const res = await funGetReportDivision(`?cat=table-progress&group=${group}&division=${param.id}&date=${moment(awal).format("YYYY-MM-DD")}&date-end=${moment(akhir).format("YYYY-MM-DD")}`)
      if (res.success) {
        setReportTable(res.data)
      } else {
        toast.error(res.message)
      }
    } catch (error) {
      console.error(error)
    } finally {
      setLoadingTable(false)
    }
  }


  function onChangeDate(val: any, kat: string) {
    if (kat == "grup") {
      setIsGroup(val)
      if (val == null || val == "") {
        setTampil(false)
        setTouched({ ...touched, grup: true })
      } else {
        setIsGroup(String(val))
        setTouched({ ...touched, grup: false })

        if (value != null && value != undefined && valueAkhir != null && valueAkhir != undefined && !touched.end_date) {
          onReport(String(val), value, valueAkhir)
          onReportTable(String(val), value, valueAkhir)
        }
      }
    } else if (kat == "start-date") {
      setValue(val)
      if (valueAkhir != null && valueAkhir != undefined) {
        if (val >= valueAkhir) {
          setTouched({ ...touched, end_date: true })
          setTampil(false)
        } else {
          setTouched({ ...touched, end_date: false })
          if ((roleLogin.get() == "supadmin" || roleLogin.get() == "developer") && (isGroup == "" || isGroup == null || isGroup == undefined)) {
            setTampil(false)
          } else {
            onReport(isGroup, val, valueAkhir)
            onReportTable(isGroup, val, valueAkhir)
          }
        }
      }
    } else if (kat == "end-date") {
      setValueAkhir(val)
      if (value != null && value != undefined) {
        if (value >= val) {
          setTouched({ ...touched, end_date: true })
          setTampil(false)
        } else {
          setTouched({ ...touched, end_date: false })
          if ((roleLogin.get() == "supadmin" || roleLogin.get() == "developer") && (isGroup == "" || isGroup == null || isGroup == undefined)) {
            setTampil(false)
          } else {
            onReport(isGroup, value, val)
            onReportTable(isGroup, value, val)
          }
        }
      }
    }
  }

  useShallowEffect(() => {
    loadData();
  }, []);

  return (
    <Box>
      <LayoutNavbarNew back="/division" title="Laporan Divisi" menu />
      <Box p={20}>
        <Stack>
          {(roleLogin.get() == "supadmin" || roleLogin.get() == "developer") &&
            <Select
              placeholder="Lembaga Desa"
              label="Lembaga Desa"
              size="md"
              required
              radius={10}
              data={dataGroup?.map((pro: any) => ({
                value: String(pro.id),
                label: pro.name
              }))}
              onChange={(val) => { onChangeDate(val, 'grup') }}
              error={touched.grup && "Lembaga desa tidak boleh kosong"}
            />
          }

          <DateInput
            valueFormat='DD-MM-YYYY'
            value={value}
            onChange={(val) => { onChangeDate(val, 'start-date') }}
            radius={10}
            size="md"
            required
            label="Tanggal Awal"
            placeholder="Tanggal Awal"
          />

          <DateInput
            valueFormat='DD-MM-YYYY'
            value={valueAkhir}
            onChange={(val) => { onChangeDate(val, 'end-date') }}
            radius={10}
            size="md"
            required
            label="Tanggal Akhir"
            placeholder="Tanggal Akhir"
            error={touched.end_date && "Tanggal akhir harus lebih besar dari tanggal awal"}
          />
          {
            tampil &&
            <>
              {
                loading ?
                  <>
                    <Box pb={20}>
                      <Skeleton width={"100%"} height={200} radius={"md"} />
                    </Box>
                    {
                      Array(2)
                        .fill(null)
                        .map((_, i) => (
                          <Box key={i} mb={0}>
                            <Skeleton height={100} width={"100%"} radius={"md"} />
                          </Box>
                        ))
                    }
                  </>
                  :
                  <>
                    <Box pt={10}>
                      <Box
                        bg={"white"}
                        style={{
                          border: `1px solid ${tema.get().bgTotalKegiatan}`,
                          borderRadius: 10,
                          padding: 10,
                        }}
                      >
                        <EchartPaiReport data={report.progress} />
                        {
                          !loadingTable ?
                            <Table highlightOnHover striped withTableBorder mt={50}>
                              <Table.Tr>
                                <Table.Th>Tugas</Table.Th>
                                <Table.Th>Progres</Table.Th>
                                <Table.Th>Status</Table.Th>
                              </Table.Tr>
                              {
                                reportTable.length == 0 ?
                                  <Table.Tr>
                                    <Table.Td colSpan={3} ta={"center"}>Data kosong</Table.Td>
                                  </Table.Tr>
                                  :
                                  reportTable.map((item: any, i: number) => {
                                    return (
                                      <Table.Tr key={i} onClick={() => { router.push(`/division/${param.id}/task/${item.id}`) }}>
                                        <Table.Td>{item.title}</Table.Td>
                                        <Table.Td>
                                          {_.isNull(item.progress) ? 0 : item.progress}%
                                        </Table.Td>
                                        <Table.Td>
                                          <Badge size="xs" color={
                                            item.status === 0 ? '#5470c6' :
                                              item.status === 2 ? '#fac858' :
                                                item.status === 1 ? '#92cc76' :
                                                  item.status === 3 ? '#ef6666' :
                                                    "grey"
                                          }>
                                            {
                                              item.status === 0 ? 'Segera' :
                                                item.status === 1 ? 'Dikerjakan' :
                                                  item.status === 2 ? 'Selesai' :
                                                    item.status === 3 ? 'Dibatalkan' :
                                                      "Segera"
                                            }
                                          </Badge>
                                        </Table.Td>
                                      </Table.Tr>
                                    )
                                  })
                              }

                            </Table>
                            : <></>
                        }
                      </Box>
                    </Box>
                    <Box pt={10}>
                      <Box
                        bg={"white"}
                        style={{
                          border: `1px solid ${tema.get().bgTotalKegiatan}`,
                          borderRadius: 10,
                          padding: 10,
                        }}
                      >
                        <EchartBarReport data={report.dokumen} />
                      </Box>
                    </Box>
                    <Box pt={10}>
                      <Box
                        bg={"white"}
                        style={{
                          border: `1px solid ${tema.get().bgTotalKegiatan}`,
                          borderRadius: 10,
                          padding: 10,
                        }}
                      >
                        <EchartBarReportCalender data={report.event} />
                        {/* <EventReport data={report.event} tgl={moment(value).format("DD MMMM YYYY")} /> */}
                      </Box>
                    </Box>

                  </>
              }
            </>
          }
        </Stack>
      </Box>
    </Box>
  );
}
