import AppHeader from "@/components/AppHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import ButtonSelect from "@/components/buttonSelect";
import { InputForm } from "@/components/inputForm";
import ModalAddDetailTugasTask from "@/components/task/modalAddDetailTugasTask";
import Text from "@/components/Text";
import Styles from "@/constants/Styles";
import { formatDateOnly } from "@/lib/fun_formatDateOnly";
import { getDatesInRange } from "@/lib/fun_getDatesInRange";
import { setTaskCreate } from "@/lib/taskCreate";
import { useTheme } from "@/providers/ThemeProvider";
import { useHeaderHeight } from '@react-navigation/elements';
import { router, Stack } from "expo-router";
import 'intl';
import 'intl/locale-data/jsonp/id';
import moment from "moment";
import { useEffect, useState } from "react";
import {
   KeyboardAvoidingView,
   Platform,
   SafeAreaView,
   ScrollView,
   View
} from "react-native";
import DateTimePicker, {
   DateType
} from "react-native-ui-datepicker";
import { useDispatch, useSelector } from "react-redux";

export default function CreateTaskAddTugas() {
   const { colors } = useTheme();
   const headerHeight = useHeaderHeight();
   const dispatch = useDispatch()
   const [disable, setDisable] = useState(true);
   const [range, setRange] = useState<{
      startDate: DateType;
      endDate: DateType;
   }>({ startDate: undefined, endDate: undefined });
   const [error, setError] = useState({
      startDate: false,
      endDate: false,
      title: false,
   })
   const [title, setTitle] = useState('');
   const taskCreate = useSelector((state: any) => state.taskCreate)
   const [dsbButton, setDsbButton] = useState(true)
   const [dataDetail, setDataDetail] = useState<any>([])
   const [modalDetail, setModalDetail] = useState(false)

   const from = formatDateOnly(range.startDate, "DD-MM-YYYY")
   const to = formatDateOnly(range.endDate, "DD-MM-YYYY")

   function checkAll() {
      if (from == "" || to == "" || title == "" || title == "null" || error.startDate || error.endDate || error.title) {
         setDisable(true)
      } else {
         setDisable(false)
      }
   }

   function onValidation(cat: string, val: string) {
      if (cat == "title") {
         setTitle(val)
         if (val == "" || val == "null") {
            setError(error => ({ ...error, title: true }))
         } else {
            setError(error => ({ ...error, title: false }))
         }
      }
   }

   function checkButton() {
      if (range.startDate == null || range.endDate == null || range.startDate == undefined || range.endDate == undefined) {
         setDsbButton(true)
         setDataDetail([])
      } else {
         setDsbButton(false)
         const awal = formatDateOnly(range.startDate, "YYYY-MM-DD")
         const akhir = formatDateOnly(range.endDate, "YYYY-MM-DD")
         const datanya = getDatesInRange(awal, akhir)
         setDataDetail(datanya.map((item: any) => ({
            date: item,
            timeStart: null,
            timeEnd: null,
         })))
      }
   }

   useEffect(() => {
      checkAll()
   }, [from, to, title, error])

   useEffect(() => {
      checkButton()
   }, [range])

   async function handleCreate() {
      try {
         const dataDetailFix = dataDetail.map((item: any) => ({
            date: moment(item.date, "DD-MM-YYYY").format("YYYY-MM-DD"),
            timeStart: item.timeStart,
            timeEnd: item.timeEnd,
         }))
         const hasilOrder = [...taskCreate, {
            title: title,
            dateStart: from,
            dateEnd: to,
            dateStartFix: formatDateOnly(range.startDate, "YYYY-MM-DD"),
            dateEndFix: formatDateOnly(range.endDate, "YYYY-MM-DD"),
            dataDetail: dataDetailFix
         }].sort((a, b) => {
            return new Date(a.dateStartFix).getTime() - new Date(b.dateStartFix).getTime();
         });

         dispatch(setTaskCreate(hasilOrder))
         router.back();
      } catch (error) {
         console.error(error);
      }
   }

   return (
      <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => {
               //          router.back();
               //       }}
               //    />
               // ),
               headerTitle: "Tambah Tugas",
               headerTitleAlign: "center",
               // headerRight: () => (
               //    <ButtonSaveHeader
               //       disable={disable}
               //       category="create"
               //       onPress={() => { handleCreate() }}
               //    />
               // ),
               header: () => (
                  <AppHeader title="Tambah Tugas"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           disable={disable}
                           category="create"
                           onPress={() => { handleCreate() }}
                        />
                     }
                  />
               )
            }}
         />
         <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : undefined}
            keyboardVerticalOffset={headerHeight}
         >
            <ScrollView>
               <View style={[Styles.p15, Styles.mb100]}>
                  <View style={[Styles.wrapPaper, Styles.p10, { backgroundColor: colors.card, borderColor: colors.background }]}>
                     <DateTimePicker
                        mode="range"
                        startDate={range.startDate}
                        endDate={range.endDate}
                        onChange={(param) => setRange(param)}
                        styles={{
                           selected: Styles.selectedDate,
                           selected_label: Styles.cWhite,
                           range_fill: Styles.selectRangeDate,
                           month_label: { color: colors.text },
                           month_selector_label: { color: colors.text },
                           year_label: { color: colors.text },
                           year_selector_label: { color: colors.text },
                           day_label: { color: colors.text },
                           time_label: { color: colors.text },
                           weekday_label: { color: colors.text },
                        }}
                     />
                  </View>
                  <View style={[Styles.mv10]}>
                     <View style={[Styles.rowSpaceBetween]}>
                        <View style={[{ width: "48%" }]}>
                           <Text style={[Styles.mb05]}>
                              Tanggal Mulai <Text style={{ color: colors.error }}>*</Text>
                           </Text>
                           <View style={[Styles.wrapPaper, Styles.noShadow, Styles.borderAll, Styles.p10, { backgroundColor: colors.card, borderColor: colors.icon + '20' }]}>
                              <Text style={{ textAlign: "center" }}>{from}</Text>
                           </View>
                        </View>
                        <View style={[{ width: "48%" }]}>
                           <Text style={[Styles.mb05]}>
                              Tanggal Berakhir <Text style={{ color: colors.error }}>*</Text>
                           </Text>
                           <View style={[Styles.wrapPaper, Styles.noShadow, Styles.borderAll, Styles.p10, { backgroundColor: colors.card, borderColor: colors.icon + '20' }]}>
                              <Text style={{ textAlign: "center" }}>{to}</Text>
                           </View>
                        </View>
                     </View>
                     {
                        (error.endDate || error.startDate) && <Text style={[Styles.textInformation, { color: colors.error }, Styles.mt05]}>Tanggal tidak boleh kosong</Text>
                     }
                     {/* <Pressable
                        style={[Styles.btnTab, Styles.btnLainnya, dsbButton && Styles.btnDisabled]}
                        disabled={dsbButton}
                        onPress={() => { setModalDetail(true) }}
                     >
                        <Text style={[dsbButton ? Styles.cGray : Styles.cWhite]}>Detail</Text>
                     </Pressable> */}
                     <ButtonSelect value="Detail" onPress={() => { setModalDetail(true) }} />
                  </View>
                  <InputForm
                     label="Judul Tugas"
                     type="default"
                     placeholder="Judul Tugas"
                     required
                     bg={colors.card}
                     value={title}
                     error={error.title}
                     errorText="Judul tidak boleh kosong"
                     onChange={(e) => {
                        onValidation("title", e)
                     }}
                  />
               </View>
            </ScrollView>
         </KeyboardAvoidingView>
         <ModalAddDetailTugasTask
            isVisible={modalDetail}
            setVisible={setModalDetail}
            dataTanggal={dataDetail}
            onSubmit={(data) => {
               setDataDetail(data)
            }}
         />
      </SafeAreaView>
   );
}
