import Styles from "@/constants/Styles";
import { stringToDateTime } from "@/lib/fun_stringToDate";
import { useTheme } from "@/providers/ThemeProvider";
import { useEffect, useState } from "react";
import { Dimensions, View, VirtualizedList } from "react-native";
import { InputDate } from "../inputDate";
import ModalFloat from "../modalFloat";
import Text from "../Text";

interface Props {
   date: string;
   timeStart: string;
   timeEnd: string;
}

export default function ModalAddDetailTugasProject({ isVisible, setVisible, dataTanggal, onSubmit }: { isVisible: boolean, setVisible: (value: boolean) => void, dataTanggal: Props[], onSubmit: (data: Props[]) => void }) {
   const { colors } = useTheme();
   const [data, setData] = useState<Props[]>(dataTanggal)
   const tinggiScreen = Dimensions.get("window").height;
   const tinggiFix = tinggiScreen * 70 / 100;
   const [error, setError] = useState<any>([])

   useEffect(() => {
      if (isVisible) {
         setData(dataTanggal)
         setError([])
      }
   }, [isVisible, dataTanggal])


   const getItem = (_data: unknown, index: number): Props => ({
      date: data[index].date,
      timeStart: data[index].timeStart,
      timeEnd: data[index].timeEnd,
   })

   function settingError(date: string, cat: 'timeStart' | 'timeEnd', val: boolean) {
      const ada = error.find((item: any) => item.date == date)
      if (ada) {
         setError(error.map((item: any) => {
            if (item.date == date) {
               return { ...item, [cat]: val }
            }
            return item
         }))
      } else {
         setError([...error, { date, [cat]: val }])
      }
   }

   function validationForm(cat: "timeStart" | "timeEnd", val: string, date: string) {
      if (cat == "timeEnd") {
         const start = stringToDateTime("", String(data.find((item) => item.date == date)?.timeStart))
         const end = stringToDateTime("", val)
         const timestampAwal = start.getTime()
         const timestampAkhir = end.getTime()
         if (val == "" || val == null || timestampAwal > timestampAkhir) {
            settingError(date, "timeEnd", true)
         } else {
            settingError(date, "timeEnd", false)
         }
      } else {
         const end = stringToDateTime("", String(data.find((item) => item.date == date)?.timeEnd))
         const start = stringToDateTime("", val)
         const timestampAwal = start.getTime()
         const timestampAkhir = end.getTime()

         if (val == "" || val == null || timestampAwal > timestampAkhir) {
            settingError(date, "timeEnd", true)
         } else {
            settingError(date, "timeEnd", false)
         }
      }

      setData(data.map((item) => {
         if (item.date == date) {
            return { ...item, [cat]: val }
         }
         return item
      }))
   }

   return (
      <ModalFloat
         title="Detail Tanggal dan Waktu Tugas"
         isVisible={isVisible}
         setVisible={setVisible}
         disableSubmit={Object.values(error).some((val: any) => val.timeEnd == true || val.timeStart == true)}
         onSubmit={() => {
            onSubmit(data)
            setVisible(false)
         }}
      >
         <View style={[{ height: tinggiFix, }]} >
            <VirtualizedList
               data={data}
               getItemCount={() => data.length}
               getItem={getItem}
               renderItem={({ item, index }: { item: Props, index: number }) => {
                  return (
                     <View key={index} style={[Styles.borderBottom, Styles.pv05, { borderBottomColor: colors.icon + "20" }]}>
                        <Text style={[Styles.textDefaultSemiBold]}>{item.date}</Text>
                        <View style={[Styles.rowSpaceBetween]}>
                           <View style={[{ width: "48%" }]}>
                              <InputDate
                                 mode="time"
                                 onChange={(val) => { validationForm("timeStart", val, item.date) }}
                                 value={item.timeStart}
                                 label="Waktu Awal"
                                 placeholder="--:--"
                                 error={error.find((error: any) => error.date == item.date)?.timeStart}
                                 errorText="Waktu awal tidak valid"
                              />
                           </View>
                           <View style={[{ width: "48%" }]}>
                              <InputDate
                                 onChange={(val) => { validationForm("timeEnd", val, item.date) }}
                                 mode="time"
                                 value={item.timeEnd}
                                 label="Waktu Akhir"
                                 placeholder="--:--"
                                 error={error.find((error: any) => error.date == item.date)?.timeEnd}
                                 errorText="Waktu akhir harus lebih dari waktu awal"
                              />
                           </View>
                        </View>
                     </View>
                  )
               }}
               keyExtractor={(item, index) => String(index)}
               showsVerticalScrollIndicator={false}
            />
         </View>

      </ModalFloat>
   )
}