import React from 'react';
import {
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  Modal,
} from 'react-native';
import styles from './style';
import Header from '../../components/Header/Header';
import R from '../../assets/R';
import Button from '../../components/Button';
import TextField from '../../components/Input/TextField';
import RadioGroup from '../../components/RadioButton/RadioGroup';
import {Camera} from 'react-native-vision-camera';
const ProfileView = props => {
  const {
    dataProfile,

    // camera
    avatarUri,
    onPressSelectImage,
    showCamera,
    cameraRef,
    device,
    onToggleCameraPosition,
    onTakePhoto,
    onCloseCamera,

    // image source modal
    showImageSourceModal,
    onCloseImageSourceModal,
    onSelectCamera,
    onSelectGallery,
    // preview
    showPreview,
    previewUri,
    onConfirmPhoto,
    onRetakePhoto,
    onClosePreview,

    // gallery preview
    recentPhotos,

    selectedValue2,
    options2,
    onValueChange2,
    // TextField states
    phoneNumber,
    setPhoneNumber,
    oldTeacherCode,
    setOldTeacherCode,
    workPlace,
    setWorkPlace,
    position,
    setPosition,
    extraDuty,
    setExtraDuty,
    laborType,
    setLaborType,
    employmentType,
    setEmploymentType,
    appointmentDecision,
    setAppointmentDecision,
    appointmentDate,
    setAppointmentDate,
    issuingAgency,
    setIssuingAgency,
    jobBeforeRecruitment,
    setJobBeforeRecruitment,
    allowanceSeniorityDate,
    setAllowanceSeniorityDate,
    workAllowancePercent,
    setWorkAllowancePercent,
    teacherAllowancePercent,
    setTeacherAllowancePercent,
    teacherType,
    setTeacherType,
    academicUnit,
    setAcademicUnit,
    subjectDepartment,
    setSubjectDepartment,
    employmentStatus,
    setEmploymentStatus,
    workStartDate,
    setWorkStartDate,
    currentContractType,
    setCurrentContractType,
    contractStartDate,
    setContractStartDate,
    contractEndDate,
    setContractEndDate,
    currentContractNumber,
    setCurrentContractNumber,
    contractEffectiveDate,
    setContractEffectiveDate,
    fullTimeWorkStartDate,
    setFullTimeWorkStartDate,
    lastClassificationDate,
    setLastClassificationDate,
    currentWorkAllowancePercent,
    setCurrentWorkAllowancePercent,
    salaryGrade,
    setSalaryGrade,
    currentSalaryLevel,
    setCurrentSalaryLevel,
    currentSalaryCoefficient,
    setCurrentSalaryCoefficient,
    salaryIncreaseMilestone,
    setSalaryIncreaseMilestone,
    lecturerTitle,
    setLecturerTitle,
    // Handlers
    onSave,
  } = props;

  const renderButtonCamera = () => {
    return (
      <Button
        title="Chọn ảnh"
        onPress={onPressSelectImage}
        backgroundColor={R.colors.blue}
        textColor={R.colors.white}
        height={30}
        borderRadius={10}
        fontSize={R.sizes.sm}
        fontWeight={'600'}
        fontFamily={R.fonts.fontMedium}
        paddingHorizontal={15}
        paddingVertical={3}
      />
    );
  };

  const renderPreviewModal = () => {
    return (
      <Modal
        visible={showPreview}
        transparent={false}
        animationType="slide"
        onRequestClose={onClosePreview}>
        <View style={styles.previewContainer}>
          <View style={styles.previewHeader}>
            <TouchableOpacity
              style={styles.previewCloseButton}
              onPress={onClosePreview}>
              <Image
                source={R.images.icClose}
                style={styles.previewCloseIcon}
              />
            </TouchableOpacity>
            <Text style={styles.previewTitle}>Xem trước ảnh</Text>
            <View style={styles.previewSpacer} />
          </View>

          <View style={styles.previewImageContainer}>
            {previewUri && (
              <Image
                source={{uri: previewUri}}
                style={styles.previewImage}
                resizeMode="contain"
              />
            )}
          </View>

          <View style={styles.previewActions}>
            <TouchableOpacity
              style={styles.previewRetakeButton}
              onPress={onRetakePhoto}>
              <Text style={styles.previewRetakeText}>Chụp lại</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={styles.previewConfirmButton}
              onPress={onConfirmPhoto}>
              <Text style={styles.previewConfirmText}>Xác nhận</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    );
  };

  const renderHeaderBody = () => {
    return (
      <View style={styles.headerBody}>
        <View style={styles.headerLeft}>
          <View style={styles.boxCamera}>
            <View style={styles.containerImage}>
              {avatarUri ? (
                <Image source={{uri: avatarUri}} style={styles.image} />
              ) : (
                <Image
                  source={R.images.iconCamera}
                  style={[styles.image, {width: 25, height: 25}]}
                />
              )}
            </View>
            <View style={styles.containerButton}>{renderButtonCamera()}</View>
          </View>
        </View>

        <View style={styles.headerRight}>
          <Text
            style={[
              styles.text,
              {
                lineHeight: 19,
                fontSize: R.fontsize.fontsSizeTitle,
                fontWeight: '600',
                fontFamily: R.fonts.fontMedium,
                color: R.colors.blue,
              },
            ]}>
            {dataProfile?.name || 'Không có dữ liệu'}
          </Text>
          <Text style={[styles.text, {fontSize: R.fontsize.fontsSizeSubTitle}]}>
            {dataProfile?.role || 'Không có dữ liệu'}
          </Text>
          <Text
            style={[
              styles.text,
              {
                lineHeight: 24,
                color: R.colors.blue,
                fontWeight: '600',
                fontFamily: R.fonts.fontMedium,
              },
            ]}>
            Mã CBGV:{' '}
            <Text
              style={[
                styles.text,
                {fontWeight: '600', fontFamily: R.fonts.fontMedium},
              ]}>
              {dataProfile?.code || 'Không có dữ liệu'}
            </Text>
          </Text>
          <Text
            style={[
              styles.text,
              {
                lineHeight: 24,
                color: R.colors.blue,
                fontWeight: '600',
                fontFamily: R.fonts.fontMedium,
              },
            ]}>
            Email:{' '}
            <Text
              style={[
                styles.text,
                {fontWeight: '600', fontFamily: R.fonts.fontMedium},
              ]}>
              {dataProfile?.email || 'Không có dữ liệu'}
            </Text>
          </Text>
          <Text
            style={[
              styles.text,
              {
                lineHeight: 24,
                color: R.colors.blue,
                fontWeight: '600',
                fontFamily: R.fonts.fontMedium,
              },
            ]}>
            TK chứng thực:{' '}
            <Text
              style={[
                styles.text,
                {fontWeight: '600', fontFamily: R.fonts.fontMedium},
              ]}>
              {dataProfile?.authCredential || 'Không có dữ liệu'}
            </Text>
          </Text>
          <Text
            style={[
              styles.text,
              {
                lineHeight: 24,
                color: R.colors.blue,
                fontWeight: '600',
                fontFamily: R.fonts.fontMedium,
              },
            ]}>
            Đơn vị công tác:{' '}
            <Text
              style={[
                styles.text,
                {fontWeight: '600', fontFamily: R.fonts.fontMedium},
              ]}>
              {dataProfile?.department || 'Không có dữ liệu'}
            </Text>
          </Text>
          <Text
            style={[
              styles.text,
              {
                lineHeight: 24,
                color: R.colors.blue,
                fontWeight: '600',
                fontFamily: R.fonts.fontMedium,
              },
            ]}>
            Bộ môn:{' '}
            <Text
              style={[
                styles.text,
                {fontWeight: '600', fontFamily: R.fonts.fontMedium},
              ]}>
              {dataProfile?.teachingUnit || 'Không có dữ liệu'}
            </Text>
          </Text>
        </View>
      </View>
    );
  };

  const renderBody = () => {
    return (
      <View style={styles.bodyProfile}>
        <View style={styles.containerInput}>
          <TextField
            title={'Số điện thoại'}
            value={phoneNumber}
            onChangeText={setPhoneNumber}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
          <View style={styles.sizedBox}></View>
          <TextField
            title={'Mã CBGV cũ'}
            value={oldTeacherCode}
            onChangeText={setOldTeacherCode}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
        </View>
        <View style={styles.containerInput}>
          <TextField
            width={'100%'}
            title={'Nơi công tác'}
            value={workPlace}
            onChangeText={setWorkPlace}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
          />
        </View>
        <View style={styles.containerInput}>
          <TextField
            width={'100%'}
            title={'Chức vụ'}
            value={position}
            onChangeText={setPosition}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
          />
        </View>
        <View style={styles.containerInput}>
          <TextField
            width={'100%'}
            title={'Vị trí kiêm nhiệm '}
            value={extraDuty}
            onChangeText={setExtraDuty}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
          />
        </View>
        <View style={styles.containerInput}>
          <TextField
            title={'Loại lao động'}
            value={laborType}
            onChangeText={setLaborType}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
          <View style={styles.sizedBox}></View>
          <TextField
            title={'Loại biên chế'}
            value={employmentType}
            onChangeText={setEmploymentType}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
        </View>
        <View style={styles.containerInput}>
          <TextField
            title={'Quyết định bổ nhiệm'}
            value={appointmentDecision}
            onChangeText={setAppointmentDecision}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
          <View style={styles.sizedBox}></View>
          <TextField
            title={'Ngày bổ nhiệm'}
            value={appointmentDate}
            onChangeText={setAppointmentDate}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
        </View>
        <View style={styles.containerInput}>
          <TextField
            title={'Cơ quan ban hành QĐ'}
            value={issuingAgency}
            onChangeText={setIssuingAgency}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            width={'100%'}
            containerBackgroundColor={R.colors.white}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Công việc trước khi tuyển dụng'}
            value={jobBeforeRecruitment}
            onChangeText={setJobBeforeRecruitment}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            width={'100%'}
            containerBackgroundColor={R.colors.white}
          />
        </View>

        <View style={[styles.containerInput]}>
          <RadioGroup
            options={options2}
            selectedValue={selectedValue2}
            onValueChange={onValueChange2}
            disabled={false}
            size={20}
            backgroundBoxColor={R.colors.blue}
            borderBoxColor={R.colors.black}
            direction={'row'}
            marginBtnAndLabel={10}
            justifyContent={'space-around'}
            editable={true}
            containerWidth={'100%'}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Ngày hưởng PCTN'}
            value={allowanceSeniorityDate}
            onChangeText={setAllowanceSeniorityDate}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            width={'100%'}
            containerBackgroundColor={R.colors.white}
          />
        </View>
        <View style={styles.containerInput}>
          <TextField
            title={'PCTN công tác(%)'}
            value={workAllowancePercent}
            onChangeText={setWorkAllowancePercent}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
          <View style={styles.sizedBox}></View>
          <TextField
            title={'PCTN nhà giáo(%)'}
            value={teacherAllowancePercent}
            onChangeText={setTeacherAllowancePercent}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Loại CBGV'}
            value={teacherType}
            onChangeText={setTeacherType}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            width={'100%'}
            containerBackgroundColor={R.colors.white}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Đơn vị sinh hoạt chuyên môn'}
            value={academicUnit}
            onChangeText={setAcademicUnit}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            width={'100%'}
            containerBackgroundColor={R.colors.white}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Bộ môn sinh hoạt chuyên môn'}
            value={subjectDepartment}
            onChangeText={setSubjectDepartment}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            width={'100%'}
            containerBackgroundColor={R.colors.white}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Trạng thái làm việc'}
            value={employmentStatus}
            onChangeText={setEmploymentStatus}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            width={'100%'}
            containerBackgroundColor={R.colors.white}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Ngày bắt đầu làm việc'}
            value={workStartDate}
            onChangeText={setWorkStartDate}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
          <View style={styles.sizedBox}></View>
          <TextField
            title={'Loại hđ hiện hành'}
            value={currentContractType}
            onChangeText={setCurrentContractType}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Ngày BĐ HĐ hiện hành'}
            value={contractStartDate}
            onChangeText={setContractStartDate}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
          <View style={styles.sizedBox}></View>
          <TextField
            title={'Ngày KT HĐ hiện hành'}
            value={contractEndDate}
            onChangeText={setContractEndDate}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Số hợp đồng hiện hành'}
            value={currentContractNumber}
            onChangeText={setCurrentContractNumber}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            width={'100%'}
            containerBackgroundColor={R.colors.white}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Ngày HL HĐ hiện hành'}
            value={contractEffectiveDate}
            onChangeText={setContractEffectiveDate}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
          <View style={styles.sizedBox}></View>
          <TextField
            title={'Ngày BĐ làm việc CT'}
            value={fullTimeWorkStartDate}
            onChangeText={setFullTimeWorkStartDate}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Thời điểm xếp BL cuối'}
            value={lastClassificationDate}
            onChangeText={setLastClassificationDate}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
          <View style={styles.sizedBox}></View>
          <TextField
            title={'(%) PCTNVK hiện hành'}
            value={currentWorkAllowancePercent}
            onChangeText={setCurrentWorkAllowancePercent}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Ngạch lương'}
            value={salaryGrade}
            onChangeText={setSalaryGrade}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            width={'100%'}
            containerBackgroundColor={R.colors.white}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Bậc lương hiện hành'}
            value={currentSalaryLevel}
            onChangeText={setCurrentSalaryLevel}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
          <View style={styles.sizedBox}></View>
          <TextField
            title={'Hệ số lương hiện hành'}
            value={currentSalaryCoefficient}
            onChangeText={setCurrentSalaryCoefficient}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            containerBackgroundColor={R.colors.white}
            width={'48%'}
          />
        </View>
        <View style={styles.containerInput}>
          <TextField
            title={'Mốc nâng lương'}
            value={salaryIncreaseMilestone}
            onChangeText={setSalaryIncreaseMilestone}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            width={'48%'}
            containerBackgroundColor={R.colors.white}
          />
        </View>

        <View style={styles.containerInput}>
          <TextField
            title={'Chức danh giảng viên'}
            value={lecturerTitle}
            onChangeText={setLecturerTitle}
            color={R.colors.black}
            fontSize={R.sizes.sm}
            fontSizeTitle={R.sizes.sm}
            width={'100%'}
            containerBackgroundColor={R.colors.white}
          />
        </View>

        <Button
          title={'Lưu'}
          onPress={onSave}
          backgroundColor={R.colors.blue}
          textColor={R.colors.white}
          fontSize={R.sizes.sm}
          paddingHorizontal={15}
          paddingVertical={5}
          borderRadius={10}
          fontSizeTitle={R.sizes.sm}
        />
      </View>
    );
  };

  return (
    <View style={styles.container}>
      <Header title={'Hồ sơ giảng viên'} isBack />
      <ScrollView showsVerticalScrollIndicator={false} vertical>
        <View style={styles.body}>
          {renderHeaderBody()}
          {renderBody()}
        </View>
      </ScrollView>

      {/* Image Source Selection Modal */}

      {/* Preview Modal */}
      {renderPreviewModal()}

      {/* Overlay Camera - chỉ UI, mọi handler/state nhận từ props */}
      {showCamera && (
        <View style={styles.overlay}>
          {device ? (
            <>
              <Camera
                ref={cameraRef}
                style={styles.absoluteFill}
                device={device}
                isActive={showCamera}
                photo
              />
              <TouchableOpacity
                style={styles.topLeft}
                onPress={onToggleCameraPosition}>
                <Image
                  source={R.images.icSwitchCamera}
                  tintColor={R.colors.white}
                  style={{width: 30, height: 30}}
                />
              </TouchableOpacity>

              <TouchableOpacity style={styles.topRight} onPress={onCloseCamera}>
                <Image
                  source={R.images.icClose}
                  tintColor={R.colors.white}
                  style={{width: 30, height: 30}}
                />
              </TouchableOpacity>

              <TouchableOpacity style={styles.bottomLeft} onPress={onSelectGallery}>
                <View style={styles.galleryPreview}>
                  {recentPhotos.length > 0 ? (
                    <View style={styles.galleryGrid}>
                      {recentPhotos.slice(0, 4).map((photoUri, index) => (
                        <Image
                          key={index}
                          source={{uri: photoUri}}
                          style={styles.galleryThumbnail}
                        />
                      ))}
                    </View>
                  ) : (
                    <Image
                      source={R.images.icTakePhoto}
                      tintColor={R.colors.white}
                      style={{width: 30, height: 30}}
                    />
                  )}
                </View>
              </TouchableOpacity>

              <TouchableOpacity style={styles.shutter} onPress={onTakePhoto}>
                {/* <Image
                  source={R.images.icTakePhoto}
                  tintColor={R.colors.white}
                  style={{width: 24, height: 24}}
                /> */}
              </TouchableOpacity>
            </>
          ) : (
            <View style={[styles.overlay, styles.center]}>
              <Text style={{color: '#fff'}}>Không tìm thấy camera</Text>
              <TouchableOpacity
                style={[styles.smallBtn, {marginTop: 16}]}
                onPress={onCloseCamera}>
                <Text style={styles.btnText}>Đóng</Text>
              </TouchableOpacity>
            </View>
          )}
        </View>
      )}
    </View>
  );
};

export default ProfileView;
