package com.example.scoutingapp;

import java.text.SimpleDateFormat;

import android.content.Context;
import android.content.SharedPreferences;
import java.util.Date;
import java.util.Locale;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;


import java.io.File;

public class EndActivity extends AppCompatActivity {
    private EditText noteText;
    private EditText MajorPenatly;
    private EditText MinorPenatly;
    private MatchData matchData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_end);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        matchData = MainActivity.matchData;
        EditText notesText = findViewById(R.id.Notes);
        notesText.setText(matchData.geteNote());
        TextView textViewTeam = findViewById(R.id.teamnumber);
        textViewTeam.setText("Team " + matchData.getTeamNumber());
        TextView textViewMatch = findViewById(R.id.matchNumber);
        textViewMatch.setText("Match " + matchData.getMatchNumber());

        //sets team number and color
        if (matchData.isPractice()) {
            textViewTeam.setBackgroundColor(Color.parseColor("#0D9204")); //red
            textViewMatch.setBackgroundColor(Color.parseColor("#FF5722"));
            textViewMatch.setText("Practice");
        } else {
            if (!matchData.isBlueAlliance()) {
                textViewTeam.setBackgroundColor(Color.parseColor("#F71000")); //red
                textViewMatch.setBackgroundColor(Color.parseColor("#F71000"));
            } else {
                textViewTeam.setBackgroundColor(Color.parseColor("#0084ff"));
                textViewMatch.setBackgroundColor(Color.parseColor("#0084ff"));//blue
            }
        }

        Button L0button = (Button) findViewById(R.id.radioButtonL0);
        Button L1button = (Button) findViewById(R.id.radioButtonL1);
        Button L2button = (Button) findViewById(R.id.radioButtonL2);
        Button L3button = (Button) findViewById(R.id.radioButtonL3);
        Button DN1 = (Button) findViewById(R.id.radioButtonDN1);
        Button D0 = (Button) findViewById(R.id.radioButtonD0);
        Button D1 = (Button) findViewById(R.id.radioButtonD1);
        Button D2 = (Button) findViewById(R.id.radioButtonD2);
        Button D3 = (Button) findViewById(R.id.radioButtonD3);
        Button D4 = (Button) findViewById(R.id.radioButtonD4);
        Button D5 = (Button) findViewById(R.id.radioButtonD5);

        MinorPenatly = (EditText) findViewById(R.id.MinorPenalty);
        MajorPenatly = (EditText) findViewById(R.id.MajorPenalty);


        Intent intent = new Intent(this, MainActivity.class);
        noteText = (EditText) findViewById(R.id.Notes);



        Button submit = (Button) findViewById(R.id.Submit_button);
        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String majorStr = MajorPenatly.getText().toString().trim();
                String minorStr = MinorPenatly.getText().toString().trim();
                int major = majorStr.isEmpty() ? 0 : Integer.parseInt(majorStr);
                int minor = minorStr.isEmpty() ? 0 : Integer.parseInt(minorStr);

                matchData.seteNote(noteText.getText().toString());
                matchData.seteMajor(major);
                matchData.seteMinors(minor);

                if (isNetworkConnected()) {
                    csvMake();
                    String csvFileString = matchData.getCSVFileName();
                    Submit submitHelper = new Submit();
                    //Writes data to file to make google sheet read it as a list
                    File csvFilefile = new File(getFilesDir(), csvFileString);
                    submitHelper.parseCSVToList(csvFilefile);
                    //Uploads the Data to the Google sheet
                    submitHelper.uploadSheets(EndActivity.this, csvFileString);
                    //submit.renameFile(EndActivity.this, csvFileString);
                    matchData.setMatchNumber(matchData.getMatchNumber()+1);
                    startActivity(intent);
                    finishAffinity();
                } else {
                    offlinecsvMake();
                    matchData.setMatchNumber(matchData.getMatchNumber()+1);
                    startActivity(intent);
                    finishAffinity();
                }

            }
        });

        Button backButton = (Button) findViewById(R.id.BackButton);

        backButton.setOnLongClickListener((v) -> {
            Intent backIntent = new Intent(EndActivity.this, TeleActivity.class);
            startActivity(backIntent);
            return true;
        });

        L1button.setOnClickListener((v) -> {
            matchData.settClimb(1);
        });

        L2button.setOnClickListener((v) -> {
            matchData.settClimb(2);
        });

        L3button.setOnClickListener((v) -> {
            matchData.settClimb(3);
        });
        L0button.setOnClickListener((v) -> {
            matchData.settClimb(0);
        });
        if (!isNetworkConnected()) {
            submit.setText("Next");
        }
        D1.setOnClickListener((v) -> {
            matchData.setDefense(1);
        });

        D2.setOnClickListener((v) -> {
            matchData.setDefense(2);
        });

        D3.setOnClickListener((v) -> {
            matchData.setDefense(3);
        });
        D4.setOnClickListener((v) -> {
            matchData.setDefense(4);
        });
        D5.setOnClickListener((v) -> {
            matchData.setDefense(5);
        });
        D0.setOnClickListener((v) -> {
            matchData.setDefense(0);
        });
        DN1.setOnClickListener((v) -> {
            matchData.setDefense(-1);
        });
    }

    public void csvMake() {
        //adds the strings
        String CSVLine = MainActivity.matchData.makeCSVString();
        Log.d("matchData string", MainActivity.matchData.makeCSVString());

        //makes the file
        File csvFile = new File(this.getFilesDir(), MainActivity.matchData.getCSVFileName());
        Log.d("CSVFile", "File created/written at: " + csvFile.getAbsolutePath());
        //writes to file
        try (FileWriter writer = new FileWriter(csvFile, true)) {
            writer.append(CSVLine).append("\n");
            Log.d("CSVFilePath", csvFile.getAbsolutePath());
        } catch (IOException e) {
            Log.d("CSVFail", "CSV didn't make");
        }
    }

        public void offlinecsvMake() {
            // 1. Get the data string
            String dataRow = MainActivity.matchData.makeCSVString();

            // 2. Point to the file
            File csvFile = new File(this.getFilesDir(), "offlineData.csv");

            // 3. Write/Append to the file
            // 'true' means it adds to the bottom of the file
            try (FileWriter writer = new FileWriter(csvFile, true)) {
                writer.append(dataRow).append("\n");
                Log.d("CSVSuccess", "Appended to: " + csvFile.getAbsolutePath());
            } catch (IOException e) {
                Log.e("CSVFail", "Error writing to CSV", e);
            }
        }
    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        }
        return false;
    }

    public static String getTimestamp() {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy HH:mm:ss.SSS", Locale.getDefault());
        return sdf.format(new Date());
    }
}
