import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import Swal from 'sweetalert2';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8000/api/v1';

export interface JsonToTypeItem {
  id: number;
  title: string;
  json_data: string;
  type_data: string;
  created_at: string;
  updated_at: string;
}

export interface UseJsonToTypeListReturn {
  items: JsonToTypeItem[];
  isLoading: boolean;
  error: string;
  fetchItems: () => Promise<void>;
  loadItem: (item: JsonToTypeItem) => void;
  downloadJson: (item: JsonToTypeItem) => void;
  downloadType: (item: JsonToTypeItem) => void;
  deleteItem: (id: number) => Promise<void>;
}

export const useJsonToTypeList = (
  onLoad?: (jsonData: string, typeData: string, title: string) => void
): UseJsonToTypeListReturn => {
  const { data: session, status } = useSession();
  const [items, setItems] = useState<JsonToTypeItem[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const fetchItems = async () => {
    if (status !== 'authenticated' || !session) {
      console.log('Kullanıcı authenticated değil');
      return;
    }

    setIsLoading(true);
    setError('');

    try {
      console.log('API çağrısı yapılıyor:', `${API_BASE_URL}/utils/jasontotype/`);
      const response = await fetch(`${API_BASE_URL}/utils/jasontotype/`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${session.accessToken}`,
        },
      });

      console.log('Response status:', response.status);

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        console.error('API Error:', errorData);
        throw new Error(errorData.detail || 'Veriler yüklenirken hata oluştu');
      }

      const data = await response.json();
      console.log('Gelen kayıt sayısı:', data.length);
      console.log('Kayıtlar:', data);
      setItems(Array.isArray(data) ? data : []);
    } catch (err) {
      console.error('Fetch error:', err);
      setError((err as Error).message);
      Swal.fire({
        icon: 'error',
        title: 'Hata',
        text: (err as Error).message,
        confirmButtonText: 'Tamam',
      });
    } finally {
      setIsLoading(false);
    }
  };

  // İlk yüklemede kayıtları getir
  useEffect(() => {
    if (status === 'authenticated') {
      fetchItems();
    }
  }, [status]);

  const loadItem = (item: JsonToTypeItem) => {
    if (onLoad) {
      onLoad(item.json_data, item.type_data, item.title);
    }

    Swal.fire({
      toast: true,
      position: 'top-end',
      icon: 'success',
      title: 'Kayıt yüklendi!',
      showConfirmButton: false,
      timer: 1500,
    });
  };

  const downloadJson = (item: JsonToTypeItem) => {
    const blob = new Blob([item.json_data], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${item.title.replace(/\s+/g, '_')}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    Swal.fire({
      toast: true,
      position: 'top-end',
      icon: 'success',
      title: 'JSON indirildi!',
      showConfirmButton: false,
      timer: 1500,
    });
  };

  const downloadType = (item: JsonToTypeItem) => {
    const blob = new Blob([item.type_data], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${item.title.replace(/\s+/g, '_')}.ts`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    Swal.fire({
      toast: true,
      position: 'top-end',
      icon: 'success',
      title: 'TypeScript indirildi!',
      showConfirmButton: false,
      timer: 1500,
    });
  };

  const deleteItem = async (id: number) => {
    const result = await Swal.fire({
      icon: 'warning',
      title: 'Emin misiniz?',
      text: 'Bu kaydı silmek istediğinizden emin misiniz?',
      showCancelButton: true,
      confirmButtonText: 'Evet, Sil',
      cancelButtonText: 'İptal',
      confirmButtonColor: '#d33',
    });

    if (!result.isConfirmed) {
      return;
    }

    try {
      const response = await fetch(`${API_BASE_URL}/utils/jasontotype/${id}/`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${session?.accessToken}`,
        },
      });

      if (!response.ok) {
        throw new Error('Silme işlemi başarısız');
      }

      setItems(items.filter(item => item.id !== id));

      Swal.fire({
        icon: 'success',
        title: 'Silindi!',
        text: 'Kayıt başarıyla silindi',
        timer: 1500,
        showConfirmButton: false,
      });
    } catch (err) {
      Swal.fire({
        icon: 'error',
        title: 'Hata',
        text: (err as Error).message,
        confirmButtonText: 'Tamam',
      });
    }
  };

  return {
    items,
    isLoading,
    error,
    fetchItems,
    loadItem,
    downloadJson,
    downloadType,
    deleteItem,
  };
};

