package com.howon.lifepass;

import androidx.appcompat.app.AlertDialog;

import android.graphics.text.LineBreaker;
import android.os.Bundle;
import android.text.Editable;
import android.text.Layout;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.content.SharedPreferences;
import android.content.Context;
import android.content.Intent;


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import android.content.pm.PackageManager;
import android.Manifest;

import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class AlertActivity extends AppCompatActivity {

    private OkHttpClient httpClient = new OkHttpClient();
    private List<DisasterMessage> messages = new ArrayList<>();
    private LinearLayout messageList;
    private String selectedProvince = "";
    private String selectedCityCounty = "";
    private String selectedDisasterType = "전체"; // 초기값 설정
    private Map<String, List<String>> cityCountyMap;
    private int currentPage = 1;
    private boolean isLoading = false;
    private static final int REQUEST_CODE_POST_NOTIFICATIONS = 1;
    private SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alert);
        // 하단바 버튼들 초기화
        ImageButton bottomButton1 = findViewById(R.id.bottomButton1);
        ImageButton bottomButton2 = findViewById(R.id.bottomButton2);
        ImageButton bottomButton3 = findViewById(R.id.bottomButton3);
        ImageButton bottomButton4 = findViewById(R.id.bottomButton4);

        // 하단바 버튼 클릭 이벤트 설정
        View.OnClickListener bottomButtonListener = v -> {
            int id = v.getId();
            if (id == R.id.bottomButton1) {
                // WeatherActivity로 전환
                startActivity(new Intent(AlertActivity.this, WeatherActivity.class));
            } else if (id == R.id.bottomButton2) {
                // AlertActivity로 전환 (현재 페이지)
                Toast.makeText(AlertActivity.this, "현재 페이지입니다.", Toast.LENGTH_SHORT).show();
            } else if (id == R.id.bottomButton3) {
                // NotificationActivity로 전환
                startActivity(new Intent(AlertActivity.this, NotificationActivity.class));
            } else if (id == R.id.bottomButton4) {
                // DisaterActivity로 전환 (현재 페이지)
                startActivity(new Intent(AlertActivity.this, DisasterActivity.class));
            }
        };

        bottomButton1.setOnClickListener(bottomButtonListener);
        bottomButton2.setOnClickListener(bottomButtonListener);
        bottomButton3.setOnClickListener(bottomButtonListener);
        bottomButton4.setOnClickListener(bottomButtonListener);

        messageList = findViewById(R.id.messageContainer);
        initCityCountyMap();

        preferences = getSharedPreferences("AlertSettings", Context.MODE_PRIVATE);

        Spinner provinceSpinner = findViewById(R.id.regionSpinner);
        Spinner cityCountySpinner = findViewById(R.id.cityCountySpinner);
        Spinner disasterTypeSpinner = findViewById(R.id.disasterTypeSpinner); // 재해 종류 스피너 추가

        ArrayAdapter<CharSequence> provinceAdapter = ArrayAdapter.createFromResource(this,
                R.array.provinces, android.R.layout.simple_spinner_item);
        provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        provinceSpinner.setAdapter(provinceAdapter);

        provinceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedProvince = parent.getItemAtPosition(position).toString();
                List<String> cityCountyList = cityCountyMap.get(selectedProvince);
                if (cityCountyList != null) {
                    ArrayAdapter<String> cityCountyAdapter = new ArrayAdapter<>(AlertActivity.this,
                            android.R.layout.simple_spinner_item, cityCountyList);
                    cityCountyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    cityCountySpinner.setAdapter(cityCountyAdapter);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        cityCountySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedCityCounty = parent.getItemAtPosition(position).toString();
                currentPage = 1;
                messages.clear();
                fetchTotalPages();  // 최신 페이지 수를 계산하여 가져옴
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        // 재해 종류 선택 스피너
        ArrayAdapter<CharSequence> disasterTypeAdapter = ArrayAdapter.createFromResource(this,
                R.array.disaster_types, android.R.layout.simple_spinner_item);
        disasterTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        disasterTypeSpinner.setAdapter(disasterTypeAdapter);

        disasterTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedDisasterType = parent.getItemAtPosition(position).toString();
                updateMessageList(messages); // 메시지 업데이트
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        // 검색 필드 설정
        EditText searchField = findViewById(R.id.searchInput);
        searchField.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                List<DisasterMessage> filtered = filterMessages(s.toString());
                updateMessageList(filtered);
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });

        ScrollView scrollView = findViewById(R.id.scrollView);
        scrollView.getViewTreeObserver().addOnScrollChangedListener(() -> {
            View view = scrollView.getChildAt(scrollView.getChildCount() - 1);
            int diff = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()));
            if (diff == 0 && !isLoading) {
                currentPage++;
                fetchMessages(currentPage);
            }
        });

        createNotificationChannel();  // Notification Channel 생성

        // Android 13 이상에서는 POST_NOTIFICATIONS 권한 필요
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_CODE_POST_NOTIFICATIONS);
            }
        }

        // 상단 스피커 아이콘 클릭 시 설정 다이얼로그 호출
        ImageView speakerIcon = findViewById(R.id.speakerIcon);
        speakerIcon.setOnClickListener(v -> showAlertSettingDialog());

        // WorkManager 설정 (정기적으로 API 호출)
        Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build();

        PeriodicWorkRequest fetchDisasterMessagesRequest = new PeriodicWorkRequest.Builder(
                FetchDisasterMessagesWorker.class, 15, TimeUnit.MINUTES) // 15분 주기
                .setConstraints(constraints)
                .build();

        WorkManager.getInstance(this).enqueue(fetchDisasterMessagesRequest);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_POST_NOTIFICATIONS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "알림 권한이 허용되었습니다.", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "알림 권한이 거부되었습니다.", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "AlertChannel";
            String description = "Channel for disaster alerts";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel("ALERT_CHANNEL_ID", name, importance);
            channel.setDescription(description);

            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }

    private void initCityCountyMap() {
        cityCountyMap = new HashMap<>();
        cityCountyMap.put("서울특별시", Arrays.asList("강남구", "강동구", "강북구", "강서구", "관악구", "광진구", "구로구", "금천구", "노원구", "도봉구", "동대문구", "동작구", "마포구", "서대문구", "서초구", "성동구", "성북구", "송파구", "양천구", "영등포구", "용산구", "은평구", "종로구", "중구", "중랑구"));
        cityCountyMap.put("부산광역시", Arrays.asList("강서구", "금정구", "기장군", "남구", "동구", "동래구", "부산진구", "북구", "사상구", "사하구", "서구", "수영구", "연제구", "영도구", "중구", "해운대구"));
        cityCountyMap.put("대구광역시", Arrays.asList("남구", "달서구", "달성군", "동구", "북구", "서구", "수성구", "중구"));
        cityCountyMap.put("인천광역시", Arrays.asList("강화군", "계양구", "미추홀구", "남동구", "동구", "부평구", "서구", "연수구", "옹진군", "중구"));
        cityCountyMap.put("광주광역시", Arrays.asList("광산구", "남구", "동구", "북구", "서구"));
        cityCountyMap.put("대전광역시", Arrays.asList("대덕구", "동구", "서구", "유성구", "중구"));
        cityCountyMap.put("울산광역시", Arrays.asList("남구", "동구", "북구", "울주군", "중구"));
        cityCountyMap.put("세종특별자치시", Arrays.asList("조치원읍", "연서면", "연동면", "연기면", "장군면", "금남면", "부강면", "고운동", "소담동", "반곡동"));
        cityCountyMap.put("경기도", Arrays.asList("가평군", "고양시", "과천시", "광명시", "광주시", "구리시", "군포시", "김포시", "남양주시", "동두천시", "부천시", "성남시", "수원시", "시흥시", "안산시", "안성시", "안양시", "양주시", "양평군", "여주시", "연천군", "오산시", "용인시", "의왕시", "의정부시", "이천시", "파주시", "평택시", "포천시", "하남시", "화성시"));
        cityCountyMap.put("강원특별자치도", Arrays.asList("춘천시", "원주시", "강릉시", "동해시", "태백시", "속초시", "삼척시", "홍천군", "횡성군", "영월군", "평창군", "정선군", "철원군", "화천군", "양구군", "인제군", "고성군", "양양군"));
        cityCountyMap.put("충청북도", Arrays.asList("청주시", "충주시", "제천시", "보은군", "옥천군", "영동군", "증평군", "진천군", "괴산군", "음성군", "단양군"));
        cityCountyMap.put("충청남도", Arrays.asList("천안시", "공주시", "보령시", "아산시", "서산시", "논산시", "계룡시", "당진시", "금산군", "부여군", "서천군", "청양군", "홍성군", "예산군", "태안군"));
        cityCountyMap.put("전북특별자치도", Arrays.asList("전주시", "군산시", "익산시", "정읍시", "남원시", "김제시", "완주군", "진안군", "무주군", "장수군", "임실군", "순창군", "고창군", "부안군"));
        cityCountyMap.put("전라남도", Arrays.asList("목포시", "여수시", "순천시", "나주시", "광양시", "담양군", "곡성군", "구례군", "고흥군", "보성군", "화순군", "장흥군", "강진군", "해남군", "영암군", "무안군", "함평군", "영광군", "장성군", "완도군", "진도군", "신안군"));
        cityCountyMap.put("경상북도", Arrays.asList("포항시", "경주시", "김천시", "안동시", "구미시", "영주시", "영천시", "상주시", "문경시", "경산시", "군위군", "의성군", "청송군", "영양군", "영덕군", "청도군", "고령군", "성주군", "칠곡군", "예천군", "봉화군", "울진군", "울릉군"));
        cityCountyMap.put("경상남도", Arrays.asList("창원시", "진주시", "통영시", "사천시", "김해시", "밀양시", "거제시", "양산시", "의령군", "함안군", "창녕군", "고성군", "남해군", "하동군", "산청군", "함양군", "거창군", "합천군"));
        cityCountyMap.put("제주특별자치도", Arrays.asList("제주시", "서귀포시"));
    }

    private boolean shouldNotify(DisasterMessage message) {
        String savedProvince = preferences.getString("selectedProvince", "");
        String savedCityCounty = preferences.getString("selectedCityCounty", "");
        String savedDisasterType = preferences.getString("selectedDisasterType", "전체");

        boolean matchesProvince = savedProvince.isEmpty() || message.getContent().contains(savedProvince);
        boolean matchesCityCounty = savedCityCounty.isEmpty() || message.getContent().contains(savedCityCounty);
        boolean matchesDisasterType = savedDisasterType.equals("전체") || message.getContent().contains(savedDisasterType);

        return matchesProvince && matchesCityCounty && matchesDisasterType;
    }

    private void sendNotification(String title, String content) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "ALERT_CHANNEL_ID")
                .setSmallIcon(R.drawable.warning1)
                .setContentTitle(title)
                .setContentText(content)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        try {
            notificationManager.notify(1, builder.build());
        } catch (SecurityException e) {
            Log.e("Notification Error", "Permission not granted for notifications");
        }
    }

    private List<DisasterMessage> filterMessages(String query) {
        List<DisasterMessage> filtered = new ArrayList<>();
        for (DisasterMessage msg : messages) {
            if (msg.getContent().contains(query)) {
                filtered.add(msg);
            }
        }
        return filtered;
    }

    private void showAlertSettingDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_alertsetting, null);

        Spinner settingProvinceSpinner = dialogView.findViewById(R.id.regionSpinner);
        Spinner settingCityCountySpinner = dialogView.findViewById(R.id.cityCountySpinner);
        Spinner settingDisasterTypeSpinner = dialogView.findViewById(R.id.disasterTypeSpinner);
        Button saveButton = dialogView.findViewById(R.id.saveButton);

        ArrayAdapter<CharSequence> provinceAdapter = ArrayAdapter.createFromResource(this,
                R.array.provinces, android.R.layout.simple_spinner_item);
        provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        settingProvinceSpinner.setAdapter(provinceAdapter);

        ArrayAdapter<CharSequence> disasterTypeAdapter = ArrayAdapter.createFromResource(this,
                R.array.disaster_types, android.R.layout.simple_spinner_item);
        disasterTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        settingDisasterTypeSpinner.setAdapter(disasterTypeAdapter);

        settingProvinceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedSettingProvince = parent.getItemAtPosition(position).toString();
                List<String> cityCountyList = cityCountyMap.get(selectedSettingProvince);
                if (cityCountyList != null) {
                    ArrayAdapter<String> cityCountyAdapter = new ArrayAdapter<>(AlertActivity.this,
                            android.R.layout.simple_spinner_item, cityCountyList);
                    cityCountyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    settingCityCountySpinner.setAdapter(cityCountyAdapter);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        saveButton.setOnClickListener(v -> {
            String selectedSettingProvince = settingProvinceSpinner.getSelectedItem().toString();
            String selectedSettingCityCounty = settingCityCountySpinner.getSelectedItem() != null ? settingCityCountySpinner.getSelectedItem().toString() : "";
            String selectedSettingDisasterType = settingDisasterTypeSpinner.getSelectedItem().toString();

            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("selectedProvince", selectedSettingProvince);
            editor.putString("selectedCityCounty", selectedSettingCityCounty);
            editor.putString("selectedDisasterType", selectedSettingDisasterType);
            editor.apply();

            Toast.makeText(AlertActivity.this, "설정이 저장되었습니다.", Toast.LENGTH_SHORT).show();
        });

        settingDisasterTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedSettingDisasterType = parent.getItemAtPosition(position).toString();
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("selectedDisasterType", selectedSettingDisasterType);
                editor.apply();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView);

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void fetchTotalPages() {
        try {
            String encodedProvince = URLEncoder.encode(selectedProvince, "UTF-8").replace("%20", "+");
            String encodedCityCounty = URLEncoder.encode(selectedCityCounty, "UTF-8").replace("%20", "+");

            String url = "https://www.safetydata.go.kr/V2/api/DSSP-IF-00247"
                    + "?serviceKey=MT13T4W16LK33RAS"
                    + "&pageNo=1"
                    + "&numOfRows=1"
                    + "&type=json"
                    + "&rgnNm=" + encodedProvince + "+" + encodedCityCounty;

            Request request = new Request.Builder().url(url).build();

            httpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        InputStream responseBodyStream = response.body().byteStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(responseBodyStream, StandardCharsets.UTF_8));
                        StringBuilder responseData = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            responseData.append(line);
                        }
                        runOnUiThread(() -> parseTotalPages(responseData.toString()));
                    } else {
                        Log.e("API Error", "Response not successful: " + response.code());
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void parseTotalPages(String responseData) {
        try {
            JSONObject json = new JSONObject(responseData);
            int totalCount = json.optInt("totalCount", 0);
            int totalPages = (int) Math.ceil((double) totalCount / 15);
            fetchMessages(totalPages); // 최신 페이지를 가져옴
        } catch (JSONException e) {
            Log.e("JSON Parsing Error", e.getMessage());
        }
    }

    private void fetchMessages(int page) {
        isLoading = true;
        try {
            String encodedProvince = URLEncoder.encode(selectedProvince, "UTF-8").replace("%20", "+");
            String encodedCityCounty = URLEncoder.encode(selectedCityCounty, "UTF-8").replace("%20", "+");

            String url = "https://www.safetydata.go.kr/V2/api/DSSP-IF-00247"
                    + "?serviceKey=MT13T4W16LK33RAS"
                    + "&pageNo=" + page
                    + "&numOfRows=15"
                    + "&type=json"
                    + "&rgnNm=" + encodedProvince + "+" + encodedCityCounty;

            Request request = new Request.Builder().url(url).build();

            httpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    isLoading = false;
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    isLoading = false;
                    if (response.isSuccessful()) {
                        InputStream responseBodyStream = response.body().byteStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(responseBodyStream, StandardCharsets.UTF_8));
                        StringBuilder responseData = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            responseData.append(line);
                        }
                        runOnUiThread(() -> parseMessages(responseData.toString()));
                    } else {
                        Log.e("API Error", "Response not successful: " + response.code());
                    }
                }
            });
        } catch (Exception e) {
            isLoading = false;
            e.printStackTrace();
        }
    }

    private void parseMessages(String responseData) {
        try {
            JSONObject json = new JSONObject(responseData);
            JSONArray body = json.optJSONArray("body");
            if (body != null) {
                messages.clear(); // 메시지 리스트 초기화
                for (int i = 0; i < body.length(); i++) {
                    JSONObject item = body.getJSONObject(i);
                    String content = item.getString("MSG_CN");
                    String date = item.getString("REG_YMD");

                    // 밀리초 부분 제거
                    if (date.contains(".")) {
                        date = date.substring(0, date.indexOf(".")); // '.' 이전까지만 추출
                    }

                    messages.add(new DisasterMessage(content, date));
                }

                // 최신순으로 정렬
                messages.sort((msg1, msg2) -> msg2.getDate().compareTo(msg1.getDate()));

                updateMessageList(messages);
            }
        } catch (JSONException e) {
            Log.e("JSON Error", e.getMessage());
        }
    }

    private void updateMessageList(List<DisasterMessage> messages) {
        messageList.removeAllViews();

        for (DisasterMessage msg : messages) {
            LinearLayout msgBox = new LinearLayout(this);
            msgBox.setOrientation(LinearLayout.VERTICAL);

            // 패딩을 충분히 추가하여 텍스트와 박스의 경계 사이에 여백 확보
            msgBox.setPadding(24, 24, 24, 24); // 상하좌우 모두 넉넉한 패딩을 설정
            msgBox.setBackgroundResource(android.R.drawable.dialog_holo_light_frame);

            // 박스 간의 아래쪽 간격을 위해 마진 추가
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(0, 0, 0, 20); // 아래쪽 마진을 추가하여 박스 간의 간격 조정
            msgBox.setLayoutParams(params);

            TextView msgView = new TextView(this);

            // 긴 문장에 대해 수동으로 줄바꿈을 추가하여 자연스럽게 보이도록 설정
            String content = msg.getContent();
            if (content.length() > 30) {
                content = content.substring(0, 30) + "\n" + content.substring(30);
            }
            msgView.setText(content + "\n" + formatDate(msg.getDate()));

            // 폰트 크기 및 줄 간격 조정
            msgView.setTextSize(15); // 폰트 크기를 적절히 설정 (텍스트가 잘 들어가게끔)
            msgView.setLineSpacing(1.2f, 1.0f); // 줄 간격을 더 넓혀 가독성 확보
            msgView.setTextColor(getResources().getColor(android.R.color.black));

            // 텍스트의 최대 줄 수 및 자동 자르기 설정
            msgView.setEllipsize(TextUtils.TruncateAt.END);
            msgView.setMaxLines(5);

            // 텍스트와 박스 간의 여백을 충분히 확보하기 위한 패딩 설정
            msgView.setPadding(16, 16, 16, 16);

            // 단어가 잘리지 않도록 설정
            msgView.setHorizontallyScrolling(false);
            msgView.setSingleLine(false);

            // 레이아웃의 너비를 충분히 확보하도록 설정
            msgView.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            ));

            msgBox.addView(msgView);
            msgBox.setOnClickListener(v -> showDialog(msg.getContent(), msg.getDate()));
            messageList.addView(msgBox);
        }
    }










    private String formatDate(String date) {
        // 날짜 포맷 수정: 예시: 2024-11-26로 표시
        if (date.contains(".")) {
            return date.substring(0, date.indexOf("."));
        }
        return date;
    }

    private void showDialog(String title, String content) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_alertplus, null);

        TextView titleView = dialogView.findViewById(R.id.dialogTitle);
        TextView contentView = dialogView.findViewById(R.id.dialogContent);
        Button closeBtn = dialogView.findViewById(R.id.closeButton);

        titleView.setText(title);
        contentView.setText(content);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView);

        AlertDialog dialog = builder.create();
        closeBtn.setOnClickListener(v -> dialog.dismiss());

        dialog.show();
    }

    public static class FetchDisasterMessagesWorker extends Worker {

        private OkHttpClient httpClient = new OkHttpClient();

        public FetchDisasterMessagesWorker(Context context, WorkerParameters workerParams) {
            super(context, workerParams);
        }

        @Override
        public Result doWork() {
            SharedPreferences preferences = getApplicationContext()
                    .getSharedPreferences("AlertSettings", Context.MODE_PRIVATE);
            String selectedProvince = preferences.getString("selectedProvince", "");
            String selectedCityCounty = preferences.getString("selectedCityCounty", "");
            String lastMessage = preferences.getString("lastMessage", ""); // 마지막 메시지 확인

            String encodedProvince, encodedCityCounty;
            try {
                encodedProvince = URLEncoder.encode(selectedProvince, "UTF-8").replace("%20", "+");
                encodedCityCounty = URLEncoder.encode(selectedCityCounty, "UTF-8").replace("%20", "+");
            } catch (Exception e) {
                return Result.failure();
            }

            String url = "https://www.safetydata.go.kr/V2/api/DSSP-IF-00247"
                    + "?serviceKey=MT13T4W16LK33RAS"
                    + "&pageNo=1"
                    + "&numOfRows=1"
                    + "&type=json"
                    + "&rgnNm=" + encodedProvince + "+" + encodedCityCounty;

            Request request = new Request.Builder().url(url).build();

            try {
                Response response = httpClient.newCall(request).execute();
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    JSONObject json = new JSONObject(responseData);
                    JSONArray body = json.optJSONArray("body");
                    if (body != null && body.length() > 0) {
                        JSONObject item = body.getJSONObject(0);
                        String content = item.getString("MSG_CN");
                        String date = item.getString("REG_YMD");

                        // 새 메시지가 마지막 메시지와 다를 경우 알림
                        if (!content.equals(lastMessage)) {
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.putString("lastMessage", content); // 마지막 메시지 저장
                            editor.apply();

                            DisasterMessage message = new DisasterMessage(content, date);
                            if (shouldNotify(message, preferences)) {
                                sendNotification("새로운 재난 메시지", content);
                            }
                        }
                    }
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
                return Result.failure();
            }

            return Result.success();
        }

        private boolean shouldNotify(DisasterMessage message, SharedPreferences preferences) {
            // 메시지가 중요하고 알림을 보낼 필요가 있는지 확인하는 조건
            return true;
        }

        private void sendNotification(String title, String content) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "ALERT_CHANNEL_ID")
                    .setSmallIcon(R.drawable.warning1)
                    .setContentTitle(title)
                    .setContentText(content)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setAutoCancel(true);

            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
            try {
                notificationManager.notify(1, builder.build());
            } catch (SecurityException e) {
                Log.e("Notification Error", "Permission not granted for notifications");
            }
        }
    }

    private static class DisasterMessage {
        private String content;
        private String date;

        public DisasterMessage(String content, String date) {
            this.content = content;
            this.date = date;
        }

        public String getContent() {
            return content;
        }

        public String getDate() {
            return date;
        }
    }


}
