import { create } from 'zustand';

interface TourState {
  currentTour: any;
  legs: any[];
  publicTours: any[];
  userRole: string | null;
  activeLegId: string | null;
  mapCenter: [number, number];
  setTour: (tour: any) => void;
  updateLegs: (legs: any[]) => void;
  createTour: (tourData: any) => Promise<any>;
  updateTourDetails: (tourId: string, data: any) => Promise<void>;
  updateTour: (id: string, data: any) => Promise<void>;
  deleteTour: (id: string) => Promise<void>;
  addLeg: (tourId: string, data: any) => Promise<void>;
  initializeLegs: (tourId: string, count: number) => Promise<void>;
  updateLeg: (legId: string, data: any) => Promise<void>;
  deleteLeg: (legId: string) => Promise<void>;
  addLocation: (tourId: string, locationData: any) => Promise<void>;
  updateLocation: (locationId: string, data: any) => Promise<void>;
  deleteLocation: (locationId: string) => Promise<void>;
  updateTourStartPoint: (tourId: string, data: any) => Promise<void>;
  updateTourEndPoint: (tourId: string, data: any) => Promise<void>;
  optimizeRouting: (legId: string) => Promise<void>;
  addMember: (tourId: string, member: { userId?: string; displayName?: string; role?: string }) => Promise<any>;
  removeMember: (tourId: string, userId: string) => Promise<void>;
  updateMemberFamilyCount: (tourId: string, userId: string, adultCount: number, childCount: number) => Promise<void>;
  setActiveLegId: (id: string | null) => void;
  setMapCenter: (pos: [number, number]) => void;
  fetchTour: (id: string) => Promise<void>;
  fetchPublicTourDetails: (tourId: string) => Promise<void>;
  fetchPublicTours: () => Promise<void>;
  createJoinRequest: (tourId: string, userId?: string) => Promise<any>;
  fetchJoinRequests: (tourId: string) => Promise<any[]>;
  acceptJoinRequest: (tourId: string, requestId: string) => Promise<any>;
  rejectJoinRequest: (tourId: string, requestId: string) => Promise<any>;
}

export const useTourStore = create<TourState>((set, get) => ({
  currentTour: null,
  legs: [],
  publicTours: [],
  userRole: null,
  activeLegId: null,
  mapCenter: [10.7769, 106.7009],
  setTour: (tour) => set({ currentTour: tour }),
  updateLegs: (legs) => set({ legs }),
  setActiveLegId: (id) => set({ activeLegId: id }),
  setMapCenter: (pos) => set({ mapCenter: pos }),
  fetchTour: async (id: string) => {
    const token = localStorage.getItem('token');
    try {
      let response = await fetch(`/api/v1/tours/${id}`, {
        headers: { 'Authorization': `Bearer ${token}` }
      });
      // Thử lại một lần nếu gặp lỗi 403 hoặc 401 (có thể do cache vai trò cũ chưa được cập nhật)
      if (response.status === 403 || response.status === 401) {
        await new Promise((resolve) => setTimeout(resolve, 1000));
        const retryResponse = await fetch(`/api/v1/tours/${id}`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Cache-Control': 'no-cache'
          }
        });
        if (retryResponse.ok) {
          response = retryResponse;
        }
      }
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const data = await response.json();
      // ...existing role detection...
      let role = 'VIEWER_ONLY';
      if (token) {
        try {
          const payload = JSON.parse(atob(token.split('.')[1]));
          const currentUserId = payload.sub;
          const participant = data.participants?.find((p: any) => p.userId === currentUserId);
          if (participant) role = participant.role;
        } catch (e) {
          console.error("Lỗi khi xác định vai trò người dùng:", e);
        }
      }
      const legs = data.legs || [];
      set({ currentTour: data, legs, userRole: role, activeLegId: legs.length > 0 ? legs[0].id : null });
    } catch (err: any) {
      console.error('Không thể tải tour:', err);
      // Không set null để tránh flash trắng; giữ nguyên state cũ nếu có
    }
  },
  fetchPublicTours: async () => {
    const token = localStorage.getItem('token');
    if (!token) return;

    try {
      const response = await fetch(`/api/v1/tours/explore`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      // If response is 401 or 403, the user is likely anonymous and rejected by backend
      if (response.status === 401 || response.status === 403) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Tài khoản khách không có quyền truy cập');
      }

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }

      const data = await response.json();
      set({ publicTours: data });
    } catch (error: any) {
      console.error('[fetchPublicTours] Error:', error.message);
      // Re-throw the error so MemberDashboard can catch it and redirect
      throw error;
    }
  },
  fetchPublicTourDetails: async (tourId: string) => {
    try {
      // Reset state cũ trước khi tải dữ liệu mới
      set({ currentTour: null, legs: [], userRole: 'VIEWER_ONLY' });

      const response = await fetch(`/api/v1/tours/${tourId}/public`);
      if (!response.ok) throw new Error('Không thể tải tour công khai');
      const data = await response.json();
      const legs = data.legs || [];
      set({ 
        currentTour: data, 
        legs, 
        userRole: 'VIEWER_ONLY',
        activeLegId: legs.length > 0 ? legs[0].id : null 
      });
    } catch (err: any) {
      console.error('Lỗi khi tải tour công khai:', err);
    }
  },
  createTour: async (tourData: any) => {
    const response = await fetch(`/api/v1/tours`, {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(tourData),
    });
    if (!response.ok) {
      const data = await response.json().catch(() => ({}));
      throw new Error(data.message || data.error || 'Lỗi khi tạo Tour');
    }
    const tour = await response.json();
    await get().fetchPublicTours();
    return tour;
  },
  updateTourDetails: async (tourId: string, data: any) => {
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/v1/tours/${tourId}`, {
      method: 'PATCH',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(data),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || errorData.error || 'Lỗi khi cập nhật thông tin tour');
    }
  },
  updateTour: async (id: string, data: any) => {
    const response = await fetch(`/api/v1/tours/${id}`, {
      method: 'PATCH',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error('Lỗi khi cập nhật Tour');
    
    // Làm mới danh sách khám phá
    get().fetchPublicTours();
  },
  deleteTour: async (id: string) => {
    const response = await fetch(`/api/v1/tours/${id}`, {
      method: 'DELETE',
      headers: { 
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
    });
    if (!response.ok) {
      const data = await response.json();
      throw new Error(data.message || 'Lỗi khi xóa Tour');
    }
    
    // Reset tour hiện tại nếu đang xem đúng tour vừa xóa
    if (get().currentTour?.id === id) set({ currentTour: null });
    get().fetchPublicTours();
  },
  addLeg: async (tourId: string, data: any) => {
    const response = await fetch(`/api/v1/tours/${tourId}/legs`, {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error('Lỗi khi thêm chặng');
    get().fetchTour(tourId);
  },
  initializeLegs: async (tourId: string, count: number) => {
    const response = await fetch(`/api/v1/tours/${tourId}/legs/batch`, {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({ count }),
    });
    if (!response.ok) throw new Error('Lỗi khi khởi tạo chặng');
    await get().fetchTour(tourId);
  },
  updateLeg: async (legId: string, data: any) => {
    const response = await fetch(`/api/v1/legs/${legId}`, {
      method: 'PATCH',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error('Lỗi khi cập nhật chặng');
    
    const { currentTour } = get();
    if (currentTour) get().fetchTour(currentTour.id);
  },
  deleteLeg: async (legId: string) => {
    const response = await fetch(`/api/v1/legs/${legId}`, {
      method: 'DELETE',
      headers: { 
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
    });
    const result = await response.json();
    if (!response.ok) {
      throw new Error(result.message || 'Lỗi khi xóa chặng');
    }
    
    const { currentTour } = get();
    if (currentTour) get().fetchTour(currentTour.id);
  },
  addLocation: async (tourId: string, locationData: any) => {
    const response = await fetch(`/api/v1/tours/${tourId}/locations`, {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(locationData),
    });
    if (!response.ok) throw new Error('Lỗi khi thêm địa điểm');
    // Làm mới dữ liệu tour hiện tại
    get().fetchTour(tourId);
  },
  updateLocation: async (locationId: string, data: any) => {
    const response = await fetch(`/api/v1/locations/${locationId}`, {
      method: 'PATCH',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error('Lỗi khi cập nhật địa điểm');
    
    const { currentTour } = get();
    if (currentTour) get().fetchTour(currentTour.id);
  },
  deleteLocation: async (locationId: string) => {
    const response = await fetch(`/api/v1/locations/${locationId}`, {
      method: 'DELETE',
      headers: { 
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
    });
    if (!response.ok) throw new Error('Lỗi khi xóa địa điểm');
    
    const { currentTour } = get();
    if (currentTour) get().fetchTour(currentTour.id);
  },
  updateTourStartPoint: async (tourId: string, data: any) => {
    const response = await fetch(`/api/v1/tours/${tourId}/start-point`, {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(data),
    });
    
    console.log(`[STORE] updateTourStartPoint API Status: ${response.status}`);
    if (!response.ok) throw new Error('Lỗi khi thiết lập điểm bắt đầu');
    await get().fetchTour(tourId);
  },
  updateTourEndPoint: async (tourId: string, data: any) => {
    const response = await fetch(`/api/v1/tours/${tourId}/end-point`, {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error('Lỗi khi thiết lập điểm kết thúc');
    await get().fetchTour(tourId);
  },
  optimizeRouting: async (legId: string) => {
    const response = await fetch(`/api/v1/routing/optimize/${legId}`, {
      method: 'POST'
    });
    const { locations, totalDistance } = await response.json();
    
    const { currentTour } = get();
    if (currentTour) {
      const updatedLegs = currentTour.legs.map((l: any) => 
        l.id === legId ? { ...l, locations: locations, totalDistance: totalDistance } : l
      );
      set({ currentTour: { ...currentTour, legs: updatedLegs }, legs: updatedLegs });
    }
  },
  removeMember: async (tourId: string, userId: string) => {
    const response = await fetch(`/api/v1/tours/${tourId}/members/${userId}`, {
      method: 'DELETE',
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`,
      },
    });
    if (!response.ok) throw new Error('Lỗi khi xóa thành viên');
    const { currentTour } = get();
    if (currentTour) get().fetchTour(currentTour.id);
  },
  addMember: async (tourId: string, member: { userId?: string; displayName?: string; role?: string }) => {
    const response = await fetch(`/api/v1/tours/${tourId}/members`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(member),
    });
    if (!response.ok) {
      const data = await response.json().catch(() => ({}));
      throw new Error(data.message || data.error || 'Lỗi khi thêm thành viên');
    }
    const { currentTour } = get();
    if (currentTour) get().fetchTour(currentTour.id);
  },
  updateMemberFamilyCount: async (tourId: string, userId: string, adultCount: number, childCount: number) => {
    const response = await fetch(`/api/v1/tours/${tourId}/members/${userId}`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({ adultCount, childCount }),
    });
    if (!response.ok) {
      const data = await response.json().catch(() => ({}));
      throw new Error(data.message || data.error || 'Lỗi khi cập nhật thành viên');
    }
    const { currentTour } = get();
    if (currentTour) get().fetchTour(currentTour.id);
  },
  createJoinRequest: async (tourId: string, userId?: string) => {
    const response = await fetch(`/api/v1/tours/${tourId}/join-requests`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({ userId }),
    });
    if (!response.ok) {
      const data = await response.json().catch(() => ({}));
      throw new Error(data.message || data.error || 'Lỗi khi tạo yêu cầu tham gia');
    }
    return response.json();
  },
  fetchJoinRequests: async (tourId: string) => {
    const response = await fetch(`/api/v1/tours/${tourId}/join-requests`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });
    if (!response.ok) {
      const data = await response.json().catch(() => ({}));
      throw new Error(data.message || data.error || 'Lỗi khi tải yêu cầu tham gia');
    }
    return response.json();
  },
  acceptJoinRequest: async (tourId: string, requestId: string) => {
    const response = await fetch(`/api/v1/tours/${tourId}/join-requests/${requestId}/accept`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });
    if (!response.ok) {
      const data = await response.json().catch(() => ({}));
      throw new Error(data.message || data.error || 'Lỗi khi chấp nhận yêu cầu');
    }
    const { currentTour } = get();
    if (currentTour) get().fetchTour(currentTour.id);
  },
  rejectJoinRequest: async (tourId: string, requestId: string) => {
    const response = await fetch(`/api/v1/tours/${tourId}/join-requests/${requestId}/reject`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });
    if (!response.ok) {
      const data = await response.json().catch(() => ({}));
      throw new Error(data.message || data.error || 'Lỗi khi từ chối yêu cầu');
    }
    const { currentTour } = get();
    if (currentTour) get().fetchTour(currentTour.id);
  },
}));