/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/camelcase */
/* eslint-disable react-native/no-inline-styles */
import { Icon } from 'react-native-elements';
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, TouchableOpacity, Image } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import apiThongTinLuotKhamMoiNhat from 'app/api/methods/getthongtinluotkhammoinhat';
import { useTranslation } from 'react-i18next';
import HeaderComponent from 'app/components/HeaderComponent';
import { scale, verticalScale, moderateScale } from 'react-native-size-matters';
import * as navigationActions from 'app/navigation/NavigationService';
import { useFocusEffect } from '@react-navigation/native';
import apiKhamList from 'app/api/methods/getkhams';
import ThongTinLuotKham from 'app/components/ThongTinLuotKham';
import _, { lte } from 'lodash';
import LuotKhamComponent from '../components/LuotKhamComponent';
import ButtonDonThuocComponent from '../components/ButtonDonThuocComponent';
import ButtonDanhSachLuotKhamComponent from '../components/ButtonDanhSachLuotKhamComponent';
import ButtonKetQuaDieuTriComponent from '../components/ButtonKetQuaDieuTriComponent';
import apiThongTinLuotKham from 'app/api/methods/thongtinluotkham';
import Spinner from 'react-native-loading-spinner-overlay';

export default function Patient({ route, navigation }) {
  const dispatch = useDispatch();

  // const ID_BenhNhan = 597882;
  const [ID_BenhNhan, setID_BenhNhan] = useState();
  const [ID_LuotKham, setID_LuotKham] = useState();
  const [ID_MedicalReport_New, setID_MedicalReport_New] = useState();

  const [luotkham, setLuotkham] = useState([]);
  const [kham, setKham] = useState([]);
  const { t, i18n } = useTranslation();
  const [isFlag, setIsFlag] = useState(true);

  const renderSeparator = () => (
    <View
      style={{
        backgroundColor: 'black',
        height: 0.5,
      }}
    />
  );
  function renderItem({ item, index, separators }) {
    let styleTenLoaiKham;

    if (item.ID_TrangThai == 'Xong') {
      styleTenLoaiKham = { color: '#0FA5A9' };
    } else {
      styleTenLoaiKham = { color: 'black' };
    }
    return <LuotKhamComponent styleTenLoaiKham={styleTenLoaiKham} ID_BenhNhan={ID_BenhNhan} {...item} />;
  }

  // useFocusEffect(
  //   React.useCallback(() => {
  //     console.log(1);
  //     const { ID_BenhNhan,ID_LuotKham } = route.params;
  //     const fetchData = async () => {
  //       console.log(ID_BenhNhan,ID_LuotKham);
  //       const response = await apiThongTinLuotKhamMoiNhat(ID_BenhNhan);
  //       setLuotkham(response);
  //       const kham = await apiKhamList(response.ID_LuotKham);
  //       setKham(kham);
  //     };

  //     return () => fetchData();
  //   }, [route.params])
  // );
  useEffect(() => {
    const fetchData = async () => {
      navigation.addListener('focus', async (payload) => {
        const routes = navigation.dangerouslyGetState().routes;
        for (let i = 0; i < navigation.dangerouslyGetState().routes.length; i++) {
          if (routes[i].name === 'hosoyte') {
            const { ID_BenhNhan, ID_LuotKham } = routes[i].params;

            setID_BenhNhan(ID_BenhNhan);
            setID_LuotKham(ID_LuotKham);
            let response;
            console.log(!ID_LuotKham);
            if (ID_LuotKham) {
              response = await apiThongTinLuotKham(ID_LuotKham);
            } else {
              response = await apiThongTinLuotKhamMoiNhat(ID_BenhNhan);
            }
            setLuotkham(response);

            console.log(response);
            setID_MedicalReport_New(response);
            const kham = await apiKhamList(response.ID_LuotKham);
            setKham(kham);
            setIsFlag(false);
            break;
          }
        }
      });
    };
    // unsubscribe();
    // return fetchData;
    fetchData();
  }, [navigation]);

  // useEffect(() => {
  //   const fetchData = async () => {
  //     const response = await apiThongTinLuotKhamMoiNhat(ID_BenhNhan);
  //     setLuotkham(response);
  //     const kham = await apiKhamList(response.ID_LuotKham);
  //     setKham(kham);
  //   };
  //   fetchData();
  // }, [ID_BenhNhan]);

  if (!luotkham) {
    return (
      <>
        <HeaderComponent />
        <View
          style={{
            flex: 1,
            marginTop: moderateScale(15),
            paddingHorizontal: moderateScale(10),
          }}>
        <Spinner visible={isFlag} />

          <View
            style={{
              flexDirection: 'row',
              paddingBottom: moderateScale(10),
              borderBottomWidth: 2,
              borderColor: '#CCCCCD',
              justifyContent: 'center',
            }}>
            <View
              style={{
                flex: 0.4,
                flexDirection: 'row',
                justifyContent: 'center',
              }}>
              <View
                style={{
                  alignItems: 'center',
                }}>
                <View
                  style={{
                    borderWidth: moderateScale(8),
                    borderColor: '#0FA5A9',
                    borderRadius: 100,
                    padding: moderateScale(25),
                  }}>
                  <Text
                    style={{ fontSize: moderateScale(25), fontWeight: 'bold' }}>
                    LH
                  </Text>
                  {/* )} */}
                </View>
                <Text
                  style={{
                    marginTop: 8,
                    fontWeight: 'bold',
                    textAlign: 'center',
                  }}>
                  Lê Văn Hưng
                </Text>
              </View>
            </View>
          </View>
          <View
            style={{
              backgroundColor: '#EDEDED',
              padding: moderateScale(10),
              marginTop: moderateScale(30),
              position: 'relative',
            }}>
            <View
              style={{
                position: 'absolute',
                top: moderateScale(-20),
                right: 0,
              }}>
              <Icon
                name="chatbubble-ellipses-outline"
                type="ionicon"
                color="#0FA5A9"
                size={moderateScale(30)}
              />
            </View>
            <Text style={{ color: '#0FA5A9' }}>
              Lê Văn Hưng chưa khám tại Family nên chưa có hồ sơ y tế. Family sẽ
              cập nhật hướng dẫn truy cập hồ sơ y tế khi đến khám bạn nhé!
            </Text>
          </View>
        </View>
      </>
    );
  } else {
    return (
      <>
        <HeaderComponent />
        <View
          style={{
            flex: 1,
            marginTop: moderateScale(15),
            paddingHorizontal: moderateScale(10),
          }}>
        <Spinner visible={isFlag} />
          <ThongTinLuotKham {...luotkham} />
          {!luotkham.benhannoitru ?
            <FlatList
              horizontal={false}
              data={kham}
              ItemSeparatorComponent={renderSeparator}
              renderItem={renderItem}
              keyExtractor={(item) => 'id' + item.ID_Kham}
            /> :
            <Text />
          }
          <View
            style={{
              borderTopWidth: 2,
              borderColor: '#CCCCCD',
              paddingVertical: moderateScale(12),
              flexDirection: 'row',
              alignItems: 'center',
              flexWrap: 'wrap',
              justifyContent: 'center',
            }}>
            <ButtonKetQuaDieuTriComponent benhannoitru={luotkham.benhannoitru ? luotkham.benhannoitru : ''} ID_MedicalReport_New={luotkham.medicalreport ? luotkham.medicalreport.ID_MedicalReport : ''} ID_MedicalReport_NT={luotkham.benhannoitru ? luotkham.benhannoitru.medicalreport_noitru.ID_MedicalReport_NT : ''} />
            <ButtonDonThuocComponent benhannoitru={luotkham.benhannoitru ? luotkham.benhannoitru : ''} ID_LuotKham={ID_LuotKham ? ID_LuotKham : ''} ID_BenhNhan={ID_BenhNhan ? ID_BenhNhan : ''} />
            <ButtonDanhSachLuotKhamComponent benhannoitru={luotkham.benhannoitru ? luotkham.benhannoitru : ''} ID_BenhNhan={ID_BenhNhan ? ID_BenhNhan : ''} />
          </View>
        </View>
      </>
    );
  }
}
