'use server';
import { revalidatePath } from 'next/cache';
import { requireAdmin } from '@/lib/auth';
import { createAdminClient } from '@/lib/supabase/admin';
import { parseBulk } from '@/lib/parse';
import { todayIstanbul } from '@/lib/format';

export type FormState = { ok?: string; error?: string; details?: string[] } | null;

// ── yardımcılar ──────────────────────────────────────────────
const str = (fd: FormData, k: string) => String(fd.get(k) ?? '').trim();
const optDate = (fd: FormData, k: string) => {
  const v = str(fd, k);
  return /^\d{4}-\d{2}-\d{2}$/.test(v) ? v : null;
};
function optNum(fd: FormData, k: string, { int = false, min = 0, max = 100000 } = {}): number | null | 'invalid' {
  const raw = str(fd, k).replace(/\s/g, '');
  if (raw === '') return null;
  const cleaned = int ? raw.replace(/[.,](?=\d{3}$)/, '') : raw.replace(',', '.');
  const v = Number(cleaned);
  if (!Number.isFinite(v) || v < min || v > max) return 'invalid';
  return int ? Math.round(v) : Math.round(v * 10) / 10;
}
const isUuid = (s: string) => /^[0-9a-f-]{36}$/i.test(s);

function readGoals(fd: FormData) {
  const fields = {
    start_weight: optNum(fd, 'start_weight', { min: 20, max: 400 }),
    goal_weight: optNum(fd, 'goal_weight', { min: 20, max: 400 }),
    calorie_goal: optNum(fd, 'calorie_goal', { int: true, max: 10000 }),
    step_goal: optNum(fd, 'step_goal', { int: true, max: 100000 }),
    protein_goal: optNum(fd, 'protein_goal', { int: true, max: 1000 }),
  };
  const bad = Object.entries(fields).filter(([, v]) => v === 'invalid').map(([k]) => k);
  if (bad.length) return { error: 'Bazı hedef değerleri anlaşılamadı.' as const };
  return {
    values: {
      ...(fields as Record<keyof typeof fields, number | null>),
      start_date: optDate(fd, 'start_date'),
      goal_date: optDate(fd, 'goal_date'),
    },
  };
}

// ── öğrenci ekle (davet e-postası gider) ─────────────────────
export async function createStudent(_prev: FormState, fd: FormData): Promise<FormState> {
  await requireAdmin();
  const email = str(fd, 'email').toLowerCase();
  const fullName = str(fd, 'full_name');
  if (!fullName) return { error: 'Ad soyad gerekli.' };
  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return { error: 'Geçerli bir e-posta yaz.' };
  const goals = readGoals(fd);
  if ('error' in goals) return { error: goals.error };

  const admin = createAdminClient();
  const { data, error } = await admin.auth.admin.inviteUserByEmail(email, {
    data: { full_name: fullName },
    redirectTo: `${process.env.NEXT_PUBLIC_SITE_URL}/auth/confirm`,
  });
  if (error || !data.user) {
    return { error: /already/i.test(error?.message ?? '') ? 'Bu e-posta zaten kayıtlı.' : `Davet gönderilemedi: ${error?.message}` };
  }
  const { error: upErr } = await admin
    .from('profiles')
    .upsert({ id: data.user.id, email, full_name: fullName, role: 'student', ...goals.values });
  if (upErr) return { error: `Profil kaydedilemedi: ${upErr.message}` };

  revalidatePath('/admin');
  return { ok: `${fullName} eklendi, ${email} adresine davet gönderildi.` };
}

// ── hedefleri güncelle ───────────────────────────────────────
export async function updateGoals(_prev: FormState, fd: FormData): Promise<FormState> {
  const { supabase } = await requireAdmin();
  const id = str(fd, 'student_id');
  if (!isUuid(id)) return { error: 'Geçersiz öğrenci.' };
  const goals = readGoals(fd);
  if ('error' in goals) return { error: goals.error };
  const fullName = str(fd, 'full_name');
  const { error } = await supabase
    .from('profiles')
    .update({ ...goals.values, ...(fullName ? { full_name: fullName } : {}) })
    .eq('id', id)
    .eq('role', 'student');
  if (error) return { error: error.message };
  revalidatePath(`/admin/ogrenci/${id}`);
  revalidatePath(`/ogrenci/${id}`);
  return { ok: 'Hedefler kaydedildi.' };
}

// ── tek günlük kayıt ─────────────────────────────────────────
export async function upsertEntry(_prev: FormState, fd: FormData): Promise<FormState> {
  const { supabase } = await requireAdmin();
  const id = str(fd, 'student_id');
  const day = optDate(fd, 'day');
  if (!isUuid(id) || !day) return { error: 'Tarih gerekli.' };
  const vals = {
    weight: optNum(fd, 'weight', { min: 20, max: 400 }),
    steps: optNum(fd, 'steps', { int: true, max: 200000 }),
    calories: optNum(fd, 'calories', { int: true, max: 20000 }),
    protein: optNum(fd, 'protein', { int: true, max: 2000 }),
    fat: optNum(fd, 'fat', { int: true, max: 2000 }),
    carbs: optNum(fd, 'carbs', { int: true, max: 3000 }),
  };
  if (Object.values(vals).includes('invalid')) return { error: 'Bazı değerler anlaşılamadı.' };
  const note = str(fd, 'note') || null;
  if (Object.values(vals).every((v) => v === null) && !note) return { error: 'En az bir değer gir.' };

  const { error } = await supabase
    .from('entries')
    .upsert({ student_id: id, day, ...(vals as Record<string, number | null>), note, updated_at: new Date().toISOString() }, { onConflict: 'student_id,day' });
  if (error) return { error: error.message };
  revalidatePath(`/admin/ogrenci/${id}`);
  revalidatePath(`/ogrenci/${id}`);
  return { ok: `${day} kaydedildi.` };
}

// ── toplu yapıştırma ─────────────────────────────────────────
// Satırda olmayan alanlar mevcut kayıttaki değeri korur (üzerine boş yazılmaz).
export async function bulkImport(_prev: FormState, fd: FormData): Promise<FormState> {
  const { supabase } = await requireAdmin();
  const id = str(fd, 'student_id');
  if (!isUuid(id)) return { error: 'Geçersiz öğrenci.' };
  const { entries, errors } = parseBulk(str(fd, 'text'), todayIstanbul());
  const details = errors.map((e) => `Satır ${e.line}: ${e.reason} — “${e.text.slice(0, 60)}”`);
  if (!entries.length) return { error: 'Kaydedilecek satır bulunamadı.', details };

  const { data: existing } = await supabase
    .from('entries')
    .select('day, weight, steps, calories, protein, fat, carbs, note')
    .eq('student_id', id)
    .in('day', entries.map((e) => e.day));
  const old = new Map((existing ?? []).map((e) => [e.day, e]));
  const now = new Date().toISOString();
  const rows = entries.map((e) => {
    const o = old.get(e.day);
    const pick = <K extends 'weight' | 'steps' | 'calories' | 'protein' | 'fat' | 'carbs' | 'note'>(k: K) => e[k] ?? o?.[k] ?? null;
    return {
      student_id: id, day: e.day, updated_at: now,
      weight: pick('weight'), steps: pick('steps'), calories: pick('calories'),
      protein: pick('protein'), fat: pick('fat'), carbs: pick('carbs'), note: pick('note'),
    };
  });
  const { error } = await supabase.from('entries').upsert(rows, { onConflict: 'student_id,day' });
  if (error) return { error: error.message, details };
  revalidatePath(`/admin/ogrenci/${id}`);
  revalidatePath(`/ogrenci/${id}`);
  const updated = rows.filter((r) => old.has(r.day)).length;
  return {
    ok: `${rows.length} gün kaydedildi (${rows.length - updated} yeni, ${updated} güncellendi).${errors.length ? ` ${errors.length} satır atlandı:` : ''}`,
    details,
  };
}

export async function deleteEntry(fd: FormData) {
  const { supabase } = await requireAdmin();
  const id = str(fd, 'student_id');
  const day = optDate(fd, 'day');
  if (!isUuid(id) || !day) return;
  await supabase.from('entries').delete().eq('student_id', id).eq('day', day);
  revalidatePath(`/admin/ogrenci/${id}`);
  revalidatePath(`/ogrenci/${id}`);
}

// ── fotoğraflar ──────────────────────────────────────────────
const MAX_PHOTO = 10 * 1024 * 1024;
const TYPES: Record<string, string> = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/heic': 'heic' };

export async function uploadPhoto(_prev: FormState, fd: FormData): Promise<FormState> {
  const { supabase } = await requireAdmin();
  const id = str(fd, 'student_id');
  const day = optDate(fd, 'taken_on');
  const file = fd.get('file');
  if (!isUuid(id) || !day) return { error: 'Tarih gerekli.' };
  if (!(file instanceof File) || file.size === 0) return { error: 'Bir fotoğraf seç.' };
  if (file.size > MAX_PHOTO) return { error: 'Fotoğraf 10 MB’tan küçük olmalı.' };
  const ext = TYPES[file.type];
  if (!ext) return { error: 'JPG, PNG veya WEBP yükle.' };
  if (ext === 'heic') return { error: 'HEIC tarayıcıda görünmez. iPhone’da Ayarlar › Kamera › Biçimler › “En Uyumlu” seç ya da JPG olarak paylaş.' };

  const path = `${id}/${day}-${crypto.randomUUID().slice(0, 8)}.${ext}`;
  const { error: upErr } = await supabase.storage.from('photos').upload(path, file, { contentType: file.type, upsert: false });
  if (upErr) return { error: `Yüklenemedi: ${upErr.message}` };
  const { error } = await supabase.from('photos').insert({ student_id: id, taken_on: day, path });
  if (error) {
    await supabase.storage.from('photos').remove([path]);
    return { error: error.message };
  }
  revalidatePath(`/admin/ogrenci/${id}`);
  revalidatePath(`/ogrenci/${id}`);
  return { ok: 'Fotoğraf yüklendi.' };
}

export async function deletePhoto(fd: FormData) {
  const { supabase } = await requireAdmin();
  const id = str(fd, 'student_id');
  const photoId = Number(str(fd, 'photo_id'));
  if (!isUuid(id) || !Number.isInteger(photoId)) return;
  const { data } = await supabase.from('photos').select('path').eq('id', photoId).eq('student_id', id).maybeSingle();
  if (!data) return;
  await supabase.storage.from('photos').remove([data.path]);
  await supabase.from('photos').delete().eq('id', photoId);
  revalidatePath(`/admin/ogrenci/${id}`);
  revalidatePath(`/ogrenci/${id}`);
}
