import React, {useEffect, useState} from 'react';
import {
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Image,
  ScrollView,
  FlatList,
  Alert,
  Modal,
  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 DetailSendDocumentView = props => {
  const {icomingDocument, items, dataList} = props;
  const [showModal, setShowModal] = useState(false);
  const [showTaskModal, setShowTaskModal] = useState(false);
  const [annotationContent, setAnnotationContent] = useState('');
  const [taskTitle, setTaskTitle] = useState('');
  const [taskDescription, setTaskDescription] = useState('');
  const [taskCategory, setTaskCategory] = useState('Công việc theo văn bản');
  const [taskDeadline, setTaskDeadline] = useState('');
  const [taskFollower, setTaskFollower] = useState('859256, Nguyễn Minh Đức');
  const [taskExecutor, setTaskExecutor] = useState('859256, Nguyễn Minh Đức');
  const getColor = status => {
    switch (status) {
      case 'Hạn chế':
        return R.colors.brown;
      case 'Công khai':
        return R.colors.blue;
    }
  };
  const getColorRegime = regime => {
    switch (regime) {
      case 'Đã phê duyệt':
        return R.colors.green;
      case 'Chờ xét duyệt':
        return R.colors.blue;
      case 'Cần chỉnh sửa':
        return R.colors.orange;
      case 'Dự thảo':
        return R.colors.orange;
    }
  }
  const renderItem = ({item}) => {
    console.log(item);
    return (
      <View style={{marginVertical: 7.5}}>
        <View style={{flexDirection: 'row', marginBottom: 5}}>
          <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={{marginTop: 5}}></View>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: 5,
            }}>
           
            <Text style={styles.text}>
              Chế độ:{" "}
              <Text
                style={{
                  fontWeight: '600',
                  fontFamily: R.fonts.fontMedium,
                  fontSize: R.fontsize.fontSizeContent,
                  color: getColor(icomingDocument.status),
                }}>
                {icomingDocument.status}
              </Text>
            </Text>

            <Text style={styles.text}>
              Trạng thái:{" "}
              <Text style={[styles.text_2 , {color:R.colors.green}]}>{icomingDocument.regime}</Text>
            </Text>
          </View>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              marginBottom: 5,
            }}>
            <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={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              marginBottom: 5,
            }}>
            <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, {marginBottom: 5}]}>
            Loại văn bản:
            <Text style={styles.text_2}>{icomingDocument.document_type}</Text>
          </Text>
          <Text style={[styles.text, {marginBottom: 5}]}>
            Lĩnh vực văn bản:
            <Text style={styles.text_2}>{icomingDocument.field}</Text>
          </Text>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              marginBottom: 5,
            }}>
            <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={{marginTop: 5}}></View>
          <Text style={[styles.text, {marginBottom: 3}]}>Nội dung</Text>
          <View style={[styles.containerContent, {marginBottom: 5}]}>
            <Text style={styles.text_2}>{icomingDocument.content}</Text>
          </View>
          <Text style={[styles.text, {marginBottom: 5}]}>
            Ý kiến của BGH:
            <Text style={styles.text_2}>{icomingDocument.opinion_bgh}</Text>
          </Text>
          <View
            style={{
              flexDirection: 'row',
              flexWrap: 'wrap',
              alignItems: 'center',
              marginBottom: 5,
            }}>
            <Text style={styles.text}>Phòng ban nhận :</Text>
            {icomingDocument.received_departments.map((item, index) => {
              return (
                <View style={styles.card}>
                  <Text
                    style={{
                      color: R.colors.white,
                      fontSize: R.fontsize.fontSizeContent,
                    }}
                    key={index}>
                    {item.name}
                  </Text>
                </View>
              );
            })}
          </View>
          <View
            style={{
              flexDirection: 'row',
              flexWrap: 'wrap',
              alignItems: 'center',
              marginBottom: 5,
            }}>
            <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={{
                      color: R.colors.white,
                      fontSize: R.fontsize.fontSizeContent,
                    }}
                    key={index}>
                    {item.name}
                  </Text>
                </View>
              );
            })}
          </View>

          <View
            style={{
              flexDirection: 'row',
              flexWrap: 'wrap',
              alignItems: 'center',
              marginBottom: 5,
            }}>
            <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={{
                      color: R.colors.white,
                      fontSize: R.fontsize.fontSizeContent,
                    }}
                    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={{width: 20, height: 20}}
              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 handleCreateTask = () => {
    if (taskTitle.trim() && taskDescription.trim()) {
      Alert.alert('Thành công', 'Đã tạo công việc thành công!');
      setTaskTitle('');
      setTaskDescription('');
      setTaskDeadline('');
      setShowTaskModal(false);
    } else {
      Alert.alert('Lỗi', 'Vui lòng nhập đầy đủ thông tin!');
    }
  };
  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 openTaskModal = () => {
    return (
      <Modal
        animationType="slide"
        transparent={true}
        visible={showTaskModal}
        onRequestClose={() => setShowTaskModal(false)}>
        <View style={styles.modalOverlay}>
          <View style={[styles.modalContainer, {maxHeight: '90%'}]}>
            <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="HS"
                placeholderTextColor={R.colors.gray}
                value={taskTitle}
                onChangeText={setTaskTitle}
                containerMarginBottom={10}
              />

              <TextMulti
                title="Mô tả"
                titleFontSize={R.fontsize.fontSizeLabel}
                placeholder="Nhập mô tả..."
                placeholderTextColor={R.colors.gray}
                multiline={true}
                numberOfLines={3}
                required
                value={taskDescription}
                onChangeText={setTaskDescription}
              />
              <View style={styles.containerDropdown}>
                <Text
                  style={[
                    styles.text,
                    {
                      marginBottom: 3,
                      fontSize: R.fontsize.fontSizeLabel,
                      fontFamily: R.fonts.fontRegular,
                      fontWeight: '400',
                      color: R.colors.black,
                    },
                  ]}>
                  Thẻ
                </Text>
                <Dropdown
                  height={35}
                  items={items}
                  placeholder="Chọn tùy chọn"
                  onSelect={item => console.log('Bạn đã chọn:', item)}
                />
              </View>
              <Text style={[styles.text_2, {marginBottom: 3}]}>
                Danh sách thẻ đã chọn :
              </Text>
              <FlatList
                data={dataList}
                renderItem={({item}) => renderItem_1({item, onPress: () => {}})}
                keyExtractor={(item, index) =>
                  item.id?.toString() || index.toString()
                }
                numColumns={2}
                style={{maxHeight: 150, marginBottom: 10}}
                showsVerticalScrollIndicator={true}
                columnWrapperStyle={styles.flatListSelect}
                nestedScrollEnabled={true}
                scrollEnabled={true}
              />
              <TextField
                title="Ngày đến hạn"
                required
                fontSizeTitle={R.fontsize.fontSizeLabel}
                value={taskDeadline}
                onChangeText={setTaskDeadline}
              />

              <View style={styles.containerDropdown}>
                <Text
                  style={[
                    styles.text,
                    {
                      marginBottom: 3,
                      fontSize: R.fontsize.fontSizeLabel,
                      fontFamily: R.fonts.fontRegular,
                      fontWeight: '400',
                      color: R.colors.black,
                    },
                  ]}>
                  Người theo dõi {''}
                  <Text style={{color: R.colors.red}}>*</Text>
                </Text>
                <Dropdown
                  height={35}
                  items={items}
                  placeholder="Chọn tùy chọn"
                  onSelect={item => console.log('Bạn đã chọn:', item)}
                />
              </View>
              <Text style={[styles.text_2, {marginBottom: 3}]}>
                Danh sách người theo dõi đã chọn :
              </Text>
              <FlatList
                data={dataList}
                renderItem={({item}) => renderItem_1({item, onPress: () => {}})}
                keyExtractor={(item, index) =>
                  item.id?.toString() || index.toString()
                }
                numColumns={2}
                style={{maxHeight: 150, marginBottom: 10}}
                showsVerticalScrollIndicator={true}
                columnWrapperStyle={styles.flatListSelect}
                nestedScrollEnabled={true}
                scrollEnabled={true}
              />
              <View style={styles.containerDropdown}>
                <Text
                  style={[
                    styles.text,
                    {
                      marginBottom: 3,
                      fontSize: R.fontsize.fontSizeLabel,
                      fontFamily: R.fonts.fontRegular,
                      fontWeight: '400',
                      color: R.colors.black,
                    },
                  ]}>
                  Người thực hiện công việc{' '}
                  <Text style={{color: R.colors.red}}>*</Text>
                </Text>
                <Dropdown
                  height={35}
                  items={items}
                  placeholder="Chọn tùy chọn"
                  onSelect={item => console.log('Bạn đã chọn:', item)}
                />
              </View>
              <Text style={[styles.text_2, {marginBottom: 3}]}>
                Danh sách người thực hiện công việc đã chọn :
              </Text>
              <FlatList
                data={dataList}
                renderItem={({item}) => renderItem_1({item, onPress: () => {}})}
                keyExtractor={(item, index) =>
                  item.id?.toString() || index.toString()
                }
                numColumns={2}
                style={{maxHeight: 150, marginBottom: 10}}
                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]}
                onPress={handleCreateTask}>
                <Text style={styles.submitButtonText}>Thêm mới</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    );
  };
  return (
    <View style={styles.container}>
      <Header title={'Văn bản đi 2038475'} isBack />
      <View style={{flex: 1}}>
        {body()}
        <View style={{marginHorizontal: 15}}>
          <FAB>
            <SubButton
              onPress={() => setShowTaskModal(true)}
              label="Tạo công việc"
              images={R.images.icMenuEdit}
              backgroundColor={R.colors.blue}
            />
          </FAB>
        </View>
      </View>
      {openTaskModal()}
    </View>
  );
};

export default DetailSendDocumentView;
