import { create } from 'zustand';

// ============ LOCAL STORAGE PERSISTENCE ============
const ADMIN_USER_KEY = 'needyfy_admin_user';
const ADMIN_TOKEN_KEY = 'needyfy_admin_token';
const SECTION_KEY = 'needyfy_current_section';
const USER_KEY = 'needyfy_user';
const USER_TOKEN_KEY = 'needyfy_user_token';
const LANGUAGE_KEY = 'needyfy_language';

function loadAdminFromStorage(): { adminUser: Record<string, unknown> | null; adminToken: string | null } {
  if (typeof window === 'undefined') return { adminUser: null, adminToken: null };
  try {
    const userStr = localStorage.getItem(ADMIN_USER_KEY);
    const tokenStr = localStorage.getItem(ADMIN_TOKEN_KEY);
    if (userStr && tokenStr) {
      return {
        adminUser: JSON.parse(userStr) as Record<string, unknown>,
        adminToken: tokenStr,
      };
    }
  } catch { /* ignore */ }
  return { adminUser: null, adminToken: null };
}

function saveAdminToStorage(admin: Record<string, unknown> | null, token: string | null) {
  if (typeof window === 'undefined') return;
  try {
    if (admin && token) {
      localStorage.setItem(ADMIN_USER_KEY, JSON.stringify(admin));
      localStorage.setItem(ADMIN_TOKEN_KEY, token);
    } else {
      localStorage.removeItem(ADMIN_USER_KEY);
      localStorage.removeItem(ADMIN_TOKEN_KEY);
    }
  } catch { /* ignore */ }
}

function saveSectionToStorage(section: AppSection) {
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(SECTION_KEY, section);
  } catch { /* ignore */ }
}

function loadSectionFromStorage(): AppSection | null {
  if (typeof window === 'undefined') return null;
  try {
    const val = localStorage.getItem(SECTION_KEY);
    if (val) return val as AppSection;
  } catch { /* ignore */ }
  return null;
}

function loadUserFromStorage(): { id: string; name: string; email: string; phone?: string; avatar?: string; roles: string[] } | null {
  if (typeof window === 'undefined') return null;
  try {
    const userStr = localStorage.getItem(USER_KEY);
    if (userStr) return JSON.parse(userStr);
  } catch { /* ignore */ }
  return null;
}

function loadUserTokenFromStorage(): string | null {
  if (typeof window === 'undefined') return null;
  try {
    return localStorage.getItem(USER_TOKEN_KEY);
  } catch { /* ignore */ }
  return null;
}

function saveUserToStorage(user: { id: string; name: string; email: string; phone?: string; avatar?: string; roles: string[] } | null, token?: string | null) {
  if (typeof window === 'undefined') return;
  try {
    if (user) {
      localStorage.setItem(USER_KEY, JSON.stringify(user));
      if (token) {
        localStorage.setItem(USER_TOKEN_KEY, token);
      }
    } else {
      localStorage.removeItem(USER_KEY);
      localStorage.removeItem(USER_TOKEN_KEY);
    }
  } catch { /* ignore */ }
}

function loadLanguageFromStorage(): Language | null {
  if (typeof window === 'undefined') return null;
  try {
    const lang = localStorage.getItem(LANGUAGE_KEY);
    if (lang === 'en' || lang === 'bn') return lang;
  } catch { /* ignore */ }
  return null;
}

function saveLanguageToStorage(lang: Language) {
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(LANGUAGE_KEY, lang);
  } catch { /* ignore */ }
}

export type AppSection = 
  | 'home' 
  | 'explore' 
  | 'messages' 
  | 'favourites' 
  | 'profile'
  | 'house-rental'
  | 'shop-rental'
  | 'marketplace'
  | 'medicine'
  | 'education'
  | 'community'
  | 'orders'
  | 'settings'
  | 'auth'
  | 'admin'
  | 'owner-dashboard'
  | 'checkout';

export type Language = 'en' | 'bn';

interface CartItem {
  productId: string;
  title: string;
  price: number;
  quantity: number;
  image: string;
  unit?: string;
}

export type NotificationType = 'house' | 'product' | 'mcq' | 'order' | 'admin' | 'system';

export interface Notification {
  id: string;
  title: string;
  message: string;
  time: string;
  isRead: boolean;
  type: NotificationType;
}

interface AdminPermissions {
  canManageUsers: boolean;
  canManageHouses: boolean;
  canManageShops: boolean;
  canManageProducts: boolean;
  canManageOrders: boolean;
  canManageMCQ: boolean;
  canManageCommunity: boolean;
  canSendNotification: boolean;
  canViewAnalytics: boolean;
  canManageTeam: boolean;
}

interface AdminUser {
  id: string;
  name: string;
  email: string;
  role: string;
  avatar?: string;
  phone?: string;
  permissions?: AdminPermissions;
}

interface AdminTab {
  id: string;
  label: string;
}

export interface TeamMember {
  id: string;
  name: string;
  email: string;
  phone?: string;
  role: string;
  permissions: AdminPermissions;
  status: 'active' | 'inactive';
  avatar?: string;
  createdAt: string;
}

// Role presets for auto-populating permissions
export const ROLE_PRESETS: Record<string, { label: string; labelBn: string; permissions: AdminPermissions }> = {
  super_admin: {
    label: 'Super Admin',
    labelBn: 'সুপার অ্যাডমিন',
    permissions: {
      canManageUsers: true,
      canManageHouses: true,
      canManageShops: true,
      canManageProducts: true,
      canManageOrders: true,
      canManageMCQ: true,
      canManageCommunity: true,
      canSendNotification: true,
      canViewAnalytics: true,
      canManageTeam: true,
    },
  },
  admin: {
    label: 'Admin',
    labelBn: 'অ্যাডমিন',
    permissions: {
      canManageUsers: true,
      canManageHouses: true,
      canManageShops: true,
      canManageProducts: true,
      canManageOrders: true,
      canManageMCQ: true,
      canManageCommunity: true,
      canSendNotification: true,
      canViewAnalytics: true,
      canManageTeam: false,
    },
  },
  moderator: {
    label: 'Moderator',
    labelBn: 'মডারেটর',
    permissions: {
      canManageUsers: false,
      canManageHouses: true,
      canManageShops: true,
      canManageProducts: false,
      canManageOrders: false,
      canManageMCQ: false,
      canManageCommunity: true,
      canSendNotification: false,
      canViewAnalytics: true,
      canManageTeam: false,
    },
  },
  editor: {
    label: 'Editor',
    labelBn: 'সম্পাদক',
    permissions: {
      canManageUsers: false,
      canManageHouses: false,
      canManageShops: false,
      canManageProducts: true,
      canManageOrders: false,
      canManageMCQ: true,
      canManageCommunity: false,
      canSendNotification: true,
      canViewAnalytics: false,
      canManageTeam: false,
    },
  },
  viewer: {
    label: 'Viewer',
    labelBn: 'দর্শক',
    permissions: {
      canManageUsers: false,
      canManageHouses: false,
      canManageShops: false,
      canManageProducts: false,
      canManageOrders: false,
      canManageMCQ: false,
      canManageCommunity: false,
      canSendNotification: false,
      canViewAnalytics: true,
      canManageTeam: false,
    },
  },
};

const initialTeamMembers: TeamMember[] = [
  {
    id: 'tm-1',
    name: 'Rahim Uddin',
    email: 'rahim@needyfy.com',
    phone: '+880 1711-000001',
    role: 'super_admin',
    permissions: ROLE_PRESETS.super_admin.permissions,
    status: 'active',
    createdAt: '2024-01-15T10:00:00Z',
  },
  {
    id: 'tm-2',
    name: 'Fatima Begum',
    email: 'fatima@needyfy.com',
    phone: '+880 1711-000002',
    role: 'admin',
    permissions: ROLE_PRESETS.admin.permissions,
    status: 'active',
    createdAt: '2024-02-20T14:30:00Z',
  },
  {
    id: 'tm-3',
    name: 'Karim Hossain',
    email: 'karim@needyfy.com',
    phone: '+880 1711-000003',
    role: 'moderator',
    permissions: ROLE_PRESETS.moderator.permissions,
    status: 'active',
    createdAt: '2024-03-10T09:15:00Z',
  },
  {
    id: 'tm-4',
    name: 'Nusrat Jahan',
    email: 'nusrat@needyfy.com',
    phone: '+880 1711-000004',
    role: 'editor',
    permissions: ROLE_PRESETS.editor.permissions,
    status: 'active',
    createdAt: '2024-04-05T11:45:00Z',
  },
  {
    id: 'tm-5',
    name: 'Arif Rahman',
    email: 'arif@needyfy.com',
    phone: '+880 1711-000005',
    role: 'viewer',
    permissions: ROLE_PRESETS.viewer.permissions,
    status: 'inactive',
    createdAt: '2024-05-01T16:20:00Z',
  },
];

interface AppState {
  // Navigation
  currentSection: AppSection;
  setCurrentSection: (section: AppSection) => void;
  
  // Auth
  isLoggedIn: boolean;
  user: {
    id: string;
    name: string;
    email: string;
    phone?: string;
    avatar?: string;
    roles: string[];
  } | null;
  userToken: string | null;
  setUser: (user: AppState['user'], token?: string | null) => void;
  logout: () => void;

  // Admin Auth
  isAdminLoggedIn: boolean;
  adminUser: AdminUser | null;
  adminToken: string | null;
  setAdminUser: (admin: AdminUser | null, token?: string | null) => void;
  adminPermissions: AdminPermissions | null;
  adminLogout: () => void;
  adminTab: string;
  setAdminTab: (tab: string) => void;

  // Language
  language: Language;
  setLanguage: (lang: Language) => void;

  // Cart
  cart: CartItem[];
  addToCart: (item: CartItem) => void;
  removeFromCart: (productId: string) => void;
  updateQuantity: (productId: string, quantity: number) => void;
  clearCart: () => void;

  // Sidebar
  sidebarOpen: boolean;
  setSidebarOpen: (open: boolean) => void;

  // Search
  searchQuery: string;
  setSearchQuery: (query: string) => void;

  // Notifications
  notifications: Notification[];
  setNotifications: (notifications: Notification[]) => void;
  markAsRead: (id: string) => void;
  markAllAsRead: () => void;
  unreadNotifications: number;
  setUnreadNotifications: (count: number) => void;
  unreadMessages: number;
  setUnreadMessages: (count: number) => void;

  // Chat navigation
  openChatWith: { id: string; name: string; phone?: string; listingTitle?: string } | null;
  setOpenChatWith: (chat: { id: string; name: string; phone?: string; listingTitle?: string } | null) => void;

  // Team Members
  teamMembers: TeamMember[];
  addTeamMember: (member: TeamMember) => void;
  updateTeamMember: (id: string, updates: Partial<TeamMember>) => void;
  deleteTeamMember: (id: string) => void;
}

// ============ STORE CREATION ============
// IMPORTANT: Always initialize with safe defaults (no localStorage at module scope).
// Hydration from localStorage happens in the `hydrateStoreFromStorage()` function
// which is called from a useEffect in page.tsx AFTER client mount.
// This prevents SSR/client hydration mismatches and ensures the app renders correctly.
export const useAppStore = create<AppState>((set) => ({
  // Navigation - always start with 'home', hydrate later
  currentSection: 'home' as AppSection,
  setCurrentSection: (section) => {
    saveSectionToStorage(section);
    set({ currentSection: section });
  },

  // Auth - always start logged out, hydrate later
  isLoggedIn: false,
  user: null,
  userToken: null,
  setUser: (user, token) => {
    saveUserToStorage(user, token);
    set({ user, isLoggedIn: !!user, userToken: token || null });
  },
  logout: () => {
    saveUserToStorage(null, null);
    saveSectionToStorage('home');
    set({ user: null, isLoggedIn: false, currentSection: 'home', userToken: null });
  },

  // Admin Auth - always start logged out, hydrate later
  isAdminLoggedIn: false,
  adminUser: null,
  adminToken: null,
  adminPermissions: null,
  setAdminUser: (admin, token) => {
    saveAdminToStorage(admin as unknown as Record<string, unknown>, token || null);
    set({ adminUser: admin, isAdminLoggedIn: !!admin, adminPermissions: admin?.permissions || null, adminToken: token || null });
  },
  adminLogout: () => {
    saveAdminToStorage(null, null);
    saveSectionToStorage('home');
    set({ adminUser: null, isAdminLoggedIn: false, adminTab: 'dashboard', adminPermissions: null, currentSection: 'home', adminToken: null });
  },
  adminTab: 'dashboard',
  setAdminTab: (tab) => set({ adminTab: tab }),

  // Language - always start with 'en', hydrate later
  language: 'en' as Language,
  setLanguage: (language) => {
    saveLanguageToStorage(language);
    set({ language });
  },

  // Cart
  cart: [],
  addToCart: (item) =>
    set((state) => {
      const existing = state.cart.find((c) => c.productId === item.productId);
      if (existing) {
        return {
          cart: state.cart.map((c) =>
            c.productId === item.productId
              ? { ...c, quantity: c.quantity + item.quantity }
              : c
          ),
        };
      }
      return { cart: [...state.cart, item] };
    }),
  removeFromCart: (productId) =>
    set((state) => ({
      cart: state.cart.filter((c) => c.productId !== productId),
    })),
  updateQuantity: (productId, quantity) =>
    set((state) => ({
      cart: state.cart.map((c) =>
        c.productId === productId ? { ...c, quantity } : c
      ),
    })),
  clearCart: () => set({ cart: [] }),

  // Sidebar
  sidebarOpen: false,
  setSidebarOpen: (open) => set({ sidebarOpen: open }),

  // Search
  searchQuery: '',
  setSearchQuery: (query) => set({ searchQuery: query }),

  // Notifications
  notifications: [
    {
      id: '1',
      title: 'New House Available',
      message: 'A 3BHK flat is now available near Dhanmondi Lake. Check it out before it\'s gone!',
      time: '2 min ago',
      isRead: false,
      type: 'house',
    },
    {
      id: '2',
      title: 'Flash Sale - 30% Off',
      message: 'Limited time offer on electronics. Get up to 30% off on selected items!',
      time: '15 min ago',
      isRead: false,
      type: 'product',
    },
    {
      id: '3',
      title: 'HSC MCQ Results',
      message: 'Your HSC practice test results are ready. You scored 85%!',
      time: '1 hour ago',
      isRead: false,
      type: 'mcq',
    },
    {
      id: '4',
      title: 'Order Delivered',
      message: 'Your order #ORD-2847 has been delivered successfully. Enjoy!',
      time: '3 hours ago',
      isRead: true,
      type: 'order',
    },
    {
      id: '5',
      title: 'System Update',
      message: 'Needyfy v2.1 is now live with improved performance and new features.',
      time: '5 hours ago',
      isRead: true,
      type: 'system',
    },
    {
      id: '6',
      title: 'New Shop Listing',
      message: 'A new commercial space is available in Gulshan-2. 2000 sqft, ideal for retail.',
      time: '8 hours ago',
      isRead: true,
      type: 'house',
    },
    {
      id: '7',
      title: 'Admin Notice',
      message: 'Scheduled maintenance on Saturday 2AM-4AM. Services may be temporarily unavailable.',
      time: '1 day ago',
      isRead: true,
      type: 'admin',
    },
    {
      id: '8',
      title: 'Grocery Deal',
      message: 'Fresh vegetables at wholesale prices this week. Order now from Marketplace!',
      time: '1 day ago',
      isRead: true,
      type: 'product',
    },
    {
      id: '9',
      title: 'Quiz Challenge',
      message: 'New General Knowledge quiz available. Compete with others and climb the leaderboard!',
      time: '2 days ago',
      isRead: true,
      type: 'mcq',
    },
    {
      id: '10',
      title: 'Welcome to Needyfy',
      message: 'Thanks for joining! Explore houses, shops, products and more all in one place.',
      time: '3 days ago',
      isRead: true,
      type: 'system',
    },
    {
      id: '11',
      title: 'New Listing in Mirpur',
      message: 'A 2BHK apartment is now available near Mirpur-10. Affordable rent with parking.',
      time: '3 days ago',
      isRead: true,
      type: 'house',
    },
    {
      id: '12',
      title: 'Order Shipped',
      message: 'Your order #ORD-3192 has been shipped and will arrive within 2-3 business days.',
      time: '4 days ago',
      isRead: true,
      type: 'order',
    },
    {
      id: '13',
      title: 'Weekend Special Offer',
      message: 'Get 20% off on all grocery items this weekend. Limited stock available!',
      time: '4 days ago',
      isRead: true,
      type: 'product',
    },
    {
      id: '14',
      title: 'English Quiz Result',
      message: 'You completed the English Grammar quiz. Score: 92%! Well done!',
      time: '5 days ago',
      isRead: true,
      type: 'mcq',
    },
    {
      id: '15',
      title: 'Community Post Liked',
      message: 'Your post "Best cafes in Dhaka" received 25 new likes today.',
      time: '5 days ago',
      isRead: true,
      type: 'system',
    },
    {
      id: '16',
      title: 'Shop Rent Reminder',
      message: 'Your shop rent payment of ৳25,000 is due in 3 days. Please pay on time.',
      time: '6 days ago',
      isRead: true,
      type: 'admin',
    },
    {
      id: '17',
      title: 'New Feature: Favourites',
      message: 'You can now save your favourite listings! Tap the heart icon to save.',
      time: '1 week ago',
      isRead: true,
      type: 'system',
    },
    {
      id: '18',
      title: 'Price Drop Alert',
      message: 'A product in your wishlist has dropped in price. Check it out now!',
      time: '1 week ago',
      isRead: true,
      type: 'product',
    },
    {
      id: '19',
      title: 'House Verified',
      message: 'Your listed property at Uttara has been verified and is now live.',
      time: '1 week ago',
      isRead: true,
      type: 'house',
    },
    {
      id: '20',
      title: 'Monthly Report Ready',
      message: 'Your monthly activity report for February is ready to view.',
      time: '2 weeks ago',
      isRead: true,
      type: 'admin',
    },
  ],
  setNotifications: (notifications) => set({ notifications, unreadNotifications: notifications.filter(n => !n.isRead).length }),
  markAsRead: (id) =>
    set((state) => {
      const notifications = state.notifications.map((n) =>
        n.id === id ? { ...n, isRead: true } : n
      );
      return {
        notifications,
        unreadNotifications: notifications.filter((n) => !n.isRead).length,
      };
    }),
  markAllAsRead: () =>
    set((state) => ({
      notifications: state.notifications.map((n) => ({ ...n, isRead: true })),
      unreadNotifications: 0,
    })),
  unreadNotifications: 3,
  setUnreadNotifications: (count) => set({ unreadNotifications: count }),
  unreadMessages: 2,
  setUnreadMessages: (count) => set({ unreadMessages: count }),

  // Chat navigation
  openChatWith: null,
  setOpenChatWith: (chat) => set({ openChatWith: chat }),

  // Team Members
  teamMembers: initialTeamMembers,
  addTeamMember: (member) =>
    set((state) => ({ teamMembers: [...state.teamMembers, member] })),
  updateTeamMember: (id, updates) =>
    set((state) => ({
      teamMembers: state.teamMembers.map((m) =>
        m.id === id ? { ...m, ...updates } : m
      ),
    })),
  deleteTeamMember: (id) =>
    set((state) => ({
      teamMembers: state.teamMembers.filter((m) => m.id !== id),
    })),
}));

// ============ HYDRATION ============
// Hydrate ALL persisted state from localStorage into the store.
// This MUST be called from a useEffect on the client AFTER mount.
// It handles: admin session, user session, current section, language.
export function hydrateStoreFromStorage() {
  if (typeof window === 'undefined') return;

  // Hydrate admin session
  const { adminUser, adminToken } = loadAdminFromStorage();
  const state = useAppStore.getState();

  if (adminUser && adminToken) {
    // Check if token is expired (24h expiry)
    try {
      const payload = JSON.parse(atob(adminToken));
      if (payload.ts && Date.now() - payload.ts > 24 * 60 * 60 * 1000) {
        // Token expired, clear storage
        saveAdminToStorage(null, null);
        useAppStore.setState({
          adminUser: null,
          adminToken: null,
          isAdminLoggedIn: false,
          adminPermissions: null,
        });
      } else {
        // Token valid - restore admin session
        const admin = adminUser as AdminUser;
        useAppStore.setState({
          adminUser: admin,
          adminToken,
          isAdminLoggedIn: true,
          adminPermissions: admin.permissions || null,
        });
      }
    } catch {
      // Invalid token format - clear
      saveAdminToStorage(null, null);
      useAppStore.setState({
        adminUser: null,
        adminToken: null,
        isAdminLoggedIn: false,
        adminPermissions: null,
      });
    }
  }

  // Hydrate user session
  const savedUser = loadUserFromStorage();
  const savedUserToken = loadUserTokenFromStorage();
  if (savedUser) {
    // Check if user token is expired (24h expiry)
    let validToken = savedUserToken;
    if (validToken) {
      try {
        const payload = JSON.parse(atob(validToken));
        if (payload.ts && Date.now() - payload.ts > 24 * 60 * 60 * 1000) {
          validToken = null;
          localStorage.removeItem(USER_TOKEN_KEY);
        }
      } catch {
        validToken = null;
        localStorage.removeItem(USER_TOKEN_KEY);
      }
    }
    useAppStore.setState({
      user: savedUser,
      isLoggedIn: true,
      userToken: validToken,
    });
  }

  // Hydrate current section (must come after admin hydration)
  const savedSection = loadSectionFromStorage();
  const currentState = useAppStore.getState();
  if (savedSection) {
    // If saved section is 'admin' but admin is not logged in, reset to home
    if (savedSection === 'admin' && !currentState.isAdminLoggedIn) {
      saveSectionToStorage('home');
      useAppStore.setState({ currentSection: 'home' });
    } else {
      useAppStore.setState({ currentSection: savedSection });
    }
  }

  // Hydrate language
  const savedLang = loadLanguageFromStorage();
  if (savedLang) {
    useAppStore.setState({ language: savedLang });
  }
}
