package com.qrcodestudio;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.getcapacitor.JSArray;
import com.getcapacitor.JSObject;

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

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;

public class QRCodeStudio {
    private static final String TAG = "QRCodeStudio";
    private static final String PREFS_NAME = "QRCodeStudioPrefs";
    private static final String HISTORY_KEY = "qr_history";
    private static final int MAX_HISTORY_ITEMS = 100;
    
    private Context context;
    private SharedPreferences preferences;
    
    public void initialize(Context context) {
        this.context = context;
        this.preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }
    
    public JSObject parseScanResult(String content) {
        JSObject result = new JSObject();
        result.put("content", content);
        result.put("type", detectQRType(content));
        result.put("data", parseQRContent(content));
        result.put("timestamp", getISO8601Timestamp());
        return result;
    }
    
    public void saveToHistory(JSObject item) {
        try {
            JSONArray history = getHistoryArray();
            
            // Add new item
            JSONObject newItem = new JSONObject(item.toString());
            newItem.put("id", UUID.randomUUID().toString());
            newItem.put("timestamp", getISO8601Timestamp());
            
            // Insert at beginning
            JSONArray newHistory = new JSONArray();
            newHistory.put(newItem);
            
            // Add existing items (up to MAX_HISTORY_ITEMS - 1)
            int limit = Math.min(history.length(), MAX_HISTORY_ITEMS - 1);
            for (int i = 0; i < limit; i++) {
                newHistory.put(history.get(i));
            }
            
            // Save to preferences
            preferences.edit()
                .putString(HISTORY_KEY, newHistory.toString())
                .apply();
                
        } catch (JSONException e) {
            Log.e(TAG, "Failed to save history item", e);
        }
    }
    
    public JSArray getHistory() {
        try {
            JSONArray history = getHistoryArray();
            return JSArray.fromJSONArray(history);
        } catch (JSONException e) {
            Log.e(TAG, "Failed to get history", e);
            return new JSArray();
        }
    }
    
    public void clearHistory() {
        preferences.edit()
            .remove(HISTORY_KEY)
            .apply();
    }
    
    private JSONArray getHistoryArray() throws JSONException {
        String historyJson = preferences.getString(HISTORY_KEY, "[]");
        return new JSONArray(historyJson);
    }
    
    private String detectQRType(String content) {
        if (content.startsWith("http://") || content.startsWith("https://")) {
            return "website";
        } else if (content.startsWith("mailto:")) {
            return "email";
        } else if (content.startsWith("tel:")) {
            return "phone";
        } else if (content.startsWith("sms:") || content.startsWith("smsto:")) {
            return "sms";
        } else if (content.startsWith("WIFI:")) {
            return "wifi";
        } else if (content.startsWith("BEGIN:VCARD")) {
            return "vcard";
        } else if (content.startsWith("geo:")) {
            return "location";
        } else if (content.startsWith("BEGIN:VEVENT")) {
            return "event";
        } else if (content.startsWith("bitcoin:") || content.startsWith("ethereum:")) {
            return "crypto";
        } else if (content.startsWith("whatsapp://")) {
            return "whatsapp";
        } else if (content.startsWith("fb://") || content.startsWith("https://www.facebook.com/")) {
            return "facebook";
        } else if (content.startsWith("instagram://") || content.startsWith("https://www.instagram.com/")) {
            return "instagram";
        } else {
            return "text";
        }
    }
    
    private JSObject parseQRContent(String content) {
        JSObject data = new JSObject();
        String type = detectQRType(content);
        
        switch (type) {
            case "website":
                data.put("url", content);
                break;
                
            case "wifi":
                parseWifiContent(content, data);
                break;
                
            case "email":
                parseEmailContent(content, data);
                break;
                
            case "phone":
                data.put("phoneNumber", content.replace("tel:", ""));
                break;
                
            case "sms":
                parseSmsContent(content, data);
                break;
                
            case "vcard":
                parseVCardContent(content, data);
                break;
                
            case "location":
                parseLocationContent(content, data);
                break;
                
            case "event":
                parseEventContent(content, data);
                break;
                
            case "crypto":
                parseCryptoContent(content, data);
                break;
                
            case "whatsapp":
                parseWhatsAppContent(content, data);
                break;
                
            default:
                data.put("text", content);
                break;
        }
        
        return data;
    }
    
    private void parseWifiContent(String content, JSObject data) {
        String[] parts = content.replace("WIFI:", "").split(";");
        for (String part : parts) {
            if (part.startsWith("T:")) {
                data.put("security", part.substring(2));
            } else if (part.startsWith("S:")) {
                data.put("ssid", part.substring(2));
            } else if (part.startsWith("P:")) {
                data.put("password", part.substring(2));
            } else if (part.startsWith("H:")) {
                data.put("hidden", "true".equals(part.substring(2)));
            }
        }
    }
    
