package com.example.bdkipoc;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class SettlementActivity extends AppCompatActivity {
    
    private TextView tvTotalAmount;
    private TextView tvTotalTransactions;
    private RecyclerView recyclerView;
    private SettlementAdapter adapter;
    private List<SettlementItem> settlementList;
    private ImageView btnBack;
    
    private String API_URL = "https://be-edc.msvc.app/transactions/performa-chanel-pembayaran?from_date=2025-01-01&to_date=2025-06-04&location_id=0&merchant_id=0";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settlement);
        
        initViews();
        setupRecyclerView();
        fetchApiData();
        setupClickListeners();
    }
    
    private void fetchApiData() {
        // Execute network call in background thread
        new ApiTask().execute(API_URL);
    }
    
    private void processApiData(JSONArray dataArray) {
        try {
            settlementList.clear();
            
            final long[] totalAmountArray = {0}; // Using array to make it effectively final
            final int[] totalTransactionsArray = {0}; // Using array to make it effectively final
            
            // Process each channel individually (no grouping)
            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject item = dataArray.getJSONObject(i);
                
                String channelCode = item.getString("channel_code");
                int transactions = item.getInt("total_transactions");
                long maxAmount = item.getLong("max_transastions");
                
                // Use channel code directly as display name with some formatting
                String displayName = formatChannelName(channelCode);
                int iconResource = getChannelIcon(channelCode);
                
                settlementList.add(new SettlementItem(
                    displayName,
                    maxAmount,
                    transactions,
                    iconResource
                ));
                
                totalAmountArray[0] += maxAmount;
                totalTransactionsArray[0] += transactions;
            }
            
            // Update UI on main thread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    updateSummary(totalAmountArray[0], totalTransactionsArray[0]);
                    adapter.notifyDataSetChanged();
                }
            });
            
        } catch (JSONException e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SettlementActivity.this, "Error parsing data", Toast.LENGTH_SHORT).show();
                    loadSampleData(); // Fallback to sample data
                }
            });
        }
    }
    
    private void updateSummary(long totalAmount, int totalTransactions) {
        tvTotalAmount.setText(formatCurrency(totalAmount));
        tvTotalTransactions.setText(String.valueOf(totalTransactions));
    }
    
    private void initViews() {
        tvTotalAmount = findViewById(R.id.tv_total_amount);
        tvTotalTransactions = findViewById(R.id.tv_total_transactions);
        recyclerView = findViewById(R.id.recycler_view);
        btnBack = findViewById(R.id.btn_back);
        
        settlementList = new ArrayList<>();
    }
    
    private void setupRecyclerView() {
        adapter = new SettlementAdapter(settlementList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }
    
    private void setupClickListeners() {
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    
    private void loadSampleData() {
        // Sample data as fallback
        settlementList.clear();
        
        settlementList.add(new SettlementItem("Kartu Kredit", 200000, 13, android.R.drawable.ic_menu_recent_history));
        settlementList.add(new SettlementItem("Kartu Debit", 200000, 13, android.R.drawable.ic_menu_manage));
        settlementList.add(new SettlementItem("Transfer", 200000, 13, android.R.drawable.ic_menu_send));
        settlementList.add(new SettlementItem("Uang Elektronik", 200000, 13, android.R.drawable.ic_menu_gallery));
        settlementList.add(new SettlementItem("QRIS", 200000, 13, android.R.drawable.ic_menu_camera));
        
        // Update summary
        tvTotalAmount.setText(formatCurrency(3506500));
        tvTotalTransactions.setText("65");
        
        adapter.notifyDataSetChanged();
    }
    
    private String formatChannelName(String channelCode) {
        // Format channel code to be more readable
        switch (channelCode) {
            case "GO-PAY":
                return "GoPay";
            case "SHOPEEPAY":
                return "ShopeePay";
            case "LINKAJA":
                return "LinkAja";
            case "MASTERCARD":
                return "Mastercard";
            case "VISA":
                return "Visa";
            case "QRIS":
                return "QRIS";
            case "DANA":
                return "Dana";
            case "OVO":
                return "OVO";
            case "DEBIT":
                return "Kartu Debit";
            case "GPN":
                return "GPN";
            case "OTHER":
                return "Lainnya";
            default:
                // Capitalize first letter and make rest lowercase
                return channelCode.substring(0, 1).toUpperCase() + 
                       channelCode.substring(1).toLowerCase();
        }
    }
    
    private String getChannelDisplayName(String channelCode) {
        // Deprecated - keeping for backward compatibility
        return formatChannelName(channelCode);
    }
    
    private int getChannelIcon(String channelCode) {
        // Dynamic icon assignment based on channel type
        switch (channelCode) {
            case "DEBIT":
                return android.R.drawable.ic_menu_manage;
            case "VISA":
            case "MASTERCARD":
                return android.R.drawable.ic_menu_recent_history;
            case "QRIS":
                return android.R.drawable.ic_menu_camera;
            case "DANA":
            case "GO-PAY":
            case "OVO":
            case "SHOPEEPAY":
            case "LINKAJA":
                return android.R.drawable.ic_menu_gallery;
            case "GPN":
                return android.R.drawable.ic_menu_send;
            case "OTHER":
                return android.R.drawable.ic_menu_info_details;
            default:
                return android.R.drawable.ic_menu_help;
        }
    }
    
    private String formatCurrency(long amount) {
        NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("id", "ID"));
        return formatter.format(amount);
    }
    
    // Deprecated helper class - no longer needed
    // private static class ChannelData { ... }
    
    // AsyncTask for API call
    private class ApiTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            try {
                URL url = new URL(urls[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();
                    return response.toString();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        
        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                try {
                    JSONObject jsonResponse = new JSONObject(result);
                    if (jsonResponse.getInt("status") == 200) {
                        JSONArray dataArray = jsonResponse.getJSONArray("data");
                        processApiData(dataArray);
                    } else {
                        Toast.makeText(SettlementActivity.this, "API Error", Toast.LENGTH_SHORT).show();
                        loadSampleData();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(SettlementActivity.this, "JSON Parse Error", Toast.LENGTH_SHORT).show();
                    loadSampleData();
                }
            } else {
                Toast.makeText(SettlementActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
                loadSampleData();
            }
        }
    }
}

// SettlementItem class - combined in same file
class SettlementItem {
    private String channelName;
    private long amount;
    private int transactionCount;
    private int iconResource;
    
    public SettlementItem() {}
    
    public SettlementItem(String channelName, long amount, int transactionCount, int iconResource) {
        this.channelName = channelName;
        this.amount = amount;
        this.transactionCount = transactionCount;
        this.iconResource = iconResource;
    }
    
    // Getters and Setters
    public String getChannelName() { return channelName; }
    public void setChannelName(String channelName) { this.channelName = channelName; }
    public long getAmount() { return amount; }
    public void setAmount(long amount) { this.amount = amount; }
    public int getTransactionCount() { return transactionCount; }
    public void setTransactionCount(int transactionCount) { this.transactionCount = transactionCount; }
    public int getIconResource() { return iconResource; }
    public void setIconResource(int iconResource) { this.iconResource = iconResource; }
}

// SettlementAdapter class - combined in same file
class SettlementAdapter extends RecyclerView.Adapter<SettlementAdapter.SettlementViewHolder> {
    
    private List<SettlementItem> settlementList;
    
    public SettlementAdapter(List<SettlementItem> settlementList) {
        this.settlementList = settlementList;
    }
    
    @NonNull
    @Override
    public SettlementViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_settlement, parent, false);
        return new SettlementViewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(@NonNull SettlementViewHolder holder, int position) {
        SettlementItem item = settlementList.get(position);
        
        holder.ivIcon.setImageResource(item.getIconResource());
        holder.tvChannelName.setText(item.getChannelName());
        holder.tvAmount.setText("Rp. " + formatCurrency(item.getAmount()));
        holder.tvTransactionCount.setText(item.getTransactionCount() + " Transaksi");
    }
    
    @Override
    public int getItemCount() {
        return settlementList.size();
    }
    
    private String formatCurrency(long amount) {
        NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("id", "ID"));
        return formatter.format(amount);
    }
    
    static class SettlementViewHolder extends RecyclerView.ViewHolder {
        ImageView ivIcon;
        TextView tvChannelName;
        TextView tvAmount;
        TextView tvTransactionCount;
        
        public SettlementViewHolder(@NonNull View itemView) {
            super(itemView);
            ivIcon = itemView.findViewById(R.id.iv_icon);
            tvChannelName = itemView.findViewById(R.id.tv_channel_name);
            tvAmount = itemView.findViewById(R.id.tv_amount);
            tvTransactionCount = itemView.findViewById(R.id.tv_transaction_count);
        }
    }
}