import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import Text from "@/components/Text";
import Styles from "@/constants/Styles";
import { setTaskCreate } from "@/lib/taskCreate";
import { useHeaderHeight } from '@react-navigation/elements';
import dayjs from "dayjs";
import { router, Stack } from "expo-router";
import 'intl';
import 'intl/locale-data/jsonp/id';
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 CreateProjectAddTask() {
   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 from = range.startDate
      ? dayjs(range.startDate).format("DD-MM-YYYY")
      : "";
   const to = range.endDate ? dayjs(range.endDate).format("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 }))
         }
      }
   }

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

   async function handleCreate() {
      try {
         dispatch(setTaskCreate([...taskCreate, {
            title: title,
            dateStart: from,
            dateEnd: to,
            dateStartFix: dayjs(range.startDate).format("YYYY-MM-DD"),
            dateEndFix: dayjs(range.endDate).format("YYYY-MM-DD"),
         }]))
         router.back();
      } catch (error) {
         console.error(error);
      }
   }

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => (
                  <ButtonBackHeader
                     onPress={() => {
                        router.back();
                     }}
                  />
               ),
               headerTitle: "Tambah Tugas",
               headerTitleAlign: "center",
               headerRight: () => (
                  <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]}>
                     <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: Styles.cBlack,
                           month_selector_label: Styles.cBlack,
                           year_label: Styles.cBlack,
                           year_selector_label: Styles.cBlack,
                           day_label: Styles.cBlack,
                           time_label: Styles.cBlack,
                           weekday_label: Styles.cBlack,
                        }}
                     />
                  </View>
                  <View style={[Styles.mv10]}>
                     <View style={[Styles.rowSpaceBetween]}>
                        <View style={[{ width: "48%" }]}>
                           <Text style={[Styles.mb05]}>
                              Tanggal Mulai <Text style={Styles.cError}>*</Text>
                           </Text>
                           <View style={[Styles.wrapPaper, Styles.p10]}>
                              <Text style={{ textAlign: "center" }}>{from}</Text>
                           </View>
                        </View>
                        <View style={[{ width: "48%" }]}>
                           <Text style={[Styles.mb05]}>
                              Tanggal Berakhir <Text style={Styles.cError}>*</Text>
                           </Text>
                           <View style={[Styles.wrapPaper, Styles.p10]}>
                              <Text style={{ textAlign: "center" }}>{to}</Text>
                           </View>
                        </View>
                     </View>
                     {
                        (error.endDate || error.startDate) && <Text style={[Styles.textInformation, Styles.cError, Styles.mt05]}>Tanggal tidak boleh kosong</Text>
                     }
                  </View>
                  <InputForm
                     label="Judul Tugas"
                     type="default"
                     placeholder="Judul Tugas"
                     required
                     bg="white"
                     value={title}
                     error={error.title}
                     errorText="Judul tidak boleh kosong"
                     onChange={(e) => {
                        onValidation("title", e)
                     }}
                  />
               </View>
            </ScrollView>
         </KeyboardAvoidingView>
      </SafeAreaView>
   );
}
