"use client";

import React, { createContext, useContext, useState, useEffect } from "react";
import { Product, OrderItem, mockProducts } from "@/data/mockData";

export type CurrencyCode = "PKR" | "USD" | "EUR" | "GBP";

export interface SiteConfig {
  contactPhone: string;
  whatsappNumber: string;
  address: string;
  instagram: string;
  facebook: string;
  tiktok: string;
  paymentMethods: {
    cod: boolean;
    bankTransfer: boolean;
    easypaisa: boolean;
    jazzcash: boolean;
    stripe: boolean;
  };
  deliveryIntegrations: {
    tcs: boolean;
    leopards: boolean;
    postex: boolean;
  };
  courierConfig?: {
    tcs: { apiKey: string; merchantId: string; clientName: string; isSandbox: boolean };
    leopards: { apiKey: string; apiPassword: string; merchantId: string; isSandbox: boolean };
    postex: { apiKey: string; clientId: string; isSandbox: boolean };
  };
  paymentConfig?: {
    stripe: { publishableKey: string; secretKey: string };
    easypaisa: { storeId: string; hashKey: string; receiverPhone: string };
    jazzcash: { merchantId: string; password: string; integritySalt: string };
    bankTransfer: { bankName: string; accountTitle: string; accountNumber: string; iban: string };
    cod: { instructions: string };
  };
}

export interface UserProfile {
  email: string;
  name: string;
  role: "user" | "admin";
  points: number;
  tier: "Bronze" | "Silver" | "Gold" | "VIP";
  wishlist: string[];
  addresses: string[];
}

interface Message {
  id: string;
  sender: "user" | "ai";
  text: string;
}

interface AppContextProps {
  // Cart
  cart: OrderItem[];
  addToCart: (product: Product, quantity: number, size: string, color: string) => void;
  removeFromCart: (itemId: string, size: string, color: string) => void;
  updateCartQty: (itemId: string, size: string, color: string, qty: number) => void;
  clearCart: () => void;
  couponCode: string;
  applyCoupon: (code: string) => boolean;
  discountPercent: number;
  shippingEstimate: number;
  getCartSubtotal: () => number;
  getCartTotal: () => number;
  
  // Wishlist
  wishlist: string[];
  toggleWishlist: (productId: string) => void;
  
  // Currency
  currency: CurrencyCode;
  setCurrency: (code: CurrencyCode) => void;
  convertPrice: (pkrPrice: number) => { value: number; symbol: string };
  formatPrice: (pkrPrice: number) => string;
  
  t: (key: string) => string;
  
  // AI Assistant
  isAiOpen: boolean;
  setIsAiOpen: (open: boolean) => void;
  aiMessages: Message[];
  sendAiMessage: (text: string) => void;
  resetAiChat: () => void;
  
  // User Auth
  user: UserProfile | null;
  login: (email: string) => void;
  logout: () => void;

  // Site Config
  siteConfig: SiteConfig;
  updateSiteConfig: (config: SiteConfig) => void;
}

const AppContext = createContext<AppContextProps | undefined>(undefined);

const RATES: Record<CurrencyCode, number> = {
  PKR: 1,
  USD: 0.0036, // 1 USD = 278 PKR approx
  EUR: 0.0033, // 1 EUR = 300 PKR approx
  GBP: 0.0028, // 1 GBP = 350 PKR approx
};

const SYMBOLS: Record<CurrencyCode, string> = {
  PKR: "Rs. ",
  USD: "$",
  EUR: "€",
  GBP: "£",
};

