import { MessageType, RoomType, TodoOptionType } from "@openchat/types"
import { RandomUtils } from "@openchat/core"
import { useEffect, useState } from "react"
import { Pressable, View, TouchableOpacity } from "react-native"
import { StyledText } from "../../../ui-components/styled-text/styled-text"
import {
 NestableDraggableFlatList,
 NestableScrollContainer,
 RenderItemParams,
} from "react-native-draggable-flatlist"
import Modal from "react-native-modal"
import { Button } from "../../../ui-components/button/button.component"
import { Checkbox } from "../../../ui-components/checkbox/checkbox.component"
import { Input } from "../../../ui-components/input/input"
import { MenuOpener } from "../../../ui-components/menu/menu-opener.provider"
import { EditDeleteTodos } from "./edit-delete-todos.component"
import { styles } from "./message-board-card-info-modal-todos.styles.module"
import { SvgXml } from "react-native-svg"
import {
 bgHeaderModal,
 bgSVG,
 bigVerticalLienForTodoEdit,
 pencilIcon,
} from "../../../ui-components/svgIcons/svgIcons"
import { ConfirmationModalize } from "../../../ui-components/confirmation-modalize/confirmation-modalize.component"
import { Icon } from "../../../ui-components/icon/icon.component"
import { useRoomMetadata } from "@openchat/ui"
import { AppColors } from "../../../app/app.colors"
import { MessageBoardCardInfoPopup } from "./message-board-card-info-popup"
import { useModal } from "../../../ui-components/modal/modal.hook"

