/**
 * usePostiz — Postiz API Integration
 * 
 * API Base: https://postiz.atlas-os.ai
 * Auth: Bearer token (JWT) after login
 * Org API Key: 51a341904d7ae5c676d47761c347dd17caa6aef5be5511d25cbb7566624d1da7
 */

import { useState, useEffect, useCallback } from 'react';

const POSTIZ_API = 'https://postiz.atlas-os.ai';
const ORG_API_KEY = '51a341904d7ae5c676d47761c347dd17caa6aef5be5511d25cbb7566624d1da7';

export interface PostizPost {
  id: string;
  content: string;
  status: 'DRAFT' | 'QUEUE' | 'PUBLISHED' | 'ERROR';
  publishDate?: string;
  integration?: {
    id: string;
    name: string;
    type: string;
  };
  createdAt: string;
  updatedAt: string;
}

export interface PostizIntegration {
  id: string;
  name: string;
  type: string;
  disabled: boolean;
  picture?: string;
}

export interface PostizStats {
  postsToday: number;
  postsThisWeek: number;
  drafts: number;
  scheduled: number;
  published: number;
  channels: number;
}

let authToken: string | null = null;

async function getAuthToken(): Promise<string | null> {
  if (authToken) return authToken;
  
  try {
    const res = await fetch(`${POSTIZ_API}/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: 'hiss@clara360.de',
        password: 'Atlas68!',
        provider: 'LOCAL',
      }),
    });
    
    if (!res.ok) return null;
    const data = await res.json();
    authToken = data.token || data.access_token || null;
    return authToken;
  } catch {
    return null;
  }
}

async function postizFetch(path: string, options?: RequestInit) {
  const token = await getAuthToken();
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    'x-org-id': ORG_API_KEY,
  };
  
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  
  return fetch(`${POSTIZ_API}${path}`, {
    ...options,
    headers: { ...headers, ...(options?.headers || {}) },
  });
}

export function usePostizPosts() {
  const [posts, setPosts] = useState<PostizPost[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchPosts = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await postizFetch('/posts');
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      setPosts(Array.isArray(data) ? data : data.posts || data.data || []);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler beim Laden');
      // Use mock data as fallback
      setPosts(getMockPosts());
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchPosts();
  }, [fetchPosts]);

  return { posts, loading, error, refetch: fetchPosts };
}

export function usePostizIntegrations() {
  const [integrations, setIntegrations] = useState<PostizIntegration[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    postizFetch('/integrations')
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (data) {
          setIntegrations(Array.isArray(data) ? data : data.integrations || []);
        }
      })
      .catch(() => setIntegrations([]))
      .finally(() => setLoading(false));
  }, []);

  return { integrations, loading };
}

export function usePostizStats(): PostizStats {
  const { posts } = usePostizPosts();
  const { integrations } = usePostizIntegrations();
  
  const today = new Date().toDateString();
  
  return {
    postsToday: posts.filter(p => 
      p.publishDate && new Date(p.publishDate).toDateString() === today
    ).length,
    postsThisWeek: posts.filter(p => {
      if (!p.publishDate) return false;
      const d = new Date(p.publishDate);
      const now = new Date();
      const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      return d >= weekAgo && d <= now;
    }).length,
    drafts: posts.filter(p => p.status === 'DRAFT').length,
    scheduled: posts.filter(p => p.status === 'QUEUE').length,
    published: posts.filter(p => p.status === 'PUBLISHED').length,
    channels: integrations.filter(i => !i.disabled).length,
  };
}

export async function createPostizDraft(content: string, integrationIds?: string[]) {
  const res = await postizFetch('/posts', {
    method: 'POST',
    body: JSON.stringify({
      content,
      status: 'DRAFT',
      integrations: integrationIds || [],
    }),
  });
  
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

export async function schedulePostizPost(postId: string, publishDate: string) {
  const res = await postizFetch(`/posts/${postId}`, {
    method: 'PUT',
    body: JSON.stringify({
      status: 'QUEUE',
      publishDate,
    }),
  });
  
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

// Mock data for development/fallback
function getMockPosts(): PostizPost[] {
  return [
    {
      id: 'mock-1',
      content: '🔌 Shelly Plus Plug S — Smart Home Energiekontrolle. Jetzt mit 15% Rabatt über unseren Affiliate-Link. #SmartHome #Energie #Affiliate',
      status: 'DRAFT',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    },
    {
      id: 'mock-2',
      content: 'ATLAS OS Update: Neue Features für Creator. Mehr Kontrolle, mehr Umsatz. #ATLASОС #Creator',
      status: 'QUEUE',
      publishDate: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(),
      createdAt: new Date(Date.now() - 3600000).toISOString(),
      updatedAt: new Date(Date.now() - 3600000).toISOString(),
    },
    {
      id: 'mock-3',
      content: 'Smart Home im Test: 5 Geräte, die sich wirklich lohnen. Link in Bio.',
      status: 'PUBLISHED',
      publishDate: new Date(Date.now() - 86400000).toISOString(),
      createdAt: new Date(Date.now() - 90000000).toISOString(),
      updatedAt: new Date(Date.now() - 86400000).toISOString(),
    },
  ];
}
