import { create } from 'zustand';
import api from './api';
import { createAxiosUploadProgressHandler } from '../lib/uploadProgress';

export interface Club {
  id: number;
  uid: string;
  name: string;
  type: 'club' | 'sport';
  description: string;
  teacher_in_charge_id: number;
  teacher_name?: string;
  schedule: string;
  max_members?: number;
  current_members?: number;
  status: 'active' | 'inactive';
}

export interface ClubMembership {
  id: number;
  uid: string;
  club_id: number;
  club_name?: string;
  club_type?: string;
  student_id: number;
  first_name?: string;
  last_name?: string;
  role: string;
  join_date: string;
  status: 'active' | 'inactive';
}

export interface ClubAnnouncement {
  id: number;
  uid: string;
  club_id: number;
  club_name?: string;
  title: string;
  content: string;
  author_name?: string;
  created_at: string;
}

export interface ClubAttendance {
  id: number;
  uid: string;
  club_id: number;
  student_id: number;
  first_name?: string;
  last_name?: string;
  date: string;
  status: 'present' | 'absent' | 'excused';
}

export interface ClubsStore {
  clubs: Club[];
  memberships: ClubMembership[];
  announcements: ClubAnnouncement[];
  attendance: ClubAttendance[];
  chats: any[];
  loading: boolean;
  uploadProgress: number;

  fetchClubs: (type?: string) => Promise<void>;
  fetchMemberships: (clubId?: number, studentId?: number) => Promise<void>;
  fetchAnnouncements: (clubId?: number) => Promise<void>;
  fetchAttendance: (clubId: number, date: string) => Promise<void>;
  fetchChats: (clubId: number) => Promise<void>;
  sendChatMessage: (clubId: number, message: string, imageUrl?: string) => Promise<void>;
  uploadChatImage: (file: File) => Promise<string>;
  
  createClub: (data: any) => Promise<void>;
  updateClub: (id: number, data: any) => Promise<void>;
  joinClub: (clubId: number, studentId?: number) => Promise<void>;
  leaveClub: (clubId: number, studentId?: number) => Promise<void>;
  postAnnouncement: (data: any) => Promise<void>;
  markAttendance: (records: any[]) => Promise<void>;
}

export const useClubsStore = create<ClubsStore>((set, get) => ({
  clubs: [],
  memberships: [],
  announcements: [],
  attendance: [],
  chats: [],
  loading: false,
  uploadProgress: 0,

  fetchClubs: async (type) => {
    set({ loading: true });
    const params = type ? { type } : {};
    const res = await api.get('/clubs', { params });
    set({ clubs: res.data, loading: false });
  },

  fetchMemberships: async (clubId, studentId) => {
    const params: any = {};
    if (clubId) params.club_id = clubId;
    if (studentId) params.student_id = studentId;
    const res = await api.get('/clubs/memberships', { params });
    set({ memberships: res.data });
  },

  fetchAnnouncements: async (clubId) => {
    const params = clubId ? { club_id: clubId } : {};
    const res = await api.get('/clubs/announcements', { params });
    set({ announcements: res.data });
  },

  fetchAttendance: async (clubId, date) => {
    const res = await api.get('/clubs/attendance', { params: { club_id: clubId, date } });
    set({ attendance: res.data });
  },

  createClub: async (data) => {
    await api.post('/clubs', data);
    get().fetchClubs();
  },

  updateClub: async (id, data) => {
    await api.put(`/clubs/${id}`, data);
    get().fetchClubs();
  },

  joinClub: async (clubId, studentId) => {
    await api.post('/clubs/memberships/join', { club_id: clubId, student_id: studentId });
    get().fetchMemberships(undefined, studentId);
    get().fetchClubs();
  },

  leaveClub: async (clubId, studentId) => {
    await api.post('/clubs/memberships/leave', { club_id: clubId, student_id: studentId });
    get().fetchMemberships(undefined, studentId);
    get().fetchClubs();
  },

  postAnnouncement: async (data) => {
    await api.post('/clubs/announcements', data);
    get().fetchAnnouncements(data.club_id);
  },

  markAttendance: async (records) => {
    await api.post('/clubs/attendance/bulk', { records });
    if (records.length > 0) {
      get().fetchAttendance(records[0].club_id, records[0].date);
    }
  },

  fetchChats: async (clubId) => {
    const res = await api.get(`/clubs/${clubId}/chats`);
    set({ chats: res.data });
  },

  sendChatMessage: async (clubId, message, imageUrl) => {
    const res = await api.post(`/clubs/${clubId}/chats`, { message, image_url: imageUrl });
    set(state => ({ chats: [...state.chats, res.data] }));
  },

  uploadChatImage: async (file) => {
    set({ uploadProgress: 0 });
    try {
      const formData = new FormData();
      formData.append('image', file);
      const res = await api.post('/clubs/chats/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: createAxiosUploadProgressHandler((percent) => {
          if (typeof percent === 'number') {
            set({ uploadProgress: percent });
          }
        })
      });
      return res.data.imageUrl;
    } finally {
      set({ uploadProgress: 0 });
    }
  }
}));