export const MessageBoardCardInfoModalTodos = ({
 message,
 todoOptions,
 setTodoOptions,
 room,
 testID,
 setIsDisableScrollInDrag,
}: {
 message: MessageType
 todoOptions: TodoOptionType[]
 setTodoOptions: (todoOptions: TodoOptionType[]) => void
 room: RoomType
 testID?: string
 setIsDisableScrollInDrag: (arg: boolean) => void
}) => {
 // ---------------------------------------------------------------------------
 // variables
 // ---------------------------------------------------------------------------

 const modal = useModal()
 const [name, setName] = useState("")
 const [isModalOpened, setModalOpened] = useState(false)
 const [updateTodo, setUpdateTodo] = useState<TodoOptionType>()
 const [contentType, setContentType] = useState<"create" | "delete">("create")
 const [deleteTodoId, setDeleteTodoId] = useState("")

 const { community, channel, group, user } = useRoomMetadata(room.id)
 console.log("====================================")
 console.log("todo options: ", todoOptions)
 console.log("====================================")
 // ---------------------------------------------------------------------------
 // effects
 // ---------------------------------------------------------------------------

 useEffect(() => {
  setTodoOptions(todoOptions.sort((a, b) => a.order - b.order))
 }, [todoOptions])

 useEffect(() => {
  if (updateTodo && updateTodo.name) setName(updateTodo.name)
 }, [updateTodo && updateTodo.name])

 // ---------------------------------------------------------------------------
 // functions
 // ---------------------------------------------------------------------------

 async function saveTodo() {
  if (!name || !message.board || !community) return
  setTodoOptions([
   ...todoOptions,
   {
    id: RandomUtils.uuid(),
    name: name,
    isChecked: false,
    order: todoOptions.length,
   },
  ])

  // setModalOpened(false)
  setName("")
 }

 async function remoteUpdateTodo(updatedTodo: any, isChecked: boolean) {
  if (!message.board || !todoOptions || !community) return
  setTodoOptions([
   ...todoOptions.map((option) => {
    if (updatedTodo.id !== option.id) return option
    return {
     ...option,
     isChecked: isChecked,
    }
   }),
  ])
 }

 async function remoteUpdateNameTodo(updatedId: string, name: string) {
  if (!message.board || !todoOptions || !community) return

  setTodoOptions([
   ...todoOptions.map((option) => {
    if (updatedId !== option.id) return option
    return {
     ...option,
     name: name,
    }
   }),
  ])
  setName("")
 }

 async function removeTodo(optionId: string) {
  if (!message.board || !todoOptions || !community) return
  setTodoOptions([...todoOptions.filter((option) => option.id !== optionId)])
 }

 // ---------------------------------------------------------------------------
 // render functions
 // ---------------------------------------------------------------------------

 function openTodoPopup(currentTodo: TodoOptionType) {
  return (
   <EditDeleteTodos
    option={currentTodo}
    removeTodo={removeTodo}
    setUpdateTodo={setUpdateTodo}
    setContentType={setContentType}
   />
  )
 }

 // function onDragEnd(reorderTodoOptions: TodoOptionType[]) {
 //  const reordered = reorderTodoOptions.map((reorderOption, index) => {
 //   const reorder = todoOptions.find((it) => it.id === reorderOption.id)!
 //   reorder.order = index + 1
 //   return reorder
 //  })

 //  setTodoOptions(reordered)
 // }

 function onDragEnd(reorderTodoOptions: TodoOptionType[]) {
  const reordered = reorderTodoOptions.map((reorderOption, index) => {
   const existingTodoOption = todoOptions.find(
    (it) => it.id === reorderOption.id,
   )!
   const updatedTodoOption = {
    ...existingTodoOption,
    order: index + 1,
   }
   return updatedTodoOption
  })

  setTodoOptions(reordered)
 }

 // const renderItem = ({
 //  item: todoOption,
 //  isActive,
 //  drag,
 // }: RenderItemParams<TodoOptionType>) => {
 //  return (
 //   <View style={styles.checkboxWrapp} key={todoOption.id}>
 //    <View style={{ flexDirection: "row", gap: 20 }}>
 //     <TouchableOpacity
 //      onLongPress={() => {
 //       drag()
 //      }}
 //     >
 //      {isActive ? (
 //       <Icon name="fas fa-grid-round" size={18} />
 //      ) : (
 //       <Icon name="fal fa-grip-lines" size={18} />
 //      )}
 //     </TouchableOpacity>
 //     <Checkbox
 //      checked={todoOption.isChecked}
 //      onClick={(isChecked) => remoteUpdateTodo(todoOption, isChecked)}
 //     />
 //    </View>
 //    <View
 //     style={{
 //      flexDirection: "row",
 //      justifyContent: "space-between",
 //      flexGrow: 1,
 //      paddingLeft: 20,
 //      flex: 1,
 //     }}
 //    >
 //     <StyledText
 //      testID={`${testID}.todo.${todoOption.order}`}
 //      onLongPress={drag}
 //      style={{
 //       fontSize: 16,
 //       fontWeight: "400",
 //       color: "#000",
 //       fontFamily: "Source Sans Pro",
 //       width: "95%",
 //      }}
 //     >
 //      {todoOption.name}
 //     </StyledText>
 //     <View style={{ position: "relative", right: -5 }}>
 //      <Pressable testID={`${testID}.${todoOption.order}.editIcon`}>
 //       <MenuOpener
 //        content={openTodoPopup(todoOption)}
 //        style={{ marginLeft: -20 }}
 //       >
 //        <Icon name="far fa-ellipsis-vertical" height={16} width={4} />
 //       </MenuOpener>
 //      </Pressable>
 //     </View>
 //    </View>
 //   </View>
 //  )
 // }

 const renderItem = ({
  item,
  drag,
  isActive,
 }: RenderItemParams<TodoOptionType>) => {
  return (
   <View style={styles.folder}>
    <View
     style={{
      flex: 1,
      flexDirection: "row",
      gap: 10,
      alignItems: "center",
     }}
    >
     <TouchableOpacity
      onLongPress={() => {
       console.log("====================================")
       console.log("123333333", todoOptions)
       console.log("====================================")
       drag()
      }}
     >
      {isActive ? (
       <Icon
        name="fa-solid fa-grid-round"
        bald={true}
        size={16}
        fill={AppColors.textSecondaryGray}
       />
      ) : (
       <Icon
        bald={true}
        name="fa-sharp fa-light fa-grip-lines"
        size={16}
        fill={AppColors.textSecondaryGray}
       />
      )}
     </TouchableOpacity>
     <View style={styles.folderContent}>
      <StyledText
       numberOfLines={1}
       ellipsizeMode="tail"
       style={styles.folderName}
      >
       {item.name}
      </StyledText>
     </View>
    </View>

    <MenuOpener
     position="bottom-left"
     // content={<MessageBoardCardInfoPopup todoOption={item} />}
     content={openTodoPopup(item)}
    >
     <Icon
      name="fa-regular fa-ellipsis-vertical"
      size={18}
      fill={AppColors.textSecondaryGray}
     />
    </MenuOpener>
   </View>
  )
 }

 function addTodoItem() {
  modal.open({
   component: (
    <View style={{ backgroundColor: AppColors.light }}>
     <View style={{ position: "relative" }}>
      {/* <SvgXml xml={bgHeaderModal} /> */}
      <StyledText
       style={{
        position: "absolute",
        fontFamily: "Source Sans Pro",
        fontSize: 24,
        fontStyle: "normal",
        fontWeight: "600",
        left: 20,
        top: 29,
       }}
      >
       Todos
      </StyledText>
     </View>
     <View
      style={{
       backgroundColor: AppColors.light,
       paddingBottom: 20,
       paddingHorizontal: 20,
      }}
     >
      {todoOptions.length > 0 && (
       <View style={styles.todoList}>
        <NestableScrollContainer>
         <NestableDraggableFlatList
          contentContainerStyle={{ gap: 10 }}
          data={todoOptions}
          renderItem={renderItem}
          onDragBegin={() => {
           setIsDisableScrollInDrag(false)
          }}
          keyExtractor={(item) => item.id}
          onDragEnd={({ data }) => {
           onDragEnd(data)
           setIsDisableScrollInDrag(true)
          }}
         />
        </NestableScrollContainer>
       </View>
      )}
      <View
       style={{
        backgroundColor: updateTodo?.name
         ? AppColors.backgroundLight
         : "transparent",
        marginHorizontal: -20,
        paddingHorizontal: 20,
        paddingVertical: 10,
       }}
      >
       <View
        style={{
         flexDirection: "row",
         marginBottom: 10,
         gap: 10,
         display: updateTodo?.name ? "flex" : "none",
         justifyContent: "space-between",
         width: "100%",
        }}
       >
        <View
         style={{
          flexDirection: "row",
          gap: 10,
         }}
        >
         <View
          style={{
           flexDirection: "row",
           gap: 15,
           alignItems: "center",
          }}
         >
          <SvgXml xml={pencilIcon(AppColors.iconDefault)} />
          <SvgXml xml={bigVerticalLienForTodoEdit()} />
         </View>
         <View
          style={{
           justifyContent: "space-between",
          }}
         >
          <StyledText
           style={{ color: AppColors.iconDefault, fontSize: 16 }}
          >
           Edit
          </StyledText>
          <StyledText
           style={{
            color: "#000",
            fontSize: 14,
            fontWeight: "400",
            flexWrap: "wrap",
           }}
          >
           {updateTodo?.name}
          </StyledText>
         </View>
        </View>
        <Pressable
         onPress={() => {
          setUpdateTodo({
           id: "",
           name: "",
           isChecked: false,
           order: 0,
          })
          setName("")
         }}
         style={{ justifyContent: "center" }}
        >
         <Icon name="far fa-xmark" height={16} width={10} />
        </Pressable>
       </View>
       <Input
        testID={`${testID}.addTodoItemInput`}
        placeholder="Write a title"
        value={name}
        onChangeText={setName}
        autoFocus={true}
        wrapperStyle={{ backgroundColor: AppColors.light }}
       />
      </View>
      <View style={styles.btnBox}>
       <Button
        containerStyle={{ width: 91 }}
        onPress={() => {
         if (!updateTodo?.name) {
          saveTodo()
         } else {
          remoteUpdateNameTodo(updateTodo.id, name)
          setUpdateTodo({
           id: "",
           name: "",
           isChecked: false,
           order: 0,
          })
         }
        }}
       >
        {updateTodo?.name ? "Save" : "Add"}
       </Button>
      </View>
      {/* <SvgXml
       xml={bgSVG}
       style={{
        position: "absolute",
        left: 0,
        bottom: 0,
        zIndex: -1,
       }}
      /> */}
     </View>
    </View>
   ),
   footer: "rgb",
   keyboard: 220,
  })
 }

 // ---------------------------------------------------------------------------
 return (
  <View style={styles.todoWrapper}>
   <View
    style={{
     flexDirection: "row",
     justifyContent: "space-between",
     alignItems: "center",
     marginBottom: 20,
    }}
   >
    <StyledText style={styles.title}>Todos</StyledText>
    <Pressable
     style={{
      display: todoOptions.length > 0 ? "flex" : "none",
     }}
     onPress={() => addTodoItem()}
    >
     <SvgXml xml={pencilIcon(AppColors.iconDefault)} />
    </Pressable>
   </View>
   {todoOptions.length > 0 ? (
    <View style={[styles.todoList, { gap: 5 }]}>
     {todoOptions.map((todo) => (
      <View style={styles.checkboxWrapp} key={todo.id}>
       <View style={{ flexDirection: "row", gap: 20 }}>
        <Checkbox
         checked={todo.isChecked}
         onClick={(isChecked) => remoteUpdateTodo(todo, isChecked)}
        />
       </View>
       <View
        style={{
         flexDirection: "row",
         justifyContent: "space-between",
         flexGrow: 1,
         paddingLeft: 20,
         flex: 1,
        }}
       >
        <StyledText
         testID={`${testID}.todo.${todo.order}`}
         style={{
          fontSize: 16,
          fontWeight: "400",
          color: "#000",
          fontFamily: "Source Sans Pro",
          width: "95%",
         }}
        >
         {todo.name}
        </StyledText>
       </View>
      </View>
     ))}
    </View>
   ) : (
    <Button
     onPress={() => addTodoItem()}
     type="outline-small"
     containerStyle={{ width: 150 }}
     icon="plus"
    >
     Add todo item
    </Button>
   )}
  </View>
 )
}
why this <Input
        testID={`${testID}.addTodoItemInput`}
        placeholder="Write a title"
        value={name}
        onChangeText={setName}
        autoFocus={true}
        wrapperStyle={{ backgroundColor: AppColors.light }}
       /> is uncontrolled ? Please fix it ?