"use client"

import { createContext, useContext, useState, useEffect, type ReactNode } from "react"
import {
  products as initialProducts,
  categories as initialCategories,
  heroSlides as initialBanners,
  promotionalBanners as initialPromotionalBanners,
  type Product,
  type Category,
  type Banner,
  type Order,
} from "./data"

export interface StoreSettings {
  storeName: string
  storeLogo: string
  locationText: string
  contactEmail: string
  whatsappLink: string
  facebookLink: string
  tiktokLink: string
}

export interface PaymentSettings {
  easypaisaNumber: string
  jazzcashNumber: string
  bankName: string
  accountTitle: string
  accountNumber: string
  whatsappNumber: string
}

export interface BundleDeal {
  id: string
  name: string
  productIds: string[]
  bundlePrice: number
  discountPercent: number
  description: string
}

interface AdminContextType {
  isAuthenticated: boolean
  login: (password: string) => boolean
  logout: () => void
  products: Product[]
  categories: Category[]
  banners: Banner[]
  promotionalBanners: Banner[]
  orders: Order[]
  paymentSettings: PaymentSettings
  storeSettings: StoreSettings
  bundleDeals: BundleDeal[]
  updatePaymentSettings: (settings: Partial<PaymentSettings>) => void
  updateStoreSettings: (settings: Partial<StoreSettings>) => void
  addProduct: (product: Omit<Product, "id" | "slug">) => void
  updateProduct: (id: string, product: Partial<Product>) => void
  deleteProduct: (id: string) => void
  addCategory: (category: Omit<Category, "id">) => void
  updateCategory: (id: string, category: Partial<Category>) => void
  deleteCategory: (id: string) => void
  addBanner: (banner: Omit<Banner, "id">) => void
  updateBanner: (id: number, banner: Partial<Banner>) => void
  deleteBanner: (id: number) => void
  addPromotionalBanner: (banner: Omit<Banner, "id">) => void
  updatePromotionalBanner: (id: number, banner: Partial<Banner>) => void
  deletePromotionalBanner: (id: number) => void
  addBundleDeal: (deal: Omit<BundleDeal, "id">) => void
  updateBundleDeal: (id: string, deal: Partial<BundleDeal>) => void
  deleteBundleDeal: (id: string) => void
  updateOrderStatus: (id: string, status: Order["status"]) => void
  addOrder: (order: Omit<Order, "id" | "date">) => string
}

const AdminContext = createContext<AdminContextType | undefined>(undefined)

const ADMIN_PASSWORD = "KhanAdultStore2025@"

const defaultStoreSettings: StoreSettings = {
  storeName: "Vimax by Khan Traders",
  storeLogo: "🏥",
  locationText: "Fast Delivery in Peshawar & All Pakistan",
  contactEmail: "tktradar123@gmail.com",
  whatsappLink: "https://wa.me/03128627995",
  facebookLink: "https://facebook.com",
  tiktokLink: "https://tiktok.com",
}

const defaultPaymentSettings: PaymentSettings = {
  easypaisaNumber: "03128627995",
  jazzcashNumber: "03128627995",
  bankName: "Meezan Bank",
  accountTitle: "Khan Traders",
  accountNumber: "PK36MEZN0001234567890123",
  whatsappNumber: "03128627995",
}

export function AdminProvider({ children }: { children: ReactNode }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [products, setProducts] = useState<Product[]>(initialProducts)
  const [categories, setCategories] = useState<Category[]>(initialCategories)
  const [banners, setBanners] = useState<Banner[]>(initialBanners)
  const [promotionalBanners, setPromotionalBanners] = useState<Banner[]>(initialPromotionalBanners)
  const [orders, setOrders] = useState<Order[]>([])
  const [paymentSettings, setPaymentSettings] = useState<PaymentSettings>(defaultPaymentSettings)
  const [storeSettings, setStoreSettings] = useState<StoreSettings>(defaultStoreSettings)
  const [bundleDeals, setBundleDeals] = useState<BundleDeal[]>([])

  useEffect(() => {
    const authStatus = sessionStorage.getItem("adminAuth")
    if (authStatus === "true") {
      setIsAuthenticated(true)
    }
    const savedSettings = localStorage.getItem("paymentSettings")
    if (savedSettings) {
      setPaymentSettings(JSON.parse(savedSettings))
    }
    const savedStoreSettings = localStorage.getItem("storeSettings")
    if (savedStoreSettings) {
      setStoreSettings(JSON.parse(savedStoreSettings))
    }
    const savedOrders = localStorage.getItem("orders")
    if (savedOrders) {
      setOrders(JSON.parse(savedOrders))
    }
    const savedPromoBanners = localStorage.getItem("promotionalBanners")
    if (savedPromoBanners) {
      setPromotionalBanners(JSON.parse(savedPromoBanners))
    }
    const savedBundleDeals = localStorage.getItem("bundleDeals")
    if (savedBundleDeals) {
      setBundleDeals(JSON.parse(savedBundleDeals))
    }
  }, [])

  useEffect(() => {
    localStorage.setItem("orders", JSON.stringify(orders))
  }, [orders])

  useEffect(() => {
    localStorage.setItem("promotionalBanners", JSON.stringify(promotionalBanners))
  }, [promotionalBanners])

  useEffect(() => {
    localStorage.setItem("bundleDeals", JSON.stringify(bundleDeals))
  }, [bundleDeals])

  const login = (password: string) => {
    if (password === ADMIN_PASSWORD) {
      setIsAuthenticated(true)
      sessionStorage.setItem("adminAuth", "true")
      return true
    }
    return false
  }

  const logout = () => {
    setIsAuthenticated(false)
    sessionStorage.removeItem("adminAuth")
  }

  const updatePaymentSettings = (settings: Partial<PaymentSettings>) => {
    setPaymentSettings((prev) => {
      const updated = { ...prev, ...settings }
      localStorage.setItem("paymentSettings", JSON.stringify(updated))
      return updated
    })
  }

  const updateStoreSettings = (settings: Partial<StoreSettings>) => {
    setStoreSettings((prev) => {
      const updated = { ...prev, ...settings }
      localStorage.setItem("storeSettings", JSON.stringify(updated))
      return updated
    })
  }

  const generateSlug = (name: string) => {
    return name
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/(^-|-$)/g, "")
  }

  const addOrder = (order: Omit<Order, "id" | "date">) => {
    const orderId = `ORD-${Date.now()}`
    const newOrder: Order = {
      ...order,
      id: orderId,
      date: new Date().toISOString().split("T")[0],
    }
    setOrders((prev) => [newOrder, ...prev])
    return orderId
  }

  const addProduct = (product: Omit<Product, "id" | "slug">) => {
    const newProduct: Product = {
      ...product,
      id: String(Date.now()),
      slug: generateSlug(product.name),
    }
    setProducts((prev) => [...prev, newProduct])
  }

  const updateProduct = (id: string, product: Partial<Product>) => {
    setProducts((prev) =>
      prev.map((p) =>
        p.id === id ? { ...p, ...product, slug: product.name ? generateSlug(product.name) : p.slug } : p,
      ),
    )
  }

  const deleteProduct = (id: string) => {
    setProducts((prev) => prev.filter((p) => p.id !== id))
  }

  const addCategory = (category: Omit<Category, "id">) => {
    const newCategory: Category = {
      ...category,
      id: String(Date.now()),
    }
    setCategories((prev) => [...prev, newCategory])
  }

  const updateCategory = (id: string, category: Partial<Category>) => {
    setCategories((prev) => prev.map((c) => (c.id === id ? { ...c, ...category } : c)))
  }

  const deleteCategory = (id: string) => {
    setCategories((prev) => prev.filter((c) => c.id !== id))
  }

  const addBanner = (banner: Omit<Banner, "id">) => {
    const newBanner: Banner = {
      ...banner,
      id: Date.now(),
    }
    setBanners((prev) => [...prev, newBanner])
  }

  const updateBanner = (id: number, banner: Partial<Banner>) => {
    setBanners((prev) => prev.map((b) => (b.id === id ? { ...b, ...banner } : b)))
  }

  const deleteBanner = (id: number) => {
    setBanners((prev) => prev.filter((b) => b.id !== id))
  }

  const addPromotionalBanner = (banner: Omit<Banner, "id">) => {
    const newBanner: Banner = {
      ...banner,
      id: Date.now(),
      section: "promotional",
    }
    setPromotionalBanners((prev) => [...prev, newBanner])
  }

  const updatePromotionalBanner = (id: number, banner: Partial<Banner>) => {
    setPromotionalBanners((prev) => prev.map((b) => (b.id === id ? { ...b, ...banner } : b)))
  }

  const deletePromotionalBanner = (id: number) => {
    setPromotionalBanners((prev) => prev.filter((b) => b.id !== id))
  }

  const addBundleDeal = (deal: Omit<BundleDeal, "id">) => {
    const newDeal: BundleDeal = {
      ...deal,
      id: String(Date.now()),
    }
    setBundleDeals((prev) => [...prev, newDeal])
  }

  const updateBundleDeal = (id: string, deal: Partial<BundleDeal>) => {
    setBundleDeals((prev) => prev.map((d) => (d.id === id ? { ...d, ...deal } : d)))
  }

  const deleteBundleDeal = (id: string) => {
    setBundleDeals((prev) => prev.filter((d) => d.id !== id))
  }

  const updateOrderStatus = (id: string, status: Order["status"]) => {
    setOrders((prev) => prev.map((o) => (o.id === id ? { ...o, status } : o)))
  }

  return (
    <AdminContext.Provider
      value={{
        isAuthenticated,
        login,
        logout,
        products,
        categories,
        banners,
        promotionalBanners,
        orders,
        paymentSettings,
        storeSettings,
        bundleDeals,
        updatePaymentSettings,
        updateStoreSettings,
        addProduct,
        updateProduct,
        deleteProduct,
        addCategory,
        updateCategory,
        deleteCategory,
        addBanner,
        updateBanner,
        deleteBanner,
        addPromotionalBanner,
        updatePromotionalBanner,
        deletePromotionalBanner,
        addBundleDeal,
        updateBundleDeal,
        deleteBundleDeal,
        updateOrderStatus,
        addOrder,
      }}
    >
      {children}
    </AdminContext.Provider>
  )
}

export function useAdmin() {
  const context = useContext(AdminContext)
  if (!context) {
    throw new Error("useAdmin must be used within an AdminProvider")
  }
  return context
}
