package com.brisco.meatwholesaler;

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

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Check demo status first
        DemoManager demoManager = new DemoManager(this);
        demoManager.recordFirstLaunch();
        
        if (demoManager.isDemoExpired()) {
            // Redirect to demo expired screen
            Intent intent = new Intent(this, DemoExpiredActivity.class);
            startActivity(intent);
            finish();
            return;
        }
        
        setContentView(R.layout.activity_main);

        // Setup demo status
        updateDemoStatus(demoManager);

        // Setup toolbar
        androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Setup drawer
        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);

        // Setup FAB for cart
        FloatingActionButton fabCart = findViewById(R.id.fab_cart);
        fabCart.setOnClickListener(view -> {
            Intent cartIntent = new Intent(MainActivity.this, CartActivity.class);
            startActivity(cartIntent);
        });

        // Setup hamper button
        findViewById(R.id.btn_view_hamper).setOnClickListener(v -> {
            Intent productIntent = new Intent(MainActivity.this, ProductDetailActivity.class);
            productIntent.putExtra("PRODUCT_ID", "jade_hamper");
            productIntent.putExtra("PRODUCT_NAME", "JADE HAMPER");
            productIntent.putExtra("PRODUCT_PRICE", 2999.99);
            productIntent.putExtra("PRODUCT_DESCRIPTION", "23 KG Premium Quality Meat - 52% Beef | 9% Lamb | 17% Pork | 22% Chicken");
            productIntent.putExtra("PRODUCT_IMAGE", "jade_hamper");
            startActivity(productIntent);
        });

        // Setup categories (for demo purposes)
        setupCategories();
    }

    private void setupCategories() {
        // This would typically load from API or database
        // For now, we'll set up click listeners for demo
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_cart) {
            Intent cartIntent = new Intent(this, CartActivity.class);
            startActivity(cartIntent);
            return true;
        } else if (id == R.id.action_search) {
            Toast.makeText(this, "Search functionality coming soon", Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.nav_home) {
            // Already on home
        } else if (id == R.id.nav_bulk_hampers) {
            openCategoryActivity("bulk_hampers", "Bulk Hampers");
        } else if (id == R.id.nav_master_wors) {
            openCategoryActivity("master_wors", "Master Wors Range®");
        } else if (id == R.id.nav_beef) {
            openCategoryActivity("beef", "Beef");
        } else if (id == R.id.nav_chicken) {
            openCategoryActivity("chicken", "Chicken");
        } else if (id == R.id.nav_pork) {
            openCategoryActivity("pork", "Pork");
        } else if (id == R.id.nav_lamb) {
            openCategoryActivity("lamb", "Lamb");
        } else if (id == R.id.nav_ostrich) {
            openCategoryActivity("ostrich", "Ostrich");
        } else if (id == R.id.nav_pies) {
            openCategoryActivity("pies", "Piemans Assorted Pies");
        } else if (id == R.id.nav_restaurant) {
            openCategoryActivity("restaurant", "Restaurant Sector");
        } else if (id == R.id.nav_specials) {
            openCategoryActivity("specials", "On Special");
        } else if (id == R.id.nav_about) {
            openAboutActivity();
        } else if (id == R.id.nav_contact) {
            openContactActivity();
        } else if (id == R.id.nav_account) {
            openAccountActivity();
        } else if (id == R.id.nav_orders) {
            openOrdersActivity();
        } else if (id == R.id.nav_logout) {
            logout();
        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void openCategoryActivity(String categoryId, String categoryName) {
        try {
            Intent intent = new Intent(this, CategoryActivity.class);
            intent.putExtra("CATEGORY_ID", categoryId);
            intent.putExtra("CATEGORY_NAME", categoryName);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "Unable to open " + categoryName, Toast.LENGTH_SHORT).show();
        }
    }

    private void openAboutActivity() {
        try {
            Intent intent = new Intent(this, AboutActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "Unable to open About page", Toast.LENGTH_SHORT).show();
        }
    }

    private void openContactActivity() {
        try {
            Intent intent = new Intent(this, ContactActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "Unable to open Contact page", Toast.LENGTH_SHORT).show();
        }
    }

    private void openAccountActivity() {
        try {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "Unable to open Account page", Toast.LENGTH_SHORT).show();
        }
    }

    private void openOrdersActivity() {
        try {
            Intent intent = new Intent(this, OrdersActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "Unable to open Orders page", Toast.LENGTH_SHORT).show();
        }
    }

    private void logout() {
        try {
            // Clear user session
            getSharedPreferences("BriscoPrefs", MODE_PRIVATE).edit().clear().apply();
            
            // Redirect to login
            Intent intent = new Intent(this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();
        } catch (Exception e) {
            Toast.makeText(this, "Unable to logout", Toast.LENGTH_SHORT).show();
        }
    }

    private void updateDemoStatus(DemoManager demoManager) {
        TextView textDemoRemaining = findViewById(R.id.text_demo_remaining);
        if (textDemoRemaining != null) {
            String remainingTime = demoManager.getRemainingTimeString();
            textDemoRemaining.setText(remainingTime + " remaining");
            
            // Change color based on urgency
            long remainingDays = demoManager.getRemainingDays();
            if (remainingDays <= 1) {
                textDemoRemaining.setTextColor(getResources().getColor(android.R.color.holo_orange_light));
            } else if (remainingDays <= 0) {
                textDemoRemaining.setTextColor(getResources().getColor(android.R.color.holo_red_light));
            }
        }
    }
}
