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 { 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 { 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 [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>
         <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 == ""}
                  />
               ),
            }}
         />
         <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : undefined}
            keyboardVerticalOffset={110}
         >
            <ScrollView>
               <View style={[Styles.p15]}>
                  <InputForm
                     label="Nama Acara"
                     type="default"
                     placeholder="Nama Acara"
                     required
                     bg="white"
                     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="white"
                     value={data.linkMeet}
                     onChange={(val) => validationForm("linkMeet", val)}
                  />
                  <SelectForm
                     bg="white"
                     label="Ulangi Acara"
                     placeholder="Ulangi Acara"
                     value={choose.label}
                     required
                     onPress={() => { setSelect(true) }}
                  />
                  <InputForm
                     label="Jumlah Pengulangan"
                     type="numeric"
                     placeholder="Jumlah Pengulangan"
                     required
                     bg="white"
                     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="white"
                     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>
   );
}
