import React, {useRef, useState, useEffect} from 'react';
import {Platform, DeviceEventEmitter, Alert, PermissionsAndroid} from 'react-native';
import {launchImageLibrary} from 'react-native-image-picker';
import {CameraRoll} from '@react-native-camera-roll/camera-roll';
import ProfileView from './view';
import {useCameraDevice, useCameraPermission} from 'react-native-vision-camera';

const Profile = (props) => {
  const [user] = useState({
    name: 'Phạm Minh Quân',
    role: 'Trợ lý bộ môn thuộc trường',
    code: '80578',
    email: 'quan.pm@uit.edu.vn',
    authCredential: 'quanpm',
    department: 'Khoa học máy tính',
    teachingUnit: 'Trí tuệ nhân tạo',
    workPlace: 'Trường Cao Đẳng FPT',
    extraDuty: 'Vị trí kiêm nhiệm',
    employmentType: ['Quyền trưởng phòng', 'Trợ lý bộ môn thuộc trường'],
    appointmentDecision: 'QĐ/UIT/2025',
    appointmentDate: '20/03/2025',
    allowanceSeniorityDate: '10/03/2025',
    teacherType: 'CBGV trường',
    academicUnit: 'Khoa Công nghệ phần mềm',
    subjectDepartment: 'Bộ môn Phát triển phần mềm',
    employmentStatus: 'Đang công tác',
    workCommencementDate: '20/03/2025',
  });

  const [phoneNumber, setPhoneNumber] = useState('');
  const [oldTeacherCode, setOldTeacherCode] = useState('');
  const [workPlace, setWorkPlace] = useState('');
  const [position, setPosition] = useState('');
  const [extraDuty, setExtraDuty] = useState('');
  const [laborType, setLaborType] = useState('');
  const [employmentType, setEmploymentType] = useState('');
  const [appointmentDecision, setAppointmentDecision] = useState('');
  const [appointmentDate, setAppointmentDate] = useState('');
  const [issuingAgency, setIssuingAgency] = useState('');
  const [jobBeforeRecruitment, setJobBeforeRecruitment] = useState('');
  const [allowanceSeniorityDate, setAllowanceSeniorityDate] = useState('');
  const [workAllowancePercent, setWorkAllowancePercent] = useState('');
  const [teacherAllowancePercent, setTeacherAllowancePercent] = useState('');
  const [teacherType, setTeacherType] = useState('');
  const [academicUnit, setAcademicUnit] = useState('');
  const [subjectDepartment, setSubjectDepartment] = useState('');
  const [employmentStatus, setEmploymentStatus] = useState('');
  const [workStartDate, setWorkStartDate] = useState('');
  const [currentContractType, setCurrentContractType] = useState('');
  const [contractStartDate, setContractStartDate] = useState('');
  const [contractEndDate, setContractEndDate] = useState('');
  const [currentContractNumber, setCurrentContractNumber] = useState('');
  const [contractEffectiveDate, setContractEffectiveDate] = useState('');
  const [fullTimeWorkStartDate, setFullTimeWorkStartDate] = useState('');
  const [lastClassificationDate, setLastClassificationDate] = useState('');
  const [currentWorkAllowancePercent, setCurrentWorkAllowancePercent] = useState('');
  const [salaryGrade, setSalaryGrade] = useState('');
  const [currentSalaryLevel, setCurrentSalaryLevel] = useState('');
  const [currentSalaryCoefficient, setCurrentSalaryCoefficient] = useState('');
  const [salaryIncreaseMilestone, setSalaryIncreaseMilestone] = useState('');
  const [lecturerTitle, setLecturerTitle] = useState('');

  const [selectedValue2, setSelectedValue2] = useState('1');
  const options2 = [
    {label: 'Cơ chế', value: '1'},
    {label: 'Biên hữu', value: '2'},
  ];
  const onValueChange2 = v => setSelectedValue2(v);

  // --- camera logic (container) ---
  const [showCamera, setShowCamera] = useState(false);
  const [showImageSourceModal, setShowImageSourceModal] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const [avatarUri, setAvatarUri] = useState(null);
  const [previewUri, setPreviewUri] = useState(null);
  const [recentPhotos, setRecentPhotos] = useState([]);
  const [useFront, setUseFront] = useState(false);
  const cameraRef = useRef(null);
  const device = useCameraDevice(useFront ? 'front' : 'back');
  const {hasPermission, requestPermission} = useCameraPermission();

  const loadRecentPhotos = async () => {
    try {
      if (Platform.OS === 'android') {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        );
        if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
          return;
        }
      }
      
      const photos = await CameraRoll.getPhotos({
        first: 4, // Get 4 recent photos for preview
        assetType: 'Photos',
      });
      
      setRecentPhotos(photos.edges.map(edge => edge.node.image.uri));
    } catch (error) {
      console.log('Error loading recent photos:', error);
    }
  };

  useEffect(() => {
    loadRecentPhotos();
  }, []);

  const openImageSourceModal = async () => {
    if (!hasPermission) {
      const ok = await requestPermission();
      if (!ok) return;
    }
    setShowCamera(true);
    DeviceEventEmitter.emit('hideTabs', true);
  };

  const closeImageSourceModal = () => {
    setShowImageSourceModal(false);
  };

  const openCamera = async () => {
    if (!hasPermission) {
      const ok = await requestPermission();
      if (!ok) return;
    }
    setShowImageSourceModal(false);
    setShowCamera(true);
    DeviceEventEmitter.emit('hideTabs', true);
  };

  const openGallery = () => {
    const options = {
      mediaType: 'photo',
      includeBase64: false,
      maxHeight: 2000,
      maxWidth: 2000,
    };

    launchImageLibrary(options, response => {
      if (response.didCancel || response.error) {
        return;
      }

      if (response.assets && response.assets[0]) {
        const imageUri = response.assets[0].uri;
        setPreviewUri(imageUri);
        setShowImageSourceModal(false);
        setShowPreview(true);
        DeviceEventEmitter.emit('hideTabs', true);
      }
    });
  };

  const onTakePhoto = async () => {
    if (!cameraRef.current) return;
    const photo = await cameraRef.current.takePhoto({
      qualityPrioritization: 'balanced',
      flash: 'off',
    });
    const uri = Platform.OS === 'android' ? 'file://' + photo.path : photo.path;
    setPreviewUri(uri);
    setShowCamera(false);
    setShowPreview(true);
  };

  const onToggleCameraPosition = () => setUseFront(v => !v);

  const onCloseCamera = () => {
    setShowCamera(false);
    DeviceEventEmitter.emit('hideTabs', false);
  };

  const onConfirmPhoto = () => {
    setAvatarUri(previewUri);
    setPreviewUri(null);
    setShowPreview(false);
    DeviceEventEmitter.emit('hideTabs', false);
  };

  const onRetakePhoto = () => {
    setPreviewUri(null);
    setShowPreview(false);
    DeviceEventEmitter.emit('hideTabs', false);
  };

  const onClosePreview = () => {
    setPreviewUri(null);
    setShowPreview(false);
    DeviceEventEmitter.emit('hideTabs', false);
  };

  const handleSave = () => {
    const [formData, setFormData] = useState({
      phoneNumber,
      oldTeacherCode,
      workPlace,
      position,
      extraDuty,
      laborType,
      employmentType,
      appointmentDecision,
      appointmentDate,
      issuingAgency,
      jobBeforeRecruitment,
      selectedValue2,
      allowanceSeniorityDate,
      workAllowancePercent,
      teacherAllowancePercent,
      teacherType,
      academicUnit,
      subjectDepartment,
      employmentStatus,
      workStartDate,
      currentContractType,
      contractStartDate,
      contractEndDate,
      currentContractNumber,
      contractEffectiveDate,
      fullTimeWorkStartDate,
      lastClassificationDate,
      currentWorkAllowancePercent,
      salaryGrade,
      currentSalaryLevel,
      currentSalaryCoefficient,
      salaryIncreaseMilestone,
      lecturerTitle,
      avatarUri,
    });
    setFormData(formData);
    // TODO: call API save
  };

  // ❗ Chỉ MỘT return: truyền mọi thứ xuống View
  return (
    <ProfileView
      // profile
      dataProfile={user}
      // camera props (UI sẽ dùng để hiển thị)
      avatarUri={avatarUri}
      onPressSelectImage={openImageSourceModal}
      showCamera={showCamera}
      cameraRef={cameraRef}
      device={device}
      onToggleCameraPosition={onToggleCameraPosition}
      onTakePhoto={onTakePhoto}
      onCloseCamera={onCloseCamera}
      // image source modal
      showImageSourceModal={showImageSourceModal}
      onCloseImageSourceModal={closeImageSourceModal}
      onSelectCamera={openCamera}
      onSelectGallery={openGallery}
      // preview
      showPreview={showPreview}
      previewUri={previewUri}
      onConfirmPhoto={onConfirmPhoto}
      onRetakePhoto={onRetakePhoto}
      onClosePreview={onClosePreview}
      // gallery preview
      recentPhotos={recentPhotos}
      // radio
      selectedValue2={selectedValue2}
      options2={options2}
      onValueChange2={onValueChange2}
      // form states
      phoneNumber={phoneNumber}
      setPhoneNumber={setPhoneNumber}
      oldTeacherCode={oldTeacherCode}
      setOldTeacherCode={setOldTeacherCode}
      workPlace={workPlace}
      setWorkPlace={setWorkPlace}
      position={position}
      setPosition={setPosition}
      extraDuty={extraDuty}
      setExtraDuty={setExtraDuty}
      laborType={laborType}
      setLaborType={setLaborType}
      employmentType={employmentType}
      setEmploymentType={setEmploymentType}
      appointmentDecision={appointmentDecision}
      setAppointmentDecision={setAppointmentDecision}
      appointmentDate={appointmentDate}
      setAppointmentDate={setAppointmentDate}
      issuingAgency={issuingAgency}
      setIssuingAgency={setIssuingAgency}
      jobBeforeRecruitment={jobBeforeRecruitment}
      setJobBeforeRecruitment={setJobBeforeRecruitment}
      allowanceSeniorityDate={allowanceSeniorityDate}
      setAllowanceSeniorityDate={setAllowanceSeniorityDate}
      workAllowancePercent={workAllowancePercent}
      setWorkAllowancePercent={setWorkAllowancePercent}
      teacherAllowancePercent={teacherAllowancePercent}
      setTeacherAllowancePercent={setTeacherAllowancePercent}
      teacherType={teacherType}
      setTeacherType={setTeacherType}
      academicUnit={academicUnit}
      setAcademicUnit={setAcademicUnit}
      subjectDepartment={subjectDepartment}
      setSubjectDepartment={setSubjectDepartment}
      employmentStatus={employmentStatus}
      setEmploymentStatus={setEmploymentStatus}
      workStartDate={workStartDate}
      setWorkStartDate={setWorkStartDate}
      currentContractType={currentContractType}
      setCurrentContractType={setCurrentContractType}
      contractStartDate={contractStartDate}
      setContractStartDate={setContractStartDate}
      contractEndDate={contractEndDate}
      setContractEndDate={setContractEndDate}
      currentContractNumber={currentContractNumber}
      setCurrentContractNumber={setCurrentContractNumber}
      contractEffectiveDate={contractEffectiveDate}
      setContractEffectiveDate={setContractEffectiveDate}
      fullTimeWorkStartDate={fullTimeWorkStartDate}
      setFullTimeWorkStartDate={setFullTimeWorkStartDate}
      lastClassificationDate={lastClassificationDate}
      setLastClassificationDate={setLastClassificationDate}
      currentWorkAllowancePercent={currentWorkAllowancePercent}
      setCurrentWorkAllowancePercent={setCurrentWorkAllowancePercent}
      salaryGrade={salaryGrade}
      setSalaryGrade={setSalaryGrade}
      currentSalaryLevel={currentSalaryLevel}
      setCurrentSalaryLevel={setCurrentSalaryLevel}
      currentSalaryCoefficient={currentSalaryCoefficient}
      setCurrentSalaryCoefficient={setCurrentSalaryCoefficient}
      salaryIncreaseMilestone={salaryIncreaseMilestone}
      setSalaryIncreaseMilestone={setSalaryIncreaseMilestone}
      lecturerTitle={lecturerTitle}
      setLecturerTitle={setLecturerTitle}
      // actions
      onSave={handleSave}
    />
  );
};

export default Profile;