    private void parseEmailContent(String content, JSObject data) {
        try {
            String email = content.replace("mailto:", "");
            String[] parts = email.split("\\?", 2);
            
            data.put("to", parts[0]);
            
            if (parts.length > 1) {
                String[] params = parts[1].split("&");
                for (String param : params) {
                    String[] keyValue = param.split("=", 2);
                    if (keyValue.length == 2) {
                        String key = keyValue[0];
                        String value = java.net.URLDecoder.decode(keyValue[1], "UTF-8");
                        
                        if ("subject".equals(key)) {
                            data.put("subject", value);
                        } else if ("body".equals(key)) {
                            data.put("body", value);
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Failed to parse email content", e);
        }
    }
    
    private void parseSmsContent(String content, JSObject data) {
        try {
            String sms = content.replace("sms:", "").replace("smsto:", "");
            String[] parts = sms.split("\\?", 2);
            
            data.put("phoneNumber", parts[0]);
            
            if (parts.length > 1 && parts[1].startsWith("body=")) {
                String body = java.net.URLDecoder.decode(parts[1].substring(5), "UTF-8");
                data.put("message", body);
            }
        } catch (Exception e) {
            Log.e(TAG, "Failed to parse SMS content", e);
        }
    }
    
    private void parseVCardContent(String content, JSObject data) {
        String[] lines = content.split("\n");
        for (String line : lines) {
            if (line.startsWith("FN:")) {
                String fullName = line.substring(3);
                data.put("fullName", fullName);
                
                // Try to split into first and last name
                String[] nameParts = fullName.split(" ", 2);
                if (nameParts.length >= 1) {
                    data.put("firstName", nameParts[0]);
                }
                if (nameParts.length >= 2) {
                    data.put("lastName", nameParts[1]);
                }
            } else if (line.startsWith("ORG:")) {
                data.put("organization", line.substring(4));
            } else if (line.startsWith("TEL:")) {
                data.put("phone", line.substring(4));
            } else if (line.startsWith("EMAIL:")) {
                data.put("email", line.substring(6));
            } else if (line.startsWith("URL:")) {
                data.put("website", line.substring(4));
            } else if (line.startsWith("ADR:")) {
                data.put("address", line.substring(4));
            }
        }
    }
    
    private void parseLocationContent(String content, JSObject data) {
        try {
            String coords = content.replace("geo:", "");
            String[] parts = coords.split(",");
            if (parts.length >= 2) {
                data.put("latitude", Double.parseDouble(parts[0]));
                data.put("longitude", Double.parseDouble(parts[1]));
                if (parts.length > 2) {
                    data.put("altitude", Double.parseDouble(parts[2]));
                }
            }
        } catch (NumberFormatException e) {
            Log.e(TAG, "Failed to parse location content", e);
        }
    }
    
    private void parseEventContent(String content, JSObject data) {
        String[] lines = content.split("\n");
        for (String line : lines) {
            if (line.startsWith("SUMMARY:")) {
                data.put("title", line.substring(8));
            } else if (line.startsWith("DTSTART:")) {
                data.put("start", line.substring(8));
            } else if (line.startsWith("DTEND:")) {
                data.put("end", line.substring(6));
            } else if (line.startsWith("LOCATION:")) {
                data.put("location", line.substring(9));
            } else if (line.startsWith("DESCRIPTION:")) {
                data.put("description", line.substring(12));
            }
        }
    }
    
    private void parseCryptoContent(String content, JSObject data) {
        try {
            String[] parts = content.split(":");
            if (parts.length >= 2) {
                data.put("currency", parts[0]);
                
                String[] addressParts = parts[1].split("\\?");
                data.put("address", addressParts[0]);
                
                if (addressParts.length > 1) {
                    String[] params = addressParts[1].split("&");
                    for (String param : params) {
                        String[] keyValue = param.split("=", 2);
                        if (keyValue.length == 2 && "amount".equals(keyValue[0])) {
                            data.put("amount", Double.parseDouble(keyValue[1]));
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Failed to parse crypto content", e);
        }
    }
    
    private void parseWhatsAppContent(String content, JSObject data) {
        try {
            if (content.startsWith("whatsapp://send?")) {
                String params = content.substring("whatsapp://send?".length());
                String[] pairs = params.split("&");
                
                for (String pair : pairs) {
                    String[] keyValue = pair.split("=", 2);
                    if (keyValue.length == 2) {
                        String key = keyValue[0];
                        String value = java.net.URLDecoder.decode(keyValue[1], "UTF-8");
                        
                        if ("phone".equals(key)) {
                            data.put("phoneNumber", value);
                        } else if ("text".equals(key)) {
                            data.put("message", value);
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Failed to parse WhatsApp content", e);
        }
    }
    
    private String getISO8601Timestamp() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        return sdf.format(new Date());
    }
}