'use client'
import { Avatar, Box, Button, Center, Divider, Flex, Grid, Group, Text, Loader } from "@mantine/core";
import { DateInput } from "@mantine/dates";
import _ from "lodash";
import { useState } from "react";
import { IDataLogUserDashboard } from "../lib/type_log_user";
import toast from "react-hot-toast";
import { funGetLogUserDashboard } from "../lib/api_log_user";
import moment from "moment";
import { useShallowEffect } from "@mantine/hooks";

export default function LogUserPage() {
   const [value, setValue] = useState<Date | undefined>(new Date());
   const [valueEnd, setValueEnd] = useState<Date | undefined>(new Date());
   const [data, setData] = useState<IDataLogUserDashboard[]>([]);
   const [loading, setLoading] = useState(true)

   async function onShow(awal: any, akhir: any) {
      try {
         setLoading(true)
         const res = await funGetLogUserDashboard(`?village=desa1&dateStart=${moment(awal).format("YYYY-MM-DD")}&dateEnd=${moment(akhir).format("YYYY-MM-DD")}`)
         if (res.success) {
            setData(res.data)
         } else {
            toast.error(res.message)
         }
      } catch (error) {
         console.error(error)
         toast.error("Gagal mendapatkan data, coba lagi nanti");
      } finally {
         setLoading(false)
      }
   }

   function onChangeDateStart(val: any, kat: string) {
      if (kat == "start") {
         val == null ? setValue(undefined) : setValue(val)
         if (valueEnd != undefined && val != undefined && valueEnd < val) {
            setValueEnd(val)
            onShow(val, val)
         } else {
            onShow(val, valueEnd)
         }
      } else if (kat == "end") {
         val == null ? setValueEnd(undefined) : setValueEnd(val)
         onShow(value, val)
      }
   }

   useShallowEffect(() => {
      onShow(value, valueEnd)
   }, [])

   return (
      <>
         <Box p={15}>
            <Box mb={20}>
               <DateInput
                  value={value}
                  onChange={(val) => { onChangeDateStart(val, 'start') }}
                  label="Tanggal Awal"
                  placeholder="Tanggal Awal"
                  mb={5}
               />
               <DateInput
                  minDate={value}
                  value={valueEnd}
                  onChange={(val) => { onChangeDateStart(val, 'end') }}
                  label="Tanggal Akhir"
                  placeholder="Tanggal Akhir"
               />
            </Box>
            <Flex gap="sm" justify="center" align="center" direction="column" wrap="wrap">
               {
                  !loading ?
                     data.length > 0 ?
                        data.map((item, i) => {
                           return (
                              <Box key={i} w={"100%"} style={{ backgroundColor: 'white', padding: 10, borderRadius: 10 }}>
                                 <Grid align="center" style={{ borderBottomWidth: 1, borderBottomColor: 'whitesmoke', borderBottomStyle: 'solid', paddingBottom: 5 }}>
                                    <Grid.Col
                                       span={{
                                          base: 1,
                                          xs: 1,
                                          sm: 1,
                                          md: 1,
                                          lg: 1,
                                          xl: 1,
                                       }}
                                    >
                                       <Avatar size={50} alt="image" src={`https://wibu-storage.wibudev.com/api/files/${item.userImg}`} />
                                    </Grid.Col>
                                    <Grid.Col
                                       span={{
                                          base: 10,
                                          xs: 10.5,
                                          sm: 10.5,
                                          md: 10.5,
                                          lg: 10.5,
                                          xl: 10.5,
                                       }}
                                       pl={20}
                                       pr={0}
                                    >
                                       <Group justify="space-between">
                                          <Text fw={"bold"} c={"black"} truncate="end" >
                                             {item.userName}
                                          </Text>
                                          <Text fw={"lighter"} fz={12}>{item.createdAt}</Text>
                                       </Group>

                                       <Text fw={"lighter"} fz={12} truncate="end">
                                          {item.userRole + ' - ' + item.userGroup}
                                       </Text>
                                    </Grid.Col>
                                 </Grid>
                                 <Box px={10} py={5}>
                                    <Text>{item.desc}</Text>
                                    <Text fw={"lighter"} fz={10}>{item.tbContent + ' | ' + item.idContent}</Text>
                                 </Box>

                              </Box>
                           )
                        })

                        :
                        (
                           <Text ta={'center'}>Data Kosong</Text>
                        )
                     :
                     (
                        <Loader color="grape" type="dots" />
                     )
               }
            </Flex>
         </Box>
      </>
   )
}