import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import Styles from "@/constants/Styles";
import { apiEditTaskTugas, apiGetTaskTugas } from "@/lib/api";
import { setUpdateTask } from "@/lib/taskUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import dayjs from "dayjs";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import {
   SafeAreaView,
   ScrollView,
   Text,
   ToastAndroid,
   View,
} from "react-native";
import DateTimePicker, { DateType } from "react-native-ui-datepicker";
import { useDispatch, useSelector } from "react-redux";

export default function UpdateProjectTaskDivision() {
   const { detail } = useLocalSearchParams<{ detail: string }>();
   const dispatch = useDispatch();
   const update = useSelector((state: any) => state.taskUpdate);
   const { token, decryptToken } = useAuthSession();
   const [range, setRange] = useState<{
      startDate: DateType;
      endDate: DateType;
   }>({ startDate: undefined, endDate: undefined });
   const [month, setMonth] = useState<any>();
   const [year, setYear] = useState<any>();
   const [loading, setLoading] = useState(true);
   const [disableBtn, setDisableBtn] = useState(false);
   const [title, setTitle] = useState("");
   const [error, setError] = useState({
      startDate: false,
      endDate: false,
      title: false,
   });

   const from = range.startDate
      ? dayjs(range.startDate).format("MMM DD, YYYY")
      : "";
   const to = range.endDate ? dayjs(range.endDate).format("MMM DD, YYYY") : "";

   async function handleLoad() {
      try {
         setLoading(true);
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetTaskTugas({
            user: hasil,
            id: detail,
         });
         setTitle(response.data.title);
         setRange({
            startDate: new Date(response.data.dateStart),
            endDate: new Date(response.data.dateEnd),
         });
         setMonth(new Date(response.data.dateStart).getMonth());
         setYear(new Date(response.data.dateStart).getFullYear());
      } catch (error) {
         console.error(error);
      } finally {
         setLoading(false);
      }
   }

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

   async function handleEdit() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiEditTaskTugas({ data: { title, dateStart: dayjs(range.startDate).format("YYYY-MM-DD"), dateEnd: dayjs(range.endDate).format("YYYY-MM-DD"), user: hasil }, id: detail });
         if (response.success) {
            dispatch(setUpdateTask({ ...update, task: !update.task }))
            ToastAndroid.show("Berhasil mengubah data", ToastAndroid.SHORT);
            router.back();
         } else {
            ToastAndroid.show(response.message, ToastAndroid.SHORT);
         }
      } catch (error) {
         console.error(error);
         ToastAndroid.show("Gagal mengubah data", ToastAndroid.SHORT);
      }
   }

   function checkAll() {
      if (
         from == "" ||
         to == "" ||
         title == "" ||
         title == "null" ||
         error.startDate ||
         error.endDate ||
         error.title
      ) {
         setDisableBtn(true);
      } else {
         setDisableBtn(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]);

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => (
                  <ButtonBackHeader
                     onPress={() => {
                        router.back();
                     }}
                  />
               ),
               headerTitle: "Edit Tanggal dan Tugas",
               headerTitleAlign: "center",
               headerRight: () => (
                  <ButtonSaveHeader
                     disable={disableBtn}
                     category="update"
                     onPress={() => {
                        handleEdit()
                     }}
                  />
               ),
            }}
         />
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <View style={[Styles.wrapPaper, Styles.p10]}>
                  {!loading && (
                     <DateTimePicker
                        mode="range"
                        startDate={range.startDate}
                        endDate={range.endDate}
                        onChange={(param) => setRange(param)}
                        month={month}
                        year={year}
                        styles={{
                           selected: Styles.selectedDate,
                           selected_label: Styles.cWhite,
                           range_fill: Styles.selectRangeDate,
                        }}
                     />
                  )}
               </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>
      </SafeAreaView>
   );
}
