import React from 'react';
import {
  Text,
  View,
  TouchableOpacity,
  Image,
  ScrollView,
  FlatList,
  Modal,
  LogBox,
  TextInput,
} from 'react-native';
import R from '../../../assets/R';
import styles from './style';
import Header from '../../../components/Header/Header';
import TextMulti from '../../../components/Input/TextMulti';
import FAB from '../../../components/FAB/fab';
import SubButton from '../../../components/FAB/sub_button';
import TextField from '../../../components/Input/TextField';
import Dropdown from '../../../components/DropdownAlert/Dropdown';

const DetailIncomingDocumentView = props => {
  const {
    icomingDocument,
    items,
    dataList,
    showModal,
    setShowModal,
    showTaskModal,
    setShowTaskModal,
    annotationContent,
    setAnnotationContent,
    taskTitle,
    setTaskTitle,
    taskDescription,
    setTaskDescription,
    taskCategory,
    setTaskCategory,
    taskDeadline,
    setTaskDeadline,
    taskFollower,
    setTaskFollower,
    taskExecutor,
    setTaskExecutor,
    selectedTags,
    selectedFollowers,
    selectedExecutors,
    errors,
    isSubmitting,
    handleAddAnnotation,
    handleCreateTask,
    handleAddTag,
    handleRemoveTag,
    handleAddFollower,
    handleRemoveFollower,
    handleAddExecutor,
    handleRemoveExecutor,
  } = props;

  LogBox.ignoreLogs(['VirtualizedLists should never be nested']);

  const getColor = status => {
    switch (status) {
      case 'Hạn chế':
        return R.colors.brown;
      case 'Công khai':
        return R.colors.blue;
    }
  };

  const renderItem = ({item}) => {
    console.log(item);
    return (
      <View style={styles.renderItemContainer}>
        <View style={styles.renderItemHeader}>
          <Text style={styles.text}>{item.author} - </Text>
          <Text style={styles.text}>{item.code} </Text>
          <Text style={styles.text}>{item.time} </Text>
          <Text style={styles.text}>{item.date}</Text>
        </View>
        <View style={styles.containerContent}>
          <Text style={styles.text_2}>{item.content}</Text>
        </View>
      </View>
    );
  };

  const body = () => {
    return (
      <ScrollView showsVerticalScrollIndicator={false}>
        <View style={styles.body}>
          <Text style={styles.textSubTitle}>{icomingDocument.title}</Text>
          <View style={styles.marginTop5}></View>
          <View style={styles.headerRow}>
            <Text style={styles.text_1}>
              Văn bản hiện có {icomingDocument.total_head_of_work} công việc
              liên {'\n'}quan
            </Text>
            <Text style={styles.text}>
              Chế độ:
              <Text
                style={[
                  styles.statusText,
                  {color: getColor(icomingDocument.status)},
                ]}>
                {icomingDocument.status}
              </Text>
            </Text>
          </View>
          <View style={styles.infoRow}>
            <Text style={styles.text}>
              Số ký hiệu:{' '}
              <Text style={styles.text_2}>{icomingDocument.symbol_number}</Text>
            </Text>
            <Text style={styles.text}>
              Số vào sổ:{' '}
              <Text style={styles.text_2}>
                {icomingDocument.number_entry_book}
              </Text>
            </Text>
          </View>
          <View style={styles.infoRow}>
            <Text style={styles.text}>
              Ngày đến:{' '}
              <Text style={styles.text_2}>{icomingDocument.term}</Text>
            </Text>
            <Text style={styles.text}>
              Ngày văn bản:{' '}
              <Text style={styles.text_2}>{icomingDocument.term_display}</Text>
            </Text>
          </View>
          <Text style={[styles.text, styles.textWithMargin]}>
            Loại văn bản:
            <Text style={styles.text_2}>{icomingDocument.document_type}</Text>
          </Text>
          <Text style={[styles.text, styles.textWithMargin]}>
            Lĩnh vực văn bản:
            <Text style={styles.text_2}>{icomingDocument.field}</Text>
          </Text>
          <View style={styles.signerContainer}>
            <Text style={styles.text}>
              Người ký:{' '}
              <Text style={styles.text_2}>{icomingDocument.signer_name}</Text>
            </Text>
            <Text style={styles.text}>
              Đối tác gửi:{' '}
              <Text style={styles.text_2}>
                {icomingDocument.sender_partner}
              </Text>
            </Text>
          </View>
          <TextMulti title="Ghi chú" />
          <View style={styles.marginTop5}></View>
          <Text style={[styles.text, styles.textWithMargin]}>Nội dung</Text>
          <View style={[styles.containerContent, styles.textWithMargin]}>
            <Text style={styles.text_2}>{icomingDocument.content}</Text>
          </View>
          <Text style={[styles.text, styles.textWithMargin]}>
            Ý kiến của BGH:
            <Text style={styles.text_2}>{icomingDocument.opinion_bgh}</Text>
          </Text>
          <View style={styles.departmentRow}>
            <Text style={styles.text}>Phòng ban nhận :</Text>
            {icomingDocument.received_departments.map((item, index) => {
              return (
                <View style={styles.card}>
                  <Text style={styles.cardText} key={index}>
                    {item.name}
                  </Text>
                </View>
              );
            })}
          </View>
          <View style={styles.departmentRow}>
            <Text style={styles.text}>Nhóm nhận :</Text>
            {icomingDocument.received_group.map((item, index) => {
              return (
                <View style={[styles.card, {backgroundColor: R.colors.blue}]}>
                  <Text style={styles.cardText} key={index}>
                    {item.name}
                  </Text>
                </View>
              );
            })}
          </View>

          <View style={styles.departmentRow}>
            <Text style={styles.text}>Người nhận :</Text>
            {icomingDocument.receiver.map((item, index) => {
              return (
                <View style={[styles.card, {backgroundColor: R.colors.blue}]}>
                  <Text style={styles.cardText} key={index}>
                    {item.name}
                  </Text>
                </View>
              );
            })}
          </View>

          <Text style={[styles.text, {color: R.colors.blue}]}>
            Tài liệu đính kèm
          </Text>

          <TouchableOpacity style={styles.containerBtn}>
            <Text style={styles.textBtn}>
              Quyết định thông báo đào tạo - QD347583
            </Text>
            <Image
              source={R.images.icDownload}
              style={styles.downloadIcon}
              resizeMode="contain"
              tintColor={R.colors.blue}
            />
          </TouchableOpacity>

          <Text style={[styles.text, {color: R.colors.blue}]}>
            Bút phê văn bản
          </Text>

          <FlatList
            data={icomingDocument.approvals}
            renderItem={renderItem}
            keyExtractor={(item, index) => index.toString()}
          />
        </View>
      </ScrollView>
    );
  };

  const renderItem_1 = ({item, onPress}) => {
    return (
      <View style={styles.chip}>
        <TouchableOpacity style={styles.containerIcon} onPress={onPress}>
          <Image
            resizeMode="cover"
            source={R.images.icCancel}
            style={styles.imageIcon}
            tintColor={R.colors.blue}
          />
        </TouchableOpacity>
        <Text style={styles.textChip}> {`${item.id}, ${item.name}`}</Text>
      </View>
    );
  };

  const openModal = () => {
    return (
      <Modal
        animationType="slide"
        transparent={true}
        visible={showModal}
        onRequestClose={() => setShowModal(false)}>
        <View style={styles.modalOverlay}>
          <View style={styles.modalContainer}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>Thêm bút phê</Text>
            </View>
            <View style={styles.modalBody}>
              <Text style={styles.inputLabel}>Bút phê</Text>
              <TextInput
                style={styles.textInput}
                placeholder="Nhập nội dung bút phê..."
                placeholderTextColor={R.colors.gray}
                multiline={true}
                numberOfLines={3}
                textAlignVertical="top"
                value={annotationContent}
                onChangeText={setAnnotationContent}
              />
            </View>

            <View style={styles.modalFooter}>
              <TouchableOpacity
                style={[styles.button, styles.cancelButton]}
                onPress={() => setShowModal(false)}>
                <Text style={styles.cancelButtonText}>Hủy</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.button, styles.submitButton]}
                onPress={handleAddAnnotation}>
                <Text style={styles.submitButtonText}>Thêm mới</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    );
  };

  const openTaskModal = () => {
    return (
      <Modal
        animationType="slide"
        transparent={true}
        visible={showTaskModal}
        onRequestClose={() => setShowTaskModal(false)}>
        <View style={styles.modalOverlay}>
          <View style={[styles.modalContainer, styles.modalContainerLarge]}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>Thêm công việc</Text>
            </View>
            <ScrollView
              style={styles.modalBody}
              showsVerticalScrollIndicator={false}>
              <TextField
                title="Tiêu đề"
                fontSizeTitle={R.fontsize.fontSizeLabel}
                required
                placeholder="Nhập tiêu đề công việc"
                placeholderTextColor={R.colors.gray}
                value={taskTitle}
                onChangeText={setTaskTitle}
                containerMarginBottom={10}
                error={errors.taskTitle}
              />

              <TextMulti
                title="Mô tả"
                titleFontSize={R.fontsize.fontSizeLabel}
                placeholder="Nhập mô tả công việc..."
                placeholderTextColor={R.colors.gray}
                multiline={true}
                numberOfLines={3}
                required
                value={taskDescription}
                onChangeText={setTaskDescription}
                error={errors.taskDescription}
              />
              <View style={styles.containerDropdown}>
                <Text style={[styles.text, styles.dropdownLabel]}>Thẻ</Text>
                <Dropdown
                  height={35}
                  items={items}
                  placeholder="Chọn thẻ"
                  onSelect={handleAddTag}
                />
              </View>
              <Text style={[styles.text_2, styles.dropdownLabel]}>
                Danh sách thẻ đã chọn :
              </Text>
              <FlatList
                data={selectedTags}
                renderItem={({item}) =>
                  renderItem_1({item, onPress: () => handleRemoveTag(item.id)})
                }
                keyExtractor={(item, index) =>
                  item.id?.toString() || index.toString()
                }
                numColumns={2}
                style={styles.flatListContainer}
                showsVerticalScrollIndicator={true}
                columnWrapperStyle={styles.flatListSelect}
                nestedScrollEnabled={true}
                scrollEnabled={true}
              />
              <TextField
                title="Ngày đến hạn"
                required
                fontSizeTitle={R.fontsize.fontSizeLabel}
                placeholder="DD/MM/YYYY"
                value={taskDeadline}
                onChangeText={setTaskDeadline}
                error={errors.taskDeadline}
              />

              <View style={styles.containerDropdown}>
                <Text style={[styles.text, styles.dropdownLabel]}>
                  Người theo dõi {''}
                  <Text style={styles.redText}>*</Text>
                </Text>
                <Dropdown
                  height={35}
                  items={items}
                  placeholder="Chọn người theo dõi"
                  onSelect={handleAddFollower}
                />
              </View>
              <Text style={[styles.text_2, styles.dropdownLabel]}>
                Danh sách người theo dõi đã chọn :
              </Text>
              <FlatList
                data={selectedFollowers}
                renderItem={({item}) =>
                  renderItem_1({
                    item,
                    onPress: () => handleRemoveFollower(item.id),
                  })
                }
                keyExtractor={(item, index) =>
                  item.id?.toString() || index.toString()
                }
                numColumns={2}
                style={styles.flatListContainer}
                showsVerticalScrollIndicator={true}
                columnWrapperStyle={styles.flatListSelect}
                nestedScrollEnabled={true}
                scrollEnabled={true}
              />
              <View style={styles.containerDropdown}>
                <Text style={[styles.text, styles.dropdownLabel]}>
                  Người thực hiện công việc{' '}
                  <Text style={styles.redText}>*</Text>
                </Text>
                <Dropdown
                  height={35}
                  items={items}
                  placeholder="Chọn người thực hiện"
                  onSelect={handleAddExecutor}
                />
              </View>
              <Text style={[styles.text_2, styles.dropdownLabel]}>
                Danh sách người thực hiện công việc đã chọn :
              </Text>
              <FlatList
                data={selectedExecutors}
                renderItem={({item}) =>
                  renderItem_1({
                    item,
                    onPress: () => handleRemoveExecutor(item.id),
                  })
                }
                keyExtractor={(item, index) =>
                  item.id?.toString() || index.toString()
                }
                numColumns={2}
                style={styles.flatListContainer}
                showsVerticalScrollIndicator={true}
                columnWrapperStyle={styles.flatListSelect}
                nestedScrollEnabled={true}
                scrollEnabled={true}
              />
            </ScrollView>

            <View style={styles.modalFooter}>
              <TouchableOpacity
                style={[styles.button, styles.cancelButton]}
                onPress={() => {
                  setShowTaskModal(false);
                }}>
                <Text style={styles.cancelButtonText}>Hủy</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[
                  styles.button,
                  styles.submitButton,
                  isSubmitting && {opacity: 0.6},
                ]}
                onPress={handleCreateTask}
                disabled={isSubmitting}>
                <Text style={styles.submitButtonText}>
                  {isSubmitting ? 'Đang tạo...' : 'Thêm mới'}
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    );
  };

  return (
    <View style={styles.container}>
      <Header title={'Văn bản 2038475'} isBack />
      <View style={styles.flex1}>
        {body()}
        <View style={styles.marginHorizontal15}>
          <FAB>
            <SubButton
              onPress={() => setShowModal(true)}
              label="Thêm bút phê"
              images={R.images.icEdit}
              backgroundColor={R.colors.orange}
            />
            <SubButton
              onPress={() => setShowTaskModal(true)}
              label="Tạo công việc"
              images={R.images.icMenuEdit}
              backgroundColor={R.colors.blue}
            />
          </FAB>
        </View>
      </View>
      {openModal()}
      {openTaskModal()}
    </View>
  );
};

export default DetailIncomingDocumentView;
