import { Achievement, Project } from '../data';

/**
 * Google Sheets Service
 */

const SPREADSHEET_ID = import.meta.env.VITE_SPREADSHEET_ID;
const API_KEY = import.meta.env.VITE_GOOGLE_API_KEY;

export async function fetchSheetData(range: string) {
  const url = `https://sheets.googleapis.com/v4/spreadsheets/${SPREADSHEET_ID}/values/${range}?key=${API_KEY}`;
  
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data.values;
  } catch (error) {
    console.error('Error fetching sheet data:', error);
    return null;
  }
}

export async function getMappedData() {
  const values = await fetchSheetData('Form Responses 1!A2:J200');
  if (!values) return { achievements: [], projects: [] };

  const achievements: Achievement[] = [];
  const projects: Project[] = [];

  values.forEach((row: any[], index: number) => {
    // New Mapping:
    // 0: Nama Mahasiswa (A)
    // 1: NIM Mahasiswa (B)
    // 2: Angkatan (C)
    // 3: Jenis Data (D)
    // 4: Nama Prestasi (E)
    // 5: Tahun (F)
    // 6: Tingkat (G)
    // 7: Bidang (H)
    // 8: Deskripsi (I)
    // 9: Gambar (J)
    
    const type = row[3]; // Jenis Data
    const id = `sheet-${index}`;
    const imageUrl = row[9] || `https://picsum.photos/seed/${id}/800/600`;
    
    if (type === 'Prestasi') {
      achievements.push({
        id,
        title: row[4] || 'Untitled Achievement',
        category: row[7] || 'Umum',
        competition: row[4] || 'Kompetisi',
        rank: 'Peserta', 
        year: parseInt(row[5]) || new Date().getFullYear(),
        level: (row[6] as any) || 'Nasional',
        description: row[8] || '',
        team: row[0] || 'Mahasiswa',
        nim: row[1],
        generation: `Angkatan ${row[2] || '-'}`,
        image: imageUrl,
        avatar: (row[0] || 'M').substring(0, 2).toUpperCase(),
      });
    } else if (type === 'Proyek') {
      projects.push({
        id: `p-${id}`,
        title: row[4] || 'Untitled Project',
        studentName: row[0] || 'Mahasiswa',
        nim: row[1],
        year: parseInt(row[5]) || new Date().getFullYear(),
        category: row[7] || 'Software',
        description: row[8] || '',
        image: imageUrl,
        link: undefined, // No link column mentioned in new structure
      });
    }
  });

  return { achievements, projects };
}
