package com.apps.chillscreen.uiView;

import android.app.WallpaperManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.apps.chillscreen.R;
import com.apps.chillscreen.adapter.BookMarkAdapter;
import com.apps.chillscreen.bean.Picture;
import com.apps.chillscreen.databinding.FragmentBookmarkBinding;
import com.apps.chillscreen.listener.BookmarkClickListener;
import com.apps.chillscreen.listener.ShowFragmentListener;
import com.apps.chillscreen.tool.PictureManager;
import com.apps.chillscreen.tool.DownloadUtils;
import com.apps.chillscreen.tool.JsonConvert;
import com.apps.chillscreen.tool.OpenUtil;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.objectbox.reactive.DataSubscription;
import okhttp3.Call;

public class BookmarkShowFragment extends Fragment implements BookmarkClickListener, ShowFragmentListener {
    FragmentBookmarkBinding binding;
    private BookMarkAdapter bookMarkAdapter;
    private DataSubscription dataSubscription;
    private Map<String, File> downloadMap = new HashMap<>();
    private String fullUrl;
    private boolean isDown = false;
    private String savePath;
    private Call call;
    private Picture currentPicture;
    private boolean isSetting;
    private SetPaperFragment setPaperFragment;
    private WallpaperManager wallpaperManager;
    private volatile boolean isUpdating = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentBookmarkBinding.inflate(getLayoutInflater(), container, false);
        init();
        return binding.getRoot();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (dataSubscription != null) {
            dataSubscription.cancel();
        }
        if (call != null) {
            call.cancel();
        }
        deleteCacheFiles();
    }

    private void init() {
        bookMarkAdapter = new BookMarkAdapter();
        wallpaperManager = WallpaperManager.getInstance(requireActivity());
        setListener();
        bookMarkAdapter.setClickListener(this);
        binding.viewPager.setAdapter(bookMarkAdapter);
        binding.viewPager.setOffscreenPageLimit(1);
        setTransform();
        binding.viewPager.setCurrentItem(0);
    }

    private void setListener() {
        dataSubscription = PictureManager.setCollectListener(pictures -> {
            if (isUpdating) return;

            requireActivity().runOnUiThread(() -> {
                isUpdating = true;
                try {
                    updateUIState(pictures);
                } finally {
                    isUpdating = false;
                }
            });
        });
    }

    private void updateUIState(List<Picture> pictures) {
        if (pictures.isEmpty()) {
            binding.layoutNoData.setVisibility(View.VISIBLE);
            binding.viewPager.setVisibility(View.GONE);
        } else {
            binding.layoutNoData.setVisibility(View.GONE);
            binding.viewPager.setVisibility(View.VISIBLE);

            // 安全更新数据
            bookMarkAdapter.setPicture(new ArrayList<>(pictures));
            bookMarkAdapter.notifyDataSetChanged();

            // 确保当前项有效
            int currentItem = binding.viewPager.getCurrentItem();
            if (currentItem >= pictures.size()) {
                binding.viewPager.setCurrentItem(Math.max(0, pictures.size() - 1), false);
            }
        }
    }

    private void setTransform() {
        binding.viewPager.setPageTransformer(((page, position) -> {
            if (page.getWidth() == 0) return;

            float scaleNum = 0.8f;
            float transX = page.getWidth() * -position * (1 - scaleNum);
            if (position < -1) {
                page.setScaleX(scaleNum);
                page.setScaleY(scaleNum);
                page.setTranslationX(transX);
            } else if (position <= 1) {
                float scale = 1 - (float) Math.pow(Math.abs(position), 2) * (1 - scaleNum);
                page.setScaleX(scale);
                page.setScaleY(scale);
                page.setTranslationX(transX);
            } else {
                page.setScaleX(scaleNum);
                page.setScaleY(scaleNum);
                page.setTranslationX(transX);
            }
        }));
    }

    @Override
    public void onSetClick(Picture picture, int position) {
        if (isSetting) return;
        currentPicture=picture;
        fullUrl = picture.getFullUrl();
        String id = picture.getImId();
        savePath = JsonConvert.INSTANCE.getSaveFilePath(requireActivity(), id);
        if (setPaperFragment == null) {
            setPaperFragment = new SetPaperFragment();
            setPaperFragment.setListener(this);
        }
        if (!setPaperFragment.isAdded()) {
            setPaperFragment.show(requireActivity().getSupportFragmentManager(), "");
        }
    }

    @Override
    public void onDownloadClick(Picture picture, int position) {
        int permissionCode = 1;
        boolean permission = OpenUtil.requestPermission(requireActivity(), permissionCode);
        if (!permission) return;
        if (isDown) {
            Toast.makeText(requireActivity(), "Downloading, please wait...", Toast.LENGTH_SHORT).show();
            return;
        }
        isDown = true;
        fullUrl = picture.getFullUrl();
        String id = picture.getImId();
        currentPicture = picture;
        savePath = JsonConvert.INSTANCE.getSaveFilePath(requireActivity(), id);
        binding.searchPb.setVisibility(View.VISIBLE);
        if (downloadMap.get(id) != null) {
            File file = downloadMap.get(id);
            save(file);
            return;
        }
        startDownload(picture);
    }

    private void save(File file) {
        PictureManager.insertOrUpdateDownload(currentPicture);
        Uri uri = OpenUtil.saveToGallery(requireActivity(), file);
        requireActivity().runOnUiThread(() -> {
            binding.searchPb.setVisibility(View.GONE);
            isDown = false;
            if (uri == null) {
                Toast.makeText(requireActivity(), getString(R.string.save_fail), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(requireActivity(), getString(R.string.save_success), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void startDownload(Picture picture) {
        call = DownloadUtils.downloadFile(fullUrl, savePath, (isSuccess, inputStream) -> {
            File file = new File(savePath);
            if (isSuccess) {
                if (file.exists()) {
                    downloadMap.put(picture.getImId(), file);
                    save(file);
                }
            } else {
                requireActivity().runOnUiThread(() -> {
                    binding.searchPb.setVisibility(View.GONE);
                    Toast.makeText(requireActivity(), getString(R.string.download_fail), Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    @Override
    public void onRemoveClick(int position) {
        // 只操作数据库，UI更新交给监听器
        Picture pictureToRemove = bookMarkAdapter.getPictureAt(position);
        if (pictureToRemove != null) {
            PictureManager.updateCollect(pictureToRemove);
        }
    }

    @Override
    public void onSelectType(int type) {
        binding.searchPb.setVisibility(View.VISIBLE);
        isSetting=true;
        File downloadFile = downloadMap.get(currentPicture.getImId());
        if (downloadFile != null && downloadFile.exists()) {
            new Thread(() -> {
                Log.d("YYYYYY", "skip download and set");
                setWallPaper(downloadFile, type);
            }).start();
        } else {
            call = DownloadUtils.downloadFile(fullUrl, savePath, (isSuccess, inputStream) -> {
                File file = new File(savePath);
                if (file.exists() && isSuccess) {
                    downloadMap.put(currentPicture.getImId(), file);
                    setWallPaper(downloadFile, type);
                } else {
                    requireActivity().runOnUiThread(() -> {
                        isSetting=false;
                        binding.searchPb.setVisibility(View.GONE);
                        Toast.makeText(requireActivity(), getString(R.string.set_fail), Toast.LENGTH_SHORT).show();
                    });
                }
            });
        }
    }

    private void setWallPaper(File downloadFile, int type) {

        try {
            FileInputStream fileInputStream = new FileInputStream(downloadFile);
            switch (type) {
                case SetPaperFragment.type_home:
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        wallpaperManager.setStream(fileInputStream);
                    } else {
                        wallpaperManager.setStream(fileInputStream, null, true, WallpaperManager.FLAG_SYSTEM);
                    }
                    break;
                case SetPaperFragment.type_lock:
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        wallpaperManager.setStream(fileInputStream);
                    } else {
                        wallpaperManager.setStream(fileInputStream, null, true, WallpaperManager.FLAG_LOCK);
                    }
                    break;
                case SetPaperFragment.type_both:
                    wallpaperManager.setStream(fileInputStream);
                    break;
            }
            requireActivity().runOnUiThread(() -> {
                isSetting=false;
                binding.searchPb.setVisibility(View.GONE);
                Toast.makeText(requireActivity(),
                        getString(R.string.set_success),
                        Toast.LENGTH_SHORT).show();
            });
        } catch (Exception e) {
            requireActivity().runOnUiThread(() -> {
                isSetting=false;
                binding.searchPb.setVisibility(View.GONE);
                Toast.makeText(requireActivity(),
                        getString(R.string.set_fail),
                        Toast.LENGTH_SHORT).show();
            });
        }
    }

    private void deleteCacheFiles() {
        for (File file : downloadMap.values()) {
            if (file != null && file.exists()) {
                boolean deleted = file.delete();
                if (!deleted) {
                    Log.d("YYYYYY", "Failed to delete: " + file.getAbsolutePath());
                }
            }
        }
        downloadMap.clear();
    }
}