import AppHeader from "@/components/AppHeader"
import ButtonSaveHeader from "@/components/buttonSaveHeader"
import { InputDate } from "@/components/inputDate"
import { InputForm } from "@/components/inputForm"
import ModalSelect from "@/components/modalSelect"
import SelectForm from "@/components/selectForm"
import Styles from "@/constants/Styles"
import { valueTypeEventRepeat } from "@/constants/TypeEventRepeat"
import { apiGetCalendarOne, apiUpdateCalendar } from "@/lib/api"
import { stringToDateTime } from "@/lib/fun_stringToDate"
import { useAuthSession } from "@/providers/AuthProvider"
import { useTheme } from "@/providers/ThemeProvider";
import { useHeaderHeight } from "@react-navigation/elements"
import { Stack, router, useLocalSearchParams } from "expo-router"
import moment from "moment"
import { useEffect, useState } from "react"
import { KeyboardAvoidingView, Platform, SafeAreaView, ScrollView, View } from "react-native"
import Toast from "react-native-toast-message"

export default function EditEventCalendar() {
   const { colors } = useTheme();
   const { token, decryptToken } = useAuthSession();
   const [choose, setChoose] = useState({ val: "", label: "" })
   const [isSelect, setSelect] = useState(false)
   const { id, detail } = useLocalSearchParams<{ id: string, detail: string }>()
   const [idCalendar, setIdCalendar] = useState('')
   const [loading, setLoading] = useState(false)
   const headerHeight = useHeaderHeight()

   const [error, setError] = useState({
      title: false,
      dateStart: false,
      timeStart: false,
      timeEnd: false,
      repeatEventType: false,
      repeatValue: false,
   });
   const [data, setData] = useState({
      timeStart: '',
      timeEnd: '',
      dateStart: '',
      title: '',
      desc: '',
      linkMeet: '',
      repeatEventTyper: '',
      repeatValue: 1,
   })

   async function handleLoad() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetCalendarOne({
            user: hasil,
            id: detail,
            cat: 'data',
         });
         setData({ ...response.data, dateStart: moment(response.data.dateStartFormat, 'DD-MM-YYYY').format('DD-MM-YYYY') })
         setIdCalendar(response.data.idCalendar)
         setChoose({ val: response.data.repeatEventTyper, label: valueTypeEventRepeat.find((item) => item.id == response.data.repeatEventTyper)?.name || "" })
      } catch (error: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mendapatkan data"

         Toast.show({ type: 'small', text1: message })
      }
   }

   useEffect(() => {
      handleLoad();
   }, []);



   function validationForm(cat: "title" | "desc" | "dateStart" | "timeStart" | "timeEnd" | "repeatEventType" | "repeatValue" | "linkMeet", val: string, label?: string) {
      if (cat == "title") {
         setData({ ...data, title: val });
         if (val == "" || val == "null") {
            setError({ ...error, title: true });
         } else {
            setError({ ...error, title: false });
         }
      } else if (cat == "desc") {
         setData({ ...data, desc: val });
      } else if (cat == "dateStart") {
         setData({ ...data, dateStart: val });
         if (val == "" || val == "null") {
            setError({ ...error, dateStart: true });
         } else {
            setError({ ...error, dateStart: false });
         }
      } else if (cat == "timeStart") {
         setData({ ...data, timeStart: val });
         if (val == "" || val == "null") {
            setError({ ...error, timeStart: true });
         } else {
            setError({ ...error, timeStart: false });
         }
         const start = stringToDateTime(data.dateStart, data.timeStart);
         const end = stringToDateTime(data.dateStart, data.timeEnd);
         const timestampAwal = start.getTime();
         const timestampAkhir = end.getTime();

         if (timestampAwal > timestampAkhir) {
            setError({ ...error, timeEnd: true });
         } else {
            setError({ ...error, timeEnd: false });
         }
      } else if (cat == "timeEnd") {
         setData({ ...data, timeEnd: val });
         if (val == "" || val == "null") {
            setError({ ...error, timeEnd: true });
         } else {
            setError({ ...error, timeEnd: false });
         }
         const start = stringToDateTime(data.dateStart, data.timeStart);
         const end = stringToDateTime(data.dateStart, val);
         const timestampAwal = start.getTime();
         const timestampAkhir = end.getTime();

         if (timestampAwal > timestampAkhir) {
            setError({ ...error, timeEnd: true });
         } else {
            setError({ ...error, timeEnd: false });
         }
      } else if (cat == "repeatEventType") {
         setChoose({ val, label: String(label) })
         setData({ ...data, repeatEventTyper: val });
         if (val == "" || val == "null") {
            setError({ ...error, repeatEventType: true });
         } else {
            setError({ ...error, repeatEventType: false });
            if (val == "once") {
               setData(data => ({ ...data, repeatValue: 1 }));
            }
         }
      } else if (cat == "repeatValue") {
         setData({ ...data, repeatValue: Number(val) });
         if (val == "" || val == "null") {
            setError({ ...error, repeatValue: true });
         } else {
            setError({ ...error, repeatValue: false });
         }
      } else if (cat == "linkMeet") {
         setData({ ...data, linkMeet: val });
      }
   }

   async function handleUpdate() {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiUpdateCalendar({ data: { ...data, user: hasil }, id: idCalendar })
         if (response.success) {
            router.replace(`/division/${id}/calendar/`)
            Toast.show({ type: 'small', text1: 'Berhasil mengubah acara', })
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mengubah acara"

         Toast.show({ type: 'small', text1: message })
      } finally {
         setLoading(false)
      }
   }


   return (
      <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
         <Stack.Screen
            options={{
               // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Edit Acara',
               headerTitleAlign: 'center',
               // headerRight: () =>
               //    <ButtonSaveHeader
               //       disable={Object.values(error).some((val) => val == true) || data.title == "" || data.dateStart == "" || data.timeStart == "" || data.timeEnd == "" || data.repeatEventTyper == "" || loading}
               //       category="update-calendar"
               //       onPress={() => {
               //          handleUpdate()
               //       }}
               //    />
               header: () => (
                  <AppHeader
                     title="Edit Acara"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           disable={Object.values(error).some((val) => val == true) || data.title == "" || data.dateStart == "" || data.timeStart == "" || data.timeEnd == "" || data.repeatEventTyper == "" || loading}
                           category="update-calendar"
                           onPress={() => {
                              handleUpdate()
                           }}
                        />
                     }
                  />
               )
            }}
         />
         <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : undefined}
            keyboardVerticalOffset={headerHeight}
         >
            <ScrollView>
               <View style={[Styles.p15]}>
                  <InputForm
                     label="Nama Acara"
                     type="default"
                     placeholder="Nama Acara"
                     required
                     bg={colors.card}
                     value={data.title}
                     onChange={(val) => validationForm("title", val)}
                     error={error.title}
                     errorText="Nama acara tidak boleh kosong"
                  />
                  <InputDate
                     onChange={(val) => validationForm("dateStart", val)}
                     mode="date"
                     value={data.dateStart}
                     label="Tanggal Acara"
                     required
                     error={error.dateStart}
                     errorText="Tanggal acara tidak boleh kosong"
                     placeholder="Pilih Tanggal Acara"
                  />
                  <View style={[Styles.rowSpaceBetween, Styles.mv10]}>
                     <View style={[{ width: "48%" }]}>
                        <InputDate
                           onChange={(val) => validationForm("timeStart", val)}
                           mode="time"
                           value={data.timeStart}
                           label="Waktu Awal"
                           required
                           error={error.timeStart}
                           errorText="Waktu awal tidak valid"
                           placeholder="--:--"
                        />
                     </View>
                     <View style={[{ width: "48%" }]}>
                        <InputDate
                           onChange={(val) => validationForm("timeEnd", val)}
                           mode="time"
                           value={data.timeEnd}
                           label="Waktu Akhir"
                           required
                           error={error.timeEnd}
                           errorText="Waktu akhir tidak valid"
                           placeholder="--:--"
                        />
                     </View>
                  </View>
                  <InputForm
                     label="Link Meet"
                     type="default"
                     placeholder="Link Meet"
                     bg={colors.card}
                     value={data.linkMeet}
                     onChange={(val) => validationForm("linkMeet", val)}
                  />
                  <SelectForm
                     bg={colors.card}
                     label="Ulangi Acara"
                     placeholder="Ulangi Acara"
                     value={choose.label}
                     required
                     onPress={() => { setSelect(true) }}
                  />
                  <InputForm
                     label="Jumlah Pengulangan"
                     type="numeric"
                     placeholder="Jumlah Pengulangan"
                     required
                     bg={colors.card}
                     value={String(data.repeatValue)}
                     onChange={(val) => validationForm("repeatValue", val)}
                     error={error.repeatValue}
                     errorText="Jumlah pengulangan tidak valid"
                     disable={choose.val == "once"}
                  />
                  <InputForm
                     label="Deskripsi"
                     type="default"
                     placeholder="Deskripsi"
                     bg={colors.card}
                     value={data.desc}
                     onChange={(val) => validationForm("desc", val)}
                     multiline
                  />
               </View>
            </ScrollView>
         </KeyboardAvoidingView>


         <ModalSelect
            category={"type-event-repeat"}
            close={setSelect}
            onSelect={(value) => {
               validationForm("repeatEventType", value.val, value.label);
            }}
            title={"Ulangi Acara"}
            open={isSelect}
            valChoose={choose.val}
         />
      </SafeAreaView>
   )
}