import api from './api';

export interface Poll {
  id: number;
  title: string;
  description: string;
  type: 'single' | 'multiple' | 'rating';
  status: 'draft' | 'active' | 'closed' | 'archived';
  start_date?: string;
  end_date?: string;
  allow_multiple: boolean;
  max_choices: number;
  show_results: 'always' | 'after_vote' | 'after_end' | 'never';
  require_auth: boolean;
  allow_guest_vote: boolean;
  featured: boolean;
  category_id?: number;
  category?: {
    id: number;
    name: string;
    slug: string;
  };
  related_match_id?: number;
  related_article_id?: number;
  related_article?: {
    id: number;
    title: string;
    slug: string;
  };
  related_event_id?: number;
  related_event?: {
    id: number;
    title: string;
    start_time: string;
  };
  related_video_url?: string;
  image_url?: string;
  total_votes: number;
  options: PollOption[];
  created_by: number;
  creator?: {
    id: number;
    email: string;
    username?: string;
  };
  created_at: string;
  updated_at: string;
}

export interface PollOption {
  id: number;
  poll_id: number;
  text: string;
  description?: string;
  image_url?: string;
  display_order: number;
  vote_count: number;
  player_id?: number;
  player?: {
    id: number;
    first_name: string;
    last_name: string;
    jersey_number?: number;
    image_url?: string;
  };
  created_at: string;
  updated_at: string;
}

export interface PollVoteRequest {
  option_ids: number[];
  session_token?: string;
}

export interface PollResult {
  option_id: number;
  text: string;
  vote_count: number;
  percentage: number;
  image_url?: string;
  player_id?: number;
}

export interface PollResultsResponse {
  poll_id: number;
  title: string;
  total_votes: number;
  results: PollResult[];
}

export interface PollResponse {
  poll: Poll;
  has_voted: boolean;
  is_active: boolean;
  can_show_results: boolean;
}

export interface CreatePollRequest {
  title: string;
  description?: string;
  type?: 'single' | 'multiple' | 'rating';
  status?: 'draft' | 'active' | 'closed' | 'archived';
  start_date?: string;
  end_date?: string;
  allow_multiple?: boolean;
  max_choices?: number;
  show_results?: 'always' | 'after_vote' | 'after_end' | 'never';
  require_auth?: boolean;
  allow_guest_vote?: boolean;
  featured?: boolean;
  category_id?: number;
  related_match_id?: number;
  related_article_id?: number;
  related_event_id?: number;
  related_video_url?: string;
  image_url?: string;
  options: {
    text: string;
    description?: string;
    image_url?: string;
    display_order?: number;
    player_id?: number;
  }[];
}

export interface UpdatePollRequest {
  title?: string;
  description?: string;
  type?: 'single' | 'multiple' | 'rating';
  status?: 'draft' | 'active' | 'closed' | 'archived';
  start_date?: string;
  end_date?: string;
  allow_multiple?: boolean;
  max_choices?: number;
  show_results?: 'always' | 'after_vote' | 'after_end' | 'never';
  require_auth?: boolean;
  allow_guest_vote?: boolean;
  featured?: boolean;
  category_id?: number;
  related_match_id?: number;
  related_article_id?: number;
  related_event_id?: number;
  related_video_url?: string;
  image_url?: string;
}

export interface PollStats {
  poll: Poll;
  votes_by_day: {
    date: string;
    count: number;
  }[];
  authenticated_votes: number;
  guest_votes: number;
}

// Public API

export const getPolls = async (params?: {
  featured?: boolean;
  status?: string;
  article_id?: number;
  event_id?: number;
  video_url?: string;
}): Promise<Poll[]> => {
  const response = await api.get('/polls', { params });
  return response.data;
};

export const getPoll = async (id: number): Promise<PollResponse> => {
  const response = await api.get(`/polls/${id}`);
  return response.data;
};

export const votePoll = async (
  id: number,
  data: PollVoteRequest
): Promise<{ message: string; poll: Poll }> => {
  const response = await api.post(`/polls/${id}/vote`, data);
  return response.data;
};

export const getPollResults = async (id: number): Promise<PollResultsResponse> => {
  const response = await api.get(`/polls/${id}/results`);
  return response.data;
};

// Admin API

export const getAdminPolls = async (params?: {
  status?: string;
}): Promise<Poll[]> => {
  const response = await api.get('/admin/polls', { params });
  return response.data;
};

export const getAdminPoll = async (id: number): Promise<PollResponse> => {
  const response = await api.get(`/admin/polls/${id}`);
  return response.data;
};

export const createPoll = async (data: CreatePollRequest): Promise<Poll> => {
  const response = await api.post('/admin/polls', data);
  return response.data;
};

export const updatePoll = async (
  id: number,
  data: UpdatePollRequest
): Promise<Poll> => {
  const response = await api.put(`/admin/polls/${id}`, data);
  return response.data;
};

export const deletePoll = async (id: number): Promise<void> => {
  await api.delete(`/admin/polls/${id}`);
};

export const getPollStats = async (id: number): Promise<PollStats> => {
  const response = await api.get(`/admin/polls/${id}/stats`);
  return response.data;
};

// Helper to generate a session token for guest voting
export const generateSessionToken = (): string => {
  const stored = localStorage.getItem('poll_session_token');
  if (stored) {
    return stored;
  }
  
  const token = `guest_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
  localStorage.setItem('poll_session_token', token);
  return token;
};