export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [cart, setCart] = useState<OrderItem[]>([]);
  const [wishlist, setWishlist] = useState<string[]>([]);
  const [currency, setCurrency] = useState<CurrencyCode>("PKR");
  const [couponCode, setCouponCode] = useState("");
  const [discountPercent, setDiscountPercent] = useState(0);
  const [isAiOpen, setIsAiOpen] = useState(false);
  const [aiMessages, setAiMessages] = useState<Message[]>([
    {
      id: "ai-init",
      sender: "ai",
      text: "Welcome to STARBOY PAKISTAN. I am your AI Stylist. Looking for outfit recommendations, sizing help, or specific fabric weights (GSM)?"
    }
  ]);
  const [user, setUser] = useState<UserProfile | null>(null);

  const [siteConfig, setSiteConfig] = useState<SiteConfig>({
    contactPhone: "+92 300 0000000",
    whatsappNumber: "923000000000",
    address: "Starboy HQ, DHA Phase 5, Lahore, Pakistan",
    instagram: "starboypakistan",
    facebook: "starboy.pk",
    tiktok: "starboypakistan",
    paymentMethods: {
      cod: true,
      bankTransfer: true,
      easypaisa: true,
      jazzcash: true,
      stripe: true,
    },
    deliveryIntegrations: {
      tcs: true,
      leopards: true,
      postex: true,
    },
    courierConfig: {
      tcs: { apiKey: "tcs_prod_key_77a9", merchantId: "tcs_merchant_002", clientName: "STARBOY_PK", isSandbox: true },
      leopards: { apiKey: "leo_key_9281a8b", apiPassword: "leo_password_9210", merchantId: "92812", isSandbox: true },
      postex: { apiKey: "postex_api_91a823c10", clientId: "sb_client_1120", isSandbox: true }
    },
    paymentConfig: {
      stripe: { publishableKey: "pk_test_51N...", secretKey: "sk_test_51N..." },
      easypaisa: { storeId: "82918", hashKey: "eh_9281a8c91a", receiverPhone: "+92 300 1234567" },
      jazzcash: { merchantId: "jc_8291a", password: "jc_password", integritySalt: "jc_salt_123" },
      bankTransfer: { bankName: "Meezan Bank Ltd", accountTitle: "STARBOY PAKISTAN", accountNumber: "02840294019284", iban: "PK92MEZN02840294019284" },
      cod: { instructions: "Please keep exact Cash amount ready for dispatch courier delivery." }
    }
  });

  // Load cart and wishlist from localStorage on mount
  useEffect(() => {
    const savedCart = localStorage.getItem("starboy_cart");
    const savedWish = localStorage.getItem("starboy_wishlist");
    const savedUser = localStorage.getItem("starboy_user");
    const savedConfig = localStorage.getItem("starboy_site_config");
    
    if (savedCart) setCart(JSON.parse(savedCart));
    if (savedWish) setWishlist(JSON.parse(savedWish));
    if (savedUser) setUser(JSON.parse(savedUser));
    if (savedConfig) setSiteConfig(JSON.parse(savedConfig));
  }, []);

  const updateSiteConfig = (newConfig: SiteConfig) => {
    setSiteConfig(newConfig);
    localStorage.setItem("starboy_site_config", JSON.stringify(newConfig));
  };

  // Sync cart
  const saveCart = (newCart: OrderItem[]) => {
    setCart(newCart);
    localStorage.setItem("starboy_cart", JSON.stringify(newCart));
  };

  // Sync wishlist
  const saveWishlist = (newWish: string[]) => {
    setWishlist(newWish);
    localStorage.setItem("starboy_wishlist", JSON.stringify(newWish));
  };

  // Cart actions
  const addToCart = (product: Product, quantity: number, size: string, color: string) => {
    const existingIndex = cart.findIndex(
      (item) => item.id === product.id && item.size === size && item.color === color
    );

    if (existingIndex > -1) {
      const newCart = [...cart];
      newCart[existingIndex].quantity += quantity;
      saveCart(newCart);
    } else {
      const newItem: OrderItem = {
        id: product.id,
        name: product.name,
        price: product.price * (1 - product.discount / 100),
        quantity,
        size,
        color,
        image: product.image,
      };
      saveCart([...cart, newItem]);
    }
  };

  const removeFromCart = (itemId: string, size: string, color: string) => {
    const newCart = cart.filter(
      (item) => !(item.id === itemId && item.size === size && item.color === color)
    );
    saveCart(newCart);
  };

  const updateCartQty = (itemId: string, size: string, color: string, qty: number) => {
    if (qty <= 0) {
      removeFromCart(itemId, size, color);
      return;
    }
    const newCart = cart.map((item) =>
      item.id === itemId && item.size === size && item.color === color
        ? { ...item, quantity: qty }
        : item
    );
    saveCart(newCart);
  };

  const clearCart = () => {
    saveCart([]);
    setCouponCode("");
    setDiscountPercent(0);
  };

  const applyCoupon = (code: string) => {
    const match = code.toUpperCase().trim();
    if (match === "STARBOY10" || match === "WELCOME10") {
      setCouponCode(match);
      setDiscountPercent(10);
      return true;
    } else if (match === "FLASH20") {
      setCouponCode(match);
      setDiscountPercent(20);
      return true;
    }
    return false;
  };

  const getCartSubtotal = () => {
    return cart.reduce((acc, item) => acc + item.price * item.quantity, 0);
  };

  const shippingEstimate = 250; // standard flat rate delivery PKR

  const getCartTotal = () => {
    const sub = getCartSubtotal();
    const discount = sub * (discountPercent / 100);
    return sub - discount + (sub > 0 ? shippingEstimate : 0);
  };

  // Wishlist actions
  const toggleWishlist = (productId: string) => {
    if (wishlist.includes(productId)) {
      const newWish = wishlist.filter((id) => id !== productId);
      saveWishlist(newWish);
    } else {
      saveWishlist([...wishlist, productId]);
    }
  };

  // Currency converter
  const convertPrice = (pkrPrice: number) => {
    const rate = RATES[currency];
    const converted = pkrPrice * rate;
    return {
      value: Number(converted.toFixed(currency === "PKR" ? 0 : 2)),
      symbol: SYMBOLS[currency],
    };
  };

  const formatPrice = (pkrPrice: number) => {
    const { value, symbol } = convertPrice(pkrPrice);
    if (currency === "PKR") {
      return `${symbol}${value.toLocaleString()}`;
    }
    return `${symbol}${value.toFixed(2)}`;
  };

  // Language Translator
  const t = (key: string): string => {
    // Default to key or parse readable string
    return key.replace(/^[a-z]+\./, "").replace(/_/g, " ").toUpperCase();
  };

  // AI Assistant responses
  const sendAiMessage = (text: string) => {
    const userMsg: Message = { id: `user-${Date.now()}`, sender: "user", text };
    setAiMessages((prev) => [...prev, userMsg]);

    // Simple delay for AI typing
    setTimeout(() => {
      let aiText = "I couldn't quite matching that details. I recommend our 240 GSM STARBOY HEAVYWEIGHT TEE in Matte Black.";
      const input = text.toLowerCase();

      if (input.includes("size") || input.includes("fit") || input.includes("height")) {
        aiText = "Based on your measurements: heights between 5'7\" and 5'10\" fit perfectly in size Medium for a slouchy oversized look. For 6'0\"+, we recommend a Large. Do you want me to add a size Medium Tee to your checkout?";
      } else if (input.includes("gsm") || input.includes("cotton") || input.includes("fabric")) {
        aiText = "We offer 240 GSM for our heavyweight tees and 420 GSM for hoodies. It uses 100% pre-shrunk combed cotton which holds its architectural form better than typical fast fashion.";
      } else if (input.includes("price") || input.includes("cost") || input.includes("pkr")) {
        aiText = "Tees start at Rs. 3,890, and hoodies are Rs. 8,490. You can toggle currency to USD, EUR, or GBP at the top navigation panel.";
      } else if (input.includes("order") || input.includes("ship") || input.includes("delivery")) {
        aiText = "We deliver nationwide in Pakistan within 2-4 business days using TCS and Leopards Courier. Cash on Delivery is supported at checkout.";
      } else if (input.includes("recommend") || input.includes("best") || input.includes("outfit")) {
        aiText = "The ultimate street outfit: Pair the 420 GSM OVERSIZED UTILITY HOODIE in Sand Grey with our SIGNATURE LOOPBACK SWEATPANTS in Off-White. Shall I show you the products?";
      }

      const aiMsg: Message = { id: `ai-${Date.now()}`, sender: "ai", text: aiText };
      setAiMessages((prev) => [...prev, aiMsg]);
    }, 800);
  };

  const resetAiChat = () => {
    setAiMessages([
      {
        id: "ai-init",
        sender: "ai",
        text: "Welcome to STARBOY PAKISTAN. I am your AI Stylist. Looking for outfit recommendations, sizing help, or specific fabric weights (GSM)?"
      }
    ]);
  };

  // Auth mock
  const login = (email: string) => {
    const mockUser: UserProfile = {
      email,
      name: email.split("@")[0].toUpperCase(),
      role: email.includes("admin") ? "admin" : "user",
      points: 450,
      tier: "Silver",
      wishlist: [],
      addresses: ["House 12-A, Street 4, DHA Phase 6, Lahore, Pakistan"],
    };
    setUser(mockUser);
    localStorage.setItem("starboy_user", JSON.stringify(mockUser));
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem("starboy_user");
  };

  return (
    <AppContext.Provider
      value={{
        cart,
        addToCart,
        removeFromCart,
        updateCartQty,
        clearCart,
        couponCode,
        applyCoupon,
        discountPercent,
        shippingEstimate,
        getCartSubtotal,
        getCartTotal,
        wishlist,
        toggleWishlist,
        currency,
        setCurrency,
        convertPrice,
        formatPrice,
        t,
        isAiOpen,
        setIsAiOpen,
        aiMessages,
        sendAiMessage,
        resetAiChat,
        user,
        login,
        logout,
        siteConfig,
        updateSiteConfig,
      }}
    >
      {children}
    </AppContext.Provider>
  );
};

export const useApp = () => {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error("useApp must be used within an AppProvider");
  }
  return context;
};
