import AppHeader from "@/components/AppHeader";
import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonNextHeader from "@/components/buttonNextHeader";
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 { setFormCreateCalendar } from "@/lib/calendarCreate";
import { stringToDateTime } from "@/lib/fun_stringToDate";
import { useHeaderHeight } from '@react-navigation/elements';
import { useTheme } from "@/providers/ThemeProvider";
import { Stack, router, useLocalSearchParams } from "expo-router";
import { useState } from "react";
import {
   KeyboardAvoidingView,
   Platform,
   SafeAreaView,
   ScrollView,
   View
} from "react-native";
import { useDispatch, useSelector } from "react-redux";

export default function CalendarDivisionCreate() {
   const { colors } = useTheme();
   const { id } = useLocalSearchParams<{ id: string }>()
   const [choose, setChoose] = useState({ val: "", label: "" })
   const [isSelect, setSelect] = useState(false)
   const update = useSelector((state: any) => state.calendarCreate)
   const dispatch = useDispatch()
   const headerHeight = useHeaderHeight();
   const [error, setError] = useState({
      title: false,
      dateStart: false,
      timeStart: false,
      timeEnd: false,
      repeatEventType: false,
      repeatValue: false,
   });
   const [data, setData] = useState({
      title: "",
      desc: "",
      dateStart: "",
      timeStart: "",
      timeEnd: "",
      repeatEventType: "",
      repeatValue: 1,
      linkMeet: "",
   });

   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, repeatEventType: 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 });
      }
   }

   function handleSetData() {
      dispatch(setFormCreateCalendar(data))
      router.push(`./create-member`)
   }

   return (
      <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => {
               //          router.back();
               //       }}
               //    />
               // ),
               headerTitle: "Tambah Acara",
               headerTitleAlign: "center",
               // headerRight: () => (
               //    <ButtonNextHeader
               //       onPress={() => { handleSetData() }}
               //       disable={Object.values(error).some((val) => val == true) || data.title == "" || data.dateStart == "" || data.timeStart == "" || data.timeEnd == "" || data.repeatEventType == ""}
               //    />
               // ),
               header: () => (
                  <AppHeader
                     title="Tambah Acara"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonNextHeader
                           onPress={() => { handleSetData() }}
                           disable={Object.values(error).some((val) => val == true) || data.title == "" || data.dateStart == "" || data.timeStart == "" || data.timeEnd == "" || data.repeatEventType == ""}
                        />
                     }
                  />
               )
            }}
         />
         <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : undefined}
            keyboardVerticalOffset={headerHeight}
         >
            <ScrollView
               showsVerticalScrollIndicator={false}
               style={[Styles.h100]}
            >
               <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>
   );
}
