package com.miraclegarden.smsmessage.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.miraclegarden.library.app.MiracleGardenActivity;
import com.miraclegarden.smsmessage.R;
import com.miraclegarden.smsmessage.comm.CommonAdapter;
import com.miraclegarden.smsmessage.comm.ViewHolder;
import com.miraclegarden.smsmessage.databinding.ActivityBankListBinding;
import com.miraclegarden.smsmessage.model.ApiError;
import com.miraclegarden.smsmessage.model.BankInfo;
import com.miraclegarden.smsmessage.network.ApiService;
import com.miraclegarden.smsmessage.network.TokenManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

public class BankListActivity extends MiracleGardenActivity<ActivityBankListBinding> {

    private ApiService apiService;
    private TokenManager tokenManager;
    private List<BankInfo> bankList = new ArrayList<>();
    private CommonAdapter<BankInfo> adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        tokenManager = TokenManager.getInstance(this);
        // 调试用：暂时跳过登录
//        if (!tokenManager.isLoggedIn()) {
//            startActivity(new Intent(this, LoginActivity.class));
//            finish();
//            return;
//        }

        apiService = new ApiService(this);

        initView();
        loadBankList();
    }

    private void initView() {
        String username = tokenManager.getUsername();
        if (username != null) {
            binding.tvUsername.setText(username);
        }

        binding.backIv.setOnClickListener(v -> finish());

        binding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        adapter = new CommonAdapter<BankInfo>(this, R.layout.item_bank, bankList) {
            @Override
            public void convert(ViewHolder holder, BankInfo bankInfo, int index) {
                holder.setText(R.id.tv_bank_name, bankInfo.getBankName());
                holder.setText(R.id.tv_account, bankInfo.getAccount());

                if (bankInfo.getRemark() != null && !bankInfo.getRemark().isEmpty()) {
                    holder.setText(R.id.tv_remark, bankInfo.getRemark());
                    holder.getView(R.id.tv_remark).setVisibility(View.VISIBLE);
                } else {
                    holder.getView(R.id.tv_remark).setVisibility(View.GONE);
                }

                String createdAt = formatTime(bankInfo.getCreatedAt());
                String updatedAt = formatTime(bankInfo.getUpdatedAt());
                holder.setText(R.id.tv_created_at, "创建: " + createdAt);
                holder.setText(R.id.tv_updated_at, "更新: " + updatedAt);
            }
        };
        binding.recyclerview.setAdapter(adapter);
    }

    private String formatTime(String isoTime) {
        if (isoTime == null || isoTime.isEmpty()) {
            return "--";
        }
        try {
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
            inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date date = inputFormat.parse(isoTime);

            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
            outputFormat.setTimeZone(TimeZone.getDefault());
            return outputFormat.format(date);
        } catch (Exception e) {
            return isoTime.substring(0, Math.min(16, isoTime.length()));
        }
    }

    private void loadBankList() {
        binding.loadingLy.setVisibility(View.VISIBLE);
        binding.emptyLy.setVisibility(View.GONE);

        apiService.getBankList(new ApiService.ApiCallback<List<BankInfo>>() {
            @Override
            public void onSuccess(List<BankInfo> result) {
                runOnUiThread(() -> {
                    binding.loadingLy.setVisibility(View.GONE);
                    bankList.clear();
                    if (result != null) {
                        bankList.addAll(result);
                    }
                    adapter.notifyDataSetChanged();

                    if (bankList.isEmpty()) {
                        binding.emptyLy.setVisibility(View.VISIBLE);
                    } else {
                        binding.emptyLy.setVisibility(View.GONE);
                    }
                });
            }

            @Override
            public void onError(ApiError error) {
                runOnUiThread(() -> {
                    binding.loadingLy.setVisibility(View.GONE);
                    Toast.makeText(BankListActivity.this,
                            "加载失败: " + error.getMessage(), Toast.LENGTH_LONG).show();
                });
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadBankList();
    }
}
