import React, { ReactNode, useState } from "react"
import { Platform, Pressable, TextStyle, View } from "react-native"
import { AppAssets } from "../../app/app.assets"
import { Button } from "../button/button.component"
import { Checkbox } from "../checkbox/checkbox.component"
import { EmptyStateLink } from "../empty-state/empty-state-link.component"
import { EmptyState } from "../empty-state/empty-state.component"
import { Input } from "../input/input"
import { MenuItem } from "../menu/index"
import { useModal } from "../modal/modal.hook"
import { Radio } from "../radio/radio.component"
import { StyledText } from "../styled-text/styled-text"
import { useStyles } from "./dropdown.style"
import { AppColors } from "../../app/app.colors"

export function DropdownItemsModal<T>({
  title,
  titleStyles,
  items,
  radio,
  searchNoResultsLabel,
  searchPlaceholder,
  isSelectedAll = false,
  checked,
  checkboxes = true,
  content,
  handleCheckboxChange,
  itemRender,
  onSearch,
  testID,
}: {
  items: T[]
  title: string
  checked: (item: T) => boolean
  checkboxes: boolean
  radio: boolean
  searchNoResultsLabel?: string
  searchPlaceholder?: string
  isSelectedAll?: boolean
  content?: ReactNode
  onSearch?: (items: T[], keyword: string) => T[]
  titleStyles?: TextStyle
  handleCheckboxChange: (item: T) => void
  itemRender: (item: T, checked: boolean) => ReactNode
  testID?: string
}) {
  // ---------------------------------------------------------------------------
  // variables
  // ---------------------------------------------------------------------------
  const styles = useStyles()
  const modal = useModal()

  const [searchKeyword, setSearchKeyword] = useState("")
  const [allSelected, setAllSelected] = useState(false)

  const filteredItems =
    onSearch && searchKeyword ? onSearch(items, searchKeyword) : items

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

  const handleSelectAll = () => {
    filteredItems.forEach((item) => {
      handleCheckboxChange(item)
    })

    setAllSelected(!allSelected)
  }

  // ---------------------------------------------------------------------------
  return (
    <View
      key={filteredItems.length}
      testID={`${testID}.modalContainer`}
      style={styles.dropdownContainer}
    >
      {/* --------------------------------------------------------------------------- */}
      {/* TITLE */}
      {/* --------------------------------------------------------------------------- */}

      {title && title.length > 0 && (
        <StyledText style={[styles.heading, titleStyles]}>{title}</StyledText>
      )}

      {/* --------------------------------------------------------------------------- */}
      {/* INPUT */}
      {/* --------------------------------------------------------------------------- */}

      {onSearch && (
        <View style={styles.inputWrap}>
          <Input
            value={searchKeyword}
            autoFocus
            onChangeText={(text) => setSearchKeyword(text.trim())}
            mode="secondary"
            placeholder={searchPlaceholder}
            showIcon={true}
            type={searchKeyword ? "clear" : "search"}
            onIconPress={() => setSearchKeyword("")}
          />
        </View>
      )}

      {/* --------------------------------------------------------------------------- */}
      {/* SELECT AND UNSELECT ALL ITEMS */}
      {/* --------------------------------------------------------------------------- */}
      {isSelectedAll && (
        <Pressable
          key={Date.now()}
          style={({ pressed }) => ({
            backgroundColor:
              Platform.OS !== "android" && pressed
                ? AppColors.backgroundDark
                : undefined,
            paddingVertical: 8,
            paddingHorizontal: 15,
          })}
          onPress={handleSelectAll}
        >
          <View style={styles.rowCheckboxWrap}>
            <View style={styles.rowCheckbox}>
              <StyledText style={[styles.textMenu]}>
                {allSelected ? "Unselect All" : "Select All"}
              </StyledText>
            </View>

            <Checkbox onClick={handleSelectAll} checked={allSelected} />
          </View>
        </Pressable>
      )}

      {/* --------------------------------------------------------------------------- */}
      {/* ITEMS */}
      {/* --------------------------------------------------------------------------- */}

      {filteredItems.map((item, index) => (
        <View style={styles.menu} key={index}>
          {checkboxes ? (
            <MenuItem
              key={filteredItems.length}
              testID={`${testID}.${index}`}
              onPress={() => {
                handleCheckboxChange(item)
                if (radio) {
                  // modal.close()
                }
              }}
            >
              <View style={styles.rowCheckboxWrap}>
                <View style={styles.rowCheckbox}>
                  <StyledText style={[styles.textMenu]}>
                    {itemRender(item, checked(item))}
                  </StyledText>
                </View>

                {/* --------------------------------------------------------------------------- */}
                {/* RADIO & CHECKBOX */}
                {/* --------------------------------------------------------------------------- */}

                {radio ? (
                  <Radio
                    onClick={() => {
                      handleCheckboxChange(item)
                      modal.close()
                    }}
                    checked={checked(item)}
                  />
                ) : (
                  <Checkbox
                    key={Date.now()}
                    onClick={() => handleCheckboxChange(item)}
                    checked={checked(item)}
                  />
                )}
              </View>
            </MenuItem>
          ) : (
            <Button
              key={filteredItems.length}
              style={[styles.btn, checked(item) ? styles.active : null]}
              onPress={() => handleCheckboxChange(item)}
            >
              <StyledText style={styles.textMenu}>
                {itemRender(item, checked(item))}
              </StyledText>
            </Button>
          )}
        </View>
      ))}

      {content}

      {/* --------------------------------------------------------------------------- */}
      {/* NO SEARCH */}
      {/* --------------------------------------------------------------------------- */}

      {filteredItems.length === 0 && searchKeyword && (
        <EmptyState
          title="Nothing found"
          style={styles.noResultWrapper}
          image={AppAssets.images.dashboardEmptyPhoto}
          description={
            <>
              “{searchKeyword}” {searchNoResultsLabel} {"\n"}
              Press to{" "}
              <EmptyStateLink onPress={() => setSearchKeyword("")}>
                reset
              </EmptyStateLink>{" "}
              search.
            </>
          }
        />
      )}
    </View>
  )
}
when i press allSelect it works as expected but when I open and close modal, the allSelect becomes by default, I want it shows checked or unchecked even I open and close modal. How to do it ?