package com.baidu.ai.sample;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

public class PicturePreviewActivity extends AppCompatActivity {

    private String[] mImageUrls;
    private ViewPager mViewPager;
    private TextView mTvIndicator;
    private int mCurrentPosition = 0;
    private static final int REQUEST_WRITE_EXTERNAL_STORAGE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pic_preview);

        initData();
        setupViewPager();
    }

    private void initData() {
        mImageUrls = getIntent().getStringArrayExtra("ImageUrls");
        mCurrentPosition = getIntent().getIntExtra("currentPosition", 0);

        if (mImageUrls == null || mImageUrls.length == 0) {
            finish();
            return;
        }

        mViewPager = findViewById(R.id.viewPager);
        mTvIndicator = findViewById(R.id.tvIndicator);

        updateIndicator();
    }

    private void setupViewPager() {
        ImagePagerAdapter adapter = new ImagePagerAdapter();
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(mCurrentPosition);

        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                mCurrentPosition = position;
                updateIndicator();
            }
        });
    }

    private void updateIndicator() {
        if (mImageUrls != null && mImageUrls.length > 1) {
            mTvIndicator.setText(String.format("%d/%d", mCurrentPosition + 1, mImageUrls.length));
            mTvIndicator.setVisibility(View.VISIBLE);
        } else {
            mTvIndicator.setVisibility(View.GONE);
        }
    }

    private void saveImage(String imageUrl) {
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_WRITE_EXTERNAL_STORAGE);
            return;
        }

        // 已有权限，开始保存
        performSaveImage(imageUrl);
    }

    private void performSaveImage(String imageUrl) {
        Glide.with(this)
                .asBitmap()
                .load(imageUrl)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap bitmap, Transition<? super Bitmap> transition) {
                        try {
                            File savedFile = saveBitmapToGallery(bitmap);
                            if (savedFile != null) {
                                Toast.makeText(PicturePreviewActivity.this,
                                        "图片已保存到: " + savedFile.getAbsolutePath(),
                                        Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(PicturePreviewActivity.this,
                                        "保存失败",
                                        Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(PicturePreviewActivity.this,
                                    "保存失败: " + e.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onLoadFailed(@androidx.annotation.Nullable android.graphics.drawable.Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        Toast.makeText(PicturePreviewActivity.this,
                                "图片加载失败",
                                Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private File saveBitmapToGallery(Bitmap bitmap) {
        // 创建 Pictures 目录
        File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File appDir = new File(picturesDir, "MyApp");
        if (!appDir.exists()) {
            if (!appDir.mkdirs()) {
                return null;
            }
        }

        // 生成文件名
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String fileName = "BDAI_IMG_GENERATED_" + timeStamp + ".jpg";

        File file = new File(appDir, fileName);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

            // 通知系统更新相册
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                android.media.MediaScannerConnection.scanFile(this,
                        new String[]{file.getAbsolutePath()}, null, null);
            } else {
                sendBroadcast(new android.content.Intent(
                        android.content.Intent.ACTION_MEDIA_MOUNTED,
                        android.net.Uri.parse("file://" + Environment.getExternalStorageDirectory())));
            }

            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_WRITE_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，保存当前显示的图片
                if (mImageUrls != null && mCurrentPosition < mImageUrls.length) {
                    performSaveImage(mImageUrls[mCurrentPosition]);
                }
            } else {
                Toast.makeText(this, "存储权限被拒绝，无法保存图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private class ImagePagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mImageUrls != null ? mImageUrls.length : 0;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            View view = LayoutInflater.from(PicturePreviewActivity.this)
                    .inflate(R.layout.item_image_preview, container, false);

            ImageView imageView = view.findViewById(R.id.iv_picture);
            ProgressBar progressBar = view.findViewById(R.id.pb_picture);
            // 加载图片
            progressBar.setVisibility(View.VISIBLE);
            Glide.with(PicturePreviewActivity.this)
                    .load(mImageUrls[position])
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(imageView);
            progressBar.setVisibility(View.GONE);

            // 点击图片退出
            imageView.setOnClickListener(v -> finish());
            imageView.setOnLongClickListener(v -> {
                // 长按图片保存
                // TODO: 实现图片保存功能
                saveImage(mImageUrls[position]);
                return true;
            });

            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }
}